<?php

/****************************************
 Functions
 
 These are functions used by ../index.php
 
 
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
   
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
   
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

********************************/

// this function is a weird hack to remove the extra single quotes that appear around the database name as soon as we edit an entry or do something else except staring at the login screen. This function will be obsolete as soon as some gentle soul explains to me which f***ing PHP "feature" inserts those single quotes (MH)
function stripQuotes($string) {
  // brute force, does not care about escaping and such. Used only for database names which must not contain quotes anyway (MH)
  return trim(str_replace("'", " ", $string));
}

// this is a somewhat more intelligent "which" replacement. It checks whether a binary is available in the default path, or if not found, whether it is available in the same directory as the refdb binaries. The latter check helps on those systems which use an empty PATH in Apache's account for security reasons. Returns a string to call the tool if it is available, or NULL if not
function nwhich($name) {
  $path = $_SESSION["path"];
  exec("which $name", $dummy, $retval);
  if ($retval == 1) {
    exec("which $path/$name", $dummy, $retval);
    if ($retval == 0) {
      return "$path/$name";
    }
  }
  else {
    return $name;
  }

  return NULL;
}

//This function sets the proper search tag depending
//on the field that you're searching for
function selectTag($kajqueryfield) {
  $get="";
  switch($kajqueryfield) {
  case "keyword":
    $get="KW";
    break;
  case "author":
    $get="AU";
    break;
  case "editor":
    $get="ED";
    break;
  case "seditor":
    $get="A2";
    break;
  case "journalfull":
    $get="JF";
    break;
  case "journalabbrev":
    $get="JO";
    break;
  case "journalabbrev1":
    $get="J1";
    break;
  case "journalabbrev2":
    $get="J2";
    break;
  }
  return ":".$get.":";
}

function refdb_xhtml2out($lines, $buttons=false) {
  //Establish initial checkbox number.
  $checkboxNumber=0;

  foreach( $lines as $line ) {
    //Remove title and ending
    if( substr($line,1,2)=="h1"
	|| substr($line,1,4)=="?xml"
	|| substr($line,1,4)=="!DOC"
	|| substr($line,1,4)=="html"
	|| substr($line,1,5)=="title"
	|| substr($line,1,5)=="/head"
	|| substr($line,1,4)=="body"
	|| substr($line,1,5)=="/html") {
      //do nothing	
    }
    //If this is the first line of a new reference it will contain the ID field
    elseif( substr($line,1,2)=="h2" ) {
      //strip the ID number out of the reference
      $colon=strpos($line, ':');
      $space=strpos($line, " (");
      $id=substr($line,$colon+1,$space-$colon-1);	
      if($buttons) {
	++$checkboxNumber;
	echo "<p><button type='submit' name='sendQuery' value='edit.$id'>Edit this entry</button>";
	echo "&#x00A0;<button type='submit' name='sendQuery' value='delete.$id'>Delete this entry</button>";
	echo "&#x00A0;<button type='submit' name='sendQuery' value='display.$id'>Display as</button>";
	echo "&#x00A0;<select name='format'><option value='ris'>RIS</option><option value='risx'>risx</option><option value='mods'>MODS</option></select></p>";
	// echo "<p><input type='checkbox' name='checkbox' value='$id'/></p>\n";
      }
      echo "$line\n";
    }
    else {
      //Here seems to be a bug in refdbc: missing </div>
      $line = str_replace("</p><div", "</p></div><div", "$line\n");
      $line = str_replace("</p></body>", "</p></div>", "$line\n");
      print $line;
    }

  }
  return $checkboxNumber;
}


function risx_xhtmlprocessor ($lines,$buttons) {

  // foreach ($lines as $line) {
  // echo "<pre>$line</pre>";
  // }

  if ($lines) {
    $output=implode("\n",$lines);

    $xml = new DOMDocument;
    $xml->loadXML($output);

    $xsl = new DOMDocument;

    if ($buttons=="true") {
      $xsl->load('xsl/refdb-entry-structure-buttons.xsl');
    }
    else {
      $xsl->load('xsl/refdb-entry-structure.xsl');
    }

    // Configure the transformer
    $proc = new XSLTProcessor;
    $proc->registerPHPFunctions();
    $proc->importStyleSheet($xsl); // attach the xsl rules

    echo $proc->transformToXML($xml);
  }

} 

// New version

function refdb_RIS2out($lines, $buttons=false) {
  //Establish initial checkbox number.
  $checkboxNumber=0;

  /* 
   // Load the XML source
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules

echo $proc->transformToXML($xml);

  */




  foreach( $lines as $line ) {
    //If this is the first line of a new reference it will contain the TY field
    if( substr($line,1,2)=="TY" ) {
      //strip the ID number out of the reference
      $ID=substr($line,6);
      if($buttons) {
	++$checkboxNumber;
	echo "<p><button type='submit' name='sendQuery' value='edit.$id'>Edit this entry</button>";
	echo "&#x00A0;<button type='submit' name='sendQuery' value='delete.$id'>Delete this entry</button>";
	echo "&#x00A0;<button type='submit' name='sendQuery' value='display.$id'>Display as</button>";
	echo "&#x00A0;<select name='format'><option value='ris'>RIS</option><option value='risx'>risx</option><option value='mods'>MODS</option></select></p>";
	// echo "<p><input type='checkbox' name='checkbox' value='$ID'/></p>\n";
      }
    }
    $formfields=parseRSS ($lines);
    //extract($output,EXTR_OVERWRITE);
    $referencetype = $formfields['TY'];
    if ($referencetype=="ABST") {}
    elseif ($referencetype=="ADVS") {}
    elseif ($referencetype=="ART") {}
    elseif ($referencetype=="BILL") {}
    elseif ($referencetype=="UNBILL") {}
    elseif ($referencetype=="CHAP") {
      echo 
	"<p>".$formfields['AI']. $formfields['PY'];
      if ($formy2!="") {
	echo "[$formy2]";
      }
      echo  $formfields['TI'];
      echo "In ".$formfields['A2']."; (ed.), ";
      if ($formfields['T2']!="") {
	echo "<u>".$formfields['T2']."</u>";
      }
      elseif ($formfields['BT']!="") {
	echo "<u>".$formfields['BT']."</u>";                                
      }
      echo ": ".$formfields['SP']."-".$formfields['EP'].".</p>\n";                                
    }
    elseif ($referencetype=="BOOK") {      
      echo"<p>".$formfields['AI'].". ".$formfields['PY'];
      if ($formy2!="") {
	echo "[$formy2]";
      }
      echo ". ";
      if ($formfields['TI']!="") {
	echo "<u>".$formfields['TI']."</u>";
      }
      elseif ($formfields['BT']!="") {
	echo "<u>".$formfields['BT']."</u>";                                
      }
      echo ".</p>\n";
    }
    elseif ($referencetype=="SER") {}
    elseif ($referencetype=="THES") {}
    elseif ($referencetype=="CTLG") {}
    elseif ($referencetype=="COMP") {}
    elseif ($referencetype=="CONF") {}
    elseif ($referencetype=="DATA") {}
    elseif ($referencetype=="ICOM") {}
    elseif ($referencetype=="GEN") {}
    elseif ($referencetype=="HEAR") {}
    elseif ($referencetype=="INPR") {}
    elseif ($referencetype=="JOUR") {
      echo"<p>".$formfields['AI'].". ".$formfields['PY']."";
      if ($formfields['Y2']!="") {
	echo "[".$formfields['Y2'];
      }
      echo ". ".$formfields['TI'].". ";
      if ($formfields['JO']!="") {
	echo "<u>".$formfields['JO']."</u>";
      }
      elseif ($formfields['J1']!="") {
	echo "<u>".$formfields['J1']."</u>";                                
      }
      elseif ($formfields['J2']!="") {
	echo "<u>".$formfields['J2']."</u>";                                
      }                                
      else {
	echo "<u>".$formfields['JF']."</u>";                                
      }                                
      echo " ".$formfields['VL']."";
      if ($formfields['IS']!="") {
	echo ".".$formfields['IS']."";
      }
      echo ": ".$formfields['SP']."-".$formfields['EP'].".</p>\n";
    }
    elseif ($referencetype=="JFULL") {}
    elseif ($referencetype=="CASE") {}
    elseif ($referencetype=="MGZN") {}
    elseif ($referencetype=="MAP") {}
    elseif ($referencetype=="MPCT") {}
    elseif ($referencetype=="MUSIC") {}
    elseif ($referencetype=="NEWS") {}
    elseif ($referencetype=="PAMP") {}
    elseif ($referencetype=="PAT") {}
    elseif ($referencetype=="PCOMM") {}
    elseif ($referencetype=="RPRT") {}
    elseif ($referencetype=="SLIDE") {}
    elseif ($referencetype=="SOUND") {}
    elseif ($referencetype=="STAT") {}
    elseif ($referencetype=="UNPB") {}
    elseif ($referencetype=="VIDEO") {}
    elseif ($referencetype=="ELEC") {}
    else {
      //Here seems to be a bug in refdbc: missing </div>
      $line = str_replace("</p><div", "</p></div><div", "$line\n");
      $line = str_replace("</p></body>", "</p></div>", "$line\n");
      print $line;
    }
    return $checkboxNumber;
  }
}

/*
    This function imports an "arbitrary" file into
    the database by sending it to various functions
    which return true if they recognize the file type.
    This corresponds to the STRATEGY design pattern
    Problem to solve: differing encodings
    EndNote RIS is currently disabled as we can't distinguish
    it from "good" RIS
*/
function importFile($infile, $my_refdbc) {
  echo "<p> File to import: $infile</p>";
  if(   importRIS($infile, $my_refdbc)
	|| importrisx($infile, $my_refdbc)
	|| importISI($infile, $my_refdbc)
	|| importBibTeX($infile, $my_refdbc)
	//	|| importEndNote($infile, $my_refdbc)
	|| importMarc($infile, $my_refdbc)
	|| importPubmed($infile, $my_refdbc)
	|| importCopac($infile, $my_refdbc)
	)
    print("<p> File successfully imported");
  else
    print("Not recognized File $infile with first line".
	  getFirstline($infile, NULL));
}
/**
 	This function imports a web of science export file
	into the database by converting it to ris and then
	calling the importRIS function
*/
function importBibTeX($infile, $my_refdbc) {
  // check our prerequisites
  $bib2ris = nwhich("bib2ris-utf8");
  if (is_null($bib2ris)) {
    return false;
  }

  if(substr(getFirstline($infile, "%"),0,1)=="@"){
    //print("<p> Recognized BibTeX </p>");
    $tempFile=tempnam("/tmp", "refdb"); // make sure filename is unique
    $cmd="$bib2ris $infile > $tempFile";
    $lines = "";
    exec($cmd,$lines);
    $retval = importRIS($tempFile, $my_refdbc);
    unlink($tempFile); // clean up
    return $retval;
  } 
  return false;
}

function importEndNote($infile, $my_refdbc) {
  // check our prerequisites
  $en2ris = nwhich("en2ris");
  if (is_null($en2ris)) {
    return false;
  }

  if(substr(getFirstline($infile, NULL),0,6)=="TY  - "){
    //print("<p> Recognized EndNote </p>");
    $tempFile=tempnam("/tmp", "refdb"); // make sure filename is unique
    $cmd="$en2ris < $infile > $tempFile";
    $lines = "";
    exec($cmd,$lines);
    $retval = importRIS($tempFile, $my_refdbc);
    unlink($tempFile); // clean up
    return $retval;
  } 
  return false;
}

function importMarc($infile, $my_refdbc) {
  // check our prerequisites
  $marc2ris = nwhich("marc2ris");
  if (is_null($marc2ris)) {
    return false;
  }

  $header = getFirstline($infile, NULL);
  if ($header == false) {
    return false;
  }

  // the following regex is supposed to match all MARC21 datasets,
  // see http://www.loc.gov/marc/specifications/specrecstruc.html
  if(ereg('^..........22........4500', $header)){
    //print("<p> Recognized MARC21 </p>");
    $tempFile=tempnam("/tmp", "refdb"); // make sure filename is unique
    $cmd="$marc2ris -t MARC21 < $infile > $tempFile";
    $lines = "";
    exec($cmd,$lines);
    $retval = importRIS($tempFile, $my_refdbc);
    unlink($tempFile); // clean up
    return $retval;
  }
  // the following regex is supposed to match all UNIMARC datasets,
  // see http://www.ifla.org/VI/3/p1996-1/uni.htm
  else if(ereg('^......... 22....... 450 ', $header)){
    //print("<p> Recognized UNIMARC </p>");
    $tempFile=tempnam("/tmp", "refdb"); // make sure filename is unique
    $cmd="$marc2ris -t UNIMARC < $infile > $tempFile";
    $lines = "";
    exec($cmd,$lines);
    $retval = importRIS($tempFile, $my_refdbc);
    unlink($tempFile); // clean up
    return $retval;
  }

  return false;
}

function importPubmed($infile, $my_refdbc) {
  // check our prerequisites
  $med2ris = nwhich("med2ris");
  if (is_null($med2ris)) {
    return false;
  }

  $header = getFirstline($infile, "<?");
  if ($header == false) {
    return false;
  }
  
  // first try Pubmed XML format
  // catches both PubmedArticle and PubmedArticleSet
  if(substr($header,0,23)=="<!DOCTYPE PubmedArticle"
     || substr($header,0,14) == "<PubmedArticle"){
    //print("<p> Recognized Pubmed XML </p>");
    $tempFile=tempnam("/tmp", "refdb"); // make sure filename is unique
    $cmd="$med2ris -T xml < $infile > $tempFile";
    $lines = "";
    exec($cmd,$lines);
    $retval = importRIS($tempFile, $my_refdbc);
    unlink($tempFile); // clean up
    return $retval;
  }
  // now try tagged format
  else if (substr($header,0,6) == "PMID- ") {
    //print("<p> Recognized Pubmed tagged </p>");
    $tempFile=tempnam("/tmp", "refdb"); // make sure filename is unique
    $cmd="$med2ris -T tag < $infile > $tempFile";
    $lines = "";
    exec($cmd,$lines);
    $retval = importRIS($tempFile, $my_refdbc);
    unlink($tempFile); // clean up
    return $retval;
  }

  return false;
}

function importISI($infile, $my_refdbc){
  // check our prerequisites
  $isi2xml = nwhich("isi2xml");
  if (is_null($isi2xml)) {
    return false;
  }
  $xml2ris = nwhich("xml2ris");
  if (is_null($xml2ris)) {
    return false;
  }

  $header = getFirstline($infile, NULL);
  if ($header == false) {
    return false;
  }

  if(substr($header,0,20)=="FN ISI Export Format"){
    //print("<p> Recognized ISI Export </p>");
    $tempFile=tempnam("/tmp", "refdb"); // make sure filename is unique
    $cmd="$isi2xml $infile | $xml2ris > $tempFile";
    $lines = "";
    exec($cmd,$lines);
    /*
		echo "<p> $cmd returned <br>";

		foreach ($lines as $line) {
			echo "$line<br/>";
		}
		echo "</p>";
    */

    return importRIS($tempFile, $my_refdbc);
    unlink($tempFile); // clean up
  } 
  return false;
}

function importCopac($infile, $my_refdbc){
  // check our prerequisites
  $copac2xml = nwhich("copac2xml");
  if (is_null($copac2xml)) {
    return false;
  }
  $xml2ris = nwhich("xml2ris");
  if (is_null($xml2ris)) {
    return false;
  }

  $header = getFirstline($infile, NULL);
  if ($header == false) {
    return false;
  }

  // as per the spec at http://copac.ac.uk/faq/, all datasets start with
  // a "TI- " tag, but their own exported records speak a different language
  // all seem to start with a "AU- " tag. Test for both variants
  if(substr($header,0,4) == "TI- "
     || substr($header,0,4) == "AU- "){
    //print("<p> Recognized COPAC </p>");
    $tempFile=tempnam("/tmp", "refdb"); // make sure filename is unique
    $cmd="$copac2xml $infile | $xml2ris > $tempFile";
    $lines = "";
    exec($cmd,$lines);
    return importRIS($tempFile, $my_refdbc);
    unlink($tempFile); // clean up
  } 
  return false;
}

/**
 	This function imports a RIS-file into the database.
*/
function importRIS($infile, $my_refdbc) {
  $lines = array(); // initialize as empty array

  if (substr(getFirstline($infile, NULL),0,6)=="TY  - ") {
    //echo "<p>Recognized RIS</p>";
    $returnvalue = 0;
    $lines = $my_refdbc->addref_from_file("", $infile, "ris", "");
    //Debugging
    //                echo "<p> return value: $returnvalue <br/> $cmd returned <br/>";
    //foreach ($lines as $line) {
    //  echo "$line<br/>";}
    //end debugging
  }
  echo "</p>";

  $num_success = 0;
  $num_failed = 0;
  $my_citekey = "";


  foreach ($lines as $line) {
    $resultfields = explode(':', $line);
    $status = $resultfields[0];

    if ($status == "406") {
      $my_citekey = $resultfields[2];
      //      echo "<p>Created citation key $citekey</p>";
    }
    else if ($status == "407") {
      // urlencoding $citekey should not be required as refdbd strips off offending characters anyway
      if (isset($resultfields[2])) {
	$citekey = $resultfields[2];
	echo "<p>Refused to overwrite dataset with citation key <a href=\"index.php?thisPage=Search%20results&query=:CK:%3d$citekey\">$citekey</a></p>";
      }
    }
    else if ($status == "408") {
      echo "<p>Successfully added <a href=\"index.php?thisPage=Search%20results&query=:CK:%3d$my_citekey\">$my_citekey</a></p>";
      $num_success++;
    }
    else if ($status == "409") {
      echo "<p>Numerical ID ignored</p>";
    }
    else if ($status == "410") {
      echo "<p>Numerical ID noexistent</p>";
    }
    else if ($status == "411") {
      echo "<p>Citation key noexistent</p>";
    }
    else if ($status == "412") {
      echo "<p>ID or citation key are missing</p>";
    }
    else if ($status == "413") {
      $citekey = $resultfields[2];
      echo "<p>Successfully updated dataset with citation key <a href=\"index.php?thisPage=Search%20results&query=:CK:%3d$citekey\">$citekey</a></p>";
      $num_success++;
    }
    else if ($status == "414") {
      echo "<p style=\"color:red\">Failed to add dataset</p>";
      $num_failed++;
    }
  }

  if ($num_success > 0) {
    return true;
  }
		
  return false;
}

function importrisx($infile, $my_refdbc) {
  $my_firstline = getFirstline($infile, NULL);
  $lines = array(); // initialize as empty array

  if (substr($my_firstline, 0, 5) == "<?xml"
      || substr($my_firstline, 0, 14) == "<!DOCTYPE ris "
      || substr($my_firstline, 0, 5) == "<ris>") {
    //echo "<p>Recognized risx</p>";
    $returnvalue = 0;
    $lines = $my_refdbc->addref_from_file("", $infile, "risx", "");
    //Debugging
    //                echo "<p> return value: $returnvalue <br/> $cmd returned <br/>";
    //                foreach ($lines as $line) {
    //		      echo "$line<br/>";}
    //end debugging
  }
  echo "</p>";

  $num_success = 0;
  $num_failed = 0;
  $my_citekey = "";

  foreach ($lines as $line) {
    $resultfields = explode(':', $line);
    $status = $resultfields[0];

    if ($status == "406") {
      $my_citekey = $resultfields[1];
      //      echo "<p>Created citation key $citekey</p>";
    }
    else if ($status == "407") {
      if (isset($resultfields[2])) {
	$citekey = $resultfields[2];
	echo "<p>Refused to overwrite dataset with citation key <a href=\"index.php?thisPage=Search%20results&query=:CK:%3d$citekey\">$citekey</a></p>";
      }
    }
    else if ($status == "408") {
      echo "<p>Successfully added <a href=\"index.php?thisPage=Search%20results&query=:CK:%3d$my_citekey\">$my_citekey</a></p>";
      $num_success++;
    }
    else if ($status == "409") {
      echo "<p>Numerical ID ignored</p>";
    }
    else if ($status == "410") {
      echo "<p>Numerical ID noexistent</p>";
    }
    else if ($status == "411") {
      echo "<p>Citation key noexistent</p>";
    }
    else if ($status == "412") {
      echo "<p>ID or citation key are missing</p>";
    }
    else if ($status == "413") {
      $citekey = $resultfields[1];
      echo "<p>Successfully updated dataset with citation key <a href=\"index.php?thisPage=Search%20results&query=:CK:%3d$citekey\">$citekey</a></p>";
      $num_success++;
    }
    else if ($status == "414") {
      echo "<p style=\"color:red\">Failed to add dataset</p>";
      $num_failed++;
    }
  }

  if ($num_success > 0) {
    return true;
  }
		
  return false;
}

// todo: import from endnote, copac, endnote xml, bibtex, marc, pubmed

function getFirstline($infile, $commentstring) {
  $maxlength = 64;// the length limit avoids reading entire
                  // MARC files into memory
  $inunit=fopen($infile,"r");
  if(!$inunit) {
    die("Couldn't open existing input file '".$infile."'."."\n");
  }

  /* skip leading empty lines, if any, and ignore commented out lines */
  /* use two loops to avoid checking string lengths in the loop */
  if (!is_null($commentstring)) {
    do {
      $inline=fgets($inunit, $maxlength);
      if (strncmp($inline, $commentstring, strlen($commentstring)) == 0) {
	continue;
      }
      $trimmedline = trim($inline);
    } while (strlen($trimmedline) == 0);
  }
  else {
    do {
      $inline=fgets($inunit, $maxlength);
      $trimmedline = trim($inline);
    } while (strlen($trimmedline) == 0);
  }

  fclose ($inunit);
  return $inline;
}


/*
    Creates the reference type selection element
    for the input form. $reference is the preselected type.
*/
function form_selection($referencetype) {
  ?>
 <select name="formTY" onchange="this.form.submit();">
    <option value="none"<?php if ($referencetype=="") {echo " selected=\"selected\"";} ?>>Choose bibliographic type</option>
											    <option value="CHAPshort"<?php if ($referencetype=="CHAPshort") {echo " selected=\"selected\"";} ?>>Book Chapter (Short form)</option>
																								  <option value="BOOKshort"<?php if ($referencetype=="BOOKshort") {echo " selected=\"selected\"";} ?>>Book, Whole (Short form)</option>
																																					<option value="JOURshort"<?php if ($referencetype=="JOURshort") {echo " selected=\"selected\"";} ?>>Journal Article (Short form)</option>
																																																	      <option value="JFULL"<?php if ($referencetype=="JFULL") {echo " selected=\"selected\"";} ?>>Journal (Whole)</option>
																																																													    <option value="ELEC"<?php if ($referencetype=="ELEC") {echo " selected=\"selected\"";} ?>>Web page</option>
																																																																									<option value="">----</option>
																																																																									<option value="ABST"<?php if ($referencetype=="ABST") {echo " selected=\"selected\"";} ?>>Abstract</option>
																																																																																				    <option value="ADVS"<?php if ($referencetype=="ADVS") {echo " selected=\"selected\"";} ?>>Audio visual mat'l</option>
                    <option value="ART"<?php if ($referencetype=="ART") {echo " selected=\"selected\"";} ?>>Artwork</option>
                    <option value="BILL"<?php if ($referencetype=="BILL") {echo " selected=\"selected\"";} ?>>Bill/resolution (enacted)</option>
                    <option value="UNBILL"<?php if ($referencetype=="UNBILL") {echo " selected=\"selected\"";} ?>>Bill/resolution (unenacted)</option>
                    <option value="CHAP"<?php if ($referencetype=="CHAP") {echo " selected=\"selected\"";} ?>>Book Chapter (Long form)</option>
                    <option value="BOOK"<?php if ($referencetype=="BOOK") {echo " selected=\"selected\"";} ?>>Book, Whole (Long form)</option>
                    <option value="SER"<?php if ($referencetype=="SER") {echo " selected=\"selected\"";} ?>>Book Series (i.e. whole series)</option>
                    <option value="THES"<?php if ($referencetype=="THES") {echo " selected=\"selected\"";} ?>>Dissertation/Thesis</option>
                    <option value="CTLG"<?php if ($referencetype=="CTLG") {echo " selected=\"selected\"";} ?>>Catalogue</option>
                    <option value="COMP"<?php if ($referencetype=="COMP") {echo " selected=\"selected\"";} ?>>Computer program</option>
                    <option value="CONF"<?php if ($referencetype=="CONF") {echo " selected=\"selected\"";} ?>>Conference proceeding</option>
                    <option value="DATA"<?php if ($referencetype=="DATA") {echo " selected=\"selected\"";} ?>>Data file</option>
                    <option value="ICOMM"<?php if ($referencetype=="ICOM") {echo " selected=\"selected\"";} ?>>E-mail</option>
                    <option value="GEN"<?php if ($referencetype=="GEN") {echo " selected=\"selected\"";} ?>>Generic/Unclassified</option>
                    <option value="HEAR"<?php if ($referencetype=="HEAR") {echo " selected=\"selected\"";} ?>>Hearing</option>
                    <option value="INPR"<?php if ($referencetype=="INPR") {echo " selected=\"selected\"";} ?>>In-press</option>
                    <option value="JOUR"<?php if ($referencetype=="JOUR") {echo " selected=\"selected\"";} ?>>Journal Article (Long form)</option>
                    <option value="JFULL">Journal (Whole)</option>
                    <option value="CASE"<?php if ($referencetype=="CASE") {echo " selected=\"selected\"";} ?>>Legal case</option>
                    <option value="MGZN"<?php if ($referencetype=="MGZN") {echo " selected=\"selected\"";} ?>>Magazine article</option>
                    <option value="MAP"<?php if ($referencetype=="MAP") {echo " selected=\"selected\"";} ?>>Map</option>
                    <option value="MPCT"<?php if ($referencetype=="MPCT") {echo " selected=\"selected\"";} ?>>Motion picture</option>
                    <option value="MUSIC"<?php if ($referencetype=="MUSIC") {echo " selected=\"selected\"";} ?>>Music score</option>
                    <option value="NEWS"<?php if ($referencetype=="NEWS") {echo " selected=\"selected\"";} ?>>Newspaper article</option>
                    <option value="PAMP"<?php if ($referencetype=="PAMP") {echo " selected=\"selected\"";} ?>>Pamphlet</option>
                    <option value="PAT"<?php if ($referencetype=="PAT") {echo " selected=\"selected\"";} ?>>Patent</option>
                    <option value="PCOMM"<?php if ($referencetype=="PCOMM") {echo " selected=\"selected\"";} ?>>Personal communication</option>
                    <option value="RPRT"<?php if ($referencetype=="RPRT") {echo " selected=\"selected\"";} ?>>Report</option>
                    <option value="SLIDE"<?php if ($referencetype=="SLIDE") {echo " selected=\"selected\"";} ?>>Slide</option>
                    <option value="SOUND"<?php if ($referencetype=="SOUND") {echo " selected=\"selected\"";} ?>>Sound recording</option>
                    <option value="STAT"<?php if ($referencetype=="STAT") {echo " selected=\"selected\"";} ?>>Statue</option>
                    <option value="UNPB"<?php if ($referencetype=="UNPB") {echo " selected=\"selected\"";} ?>>Unpublished work</option>
                    <option value="VIDEO"<?php if ($referencetype=="VIDEO") {echo " selected=\"selected\"";} ?>>Video recording</option>    
                    <option value="ELEC">Web page</option>
                </select>
            <?php
        }
    /**
    Returns the Text for the primary
    title or author depending on the reference type
    */
        function  generateFormPart($ref_type,$field, $default) {
			//print("<p> generateFormPart($ref_type, $field)</p>");
			//var_dump($default);
			

	      		//print("<p>".substr($field,0,4)."  ".substr($field,4)."</p>"); 
	      //First work on sections
	      if(substr($field,0,4)=="sec_"){
	      		$field = substr($field,4);

	      		$headings=array("primary" => "Primary Author, Title, and Date", 
					"secondary" => "Secondary Information",
					"tertiary" => "Tertiary Author, Title",
					"publication" => "Publication Information",
					"shelf" => "Shelfing/Location Information"
					);
			$heading = $headings[$field];
			//For the first section
			//we must not include closing tags
			if($field=="primary"){
			} else {
			    echo "                    </table>\n";
			    echo "                </div>\n";
			}
			echo "                <div id=\"".$field."\" class=\"bibliographicform\">\n";
			echo "                    <h3>".$heading."</h3>\n";
			echo "                    <table>\n";


	      //Now process actual fields
	      } else {
// set the M1-M3 field labels according to the reference type
if ($ref_type == "ABST") {
  $m1label = "Miscellaneous field 1 (n/a)";
  $m2label = "Miscellaneous field 1 (n/a)";
  $m3label = "DOI";
}
else if ($ref_type == "ART") {
  $m1label = "Type of work";
  $m2label = "Miscellaneous field 2 (n/a)";
  $m3label = "DOI";
}
else if ($ref_type == "ADVS") {
  $m1label = "Miscellaneous field 1 (n/a)";
  $m2label = "DOI";
  $m3label = "Media type";
}
else if ($ref_type == "BILL") {
  $m1label = "Miscellaneous field 1 (n/a)";
  $m2label = "Miscellaneous field 2 (n/a)";
  $m3label = "DOI";
}
else if ($ref_type == "CHAP" || $ref_type == "CHAPshort") {
  $m1label = "Number of volumes";
  $m2label = "Volume";
  $m3label = "DOI";
}
else if ($ref_type == "BOOK" || $ref_type == "BOOKshort") {
  $m1label = "Number of volumes";
  $m2label = "Miscellaneous field 2 (n/a)";
  $m3label = "DOI";
}
else if ($ref_type == "CTLG") {
  $m1label = "Miscellaneous field 1 (n/a)";
  $m2label = "Miscellaneous field 2 (n/a)";
  $m3label = "DOI";
}
else if ($ref_type == "COMP") {
  $m1label = "Computer";
  $m2label = "Operating system type";
  $m3label = "Media type";
}
else if ($ref_type == "CONF") {
  $m1label = "Number of volumes";
  $m2label = "Conference location";
  $m3label = "DOI";
}
else if ($ref_type == "DATA") {
  $m1label = "Miscellaneous field 1 (n/a)";
  $m2label = "Miscellaneous field 2 (n/a)";
  $m3label = "DOI";
}
else if ($ref_type == "ELEC") {
  $m1label = "Medium";
  $m2label = "Unique ID";
  $m3label = "DOI";
}
else if ($ref_type == "HEAR") {
  $m1label = "Miscellaneous field 1 (n/a)";
  $m2label = "Miscellaneous field 2 (n/a)";
  $m3label = "DOI";
}
else if ($ref_type == "INPR") {
  $m1label = "Miscellaneous field 1 (n/a)";
  $m2label = "Miscellaneous field 2 (n/a)";
  $m3label = "DOI";
}
else if ($ref_type == "ICOMM") {
  $m1label = "Sender email address";
  $m2label = "Recipient email address";
  $m3label = "DOI";
}
else if ($ref_type == "JOUR" || $ref_type == "JOURshort") {
  $m1label = "Medium";
  $m2label = "Miscellaneous field 2 (n/a)";
  $m3label = "DOI";
}
else if ($ref_type == "JFULL") {
  $m1label = "Registry number";
  $m2label = "Unique ID";
  $m3label = "DOI";
}
else if ($ref_type == "MGZN") {
  $m1label = "Miscellaneous field 1 (n/a)";
  $m2label = "Miscellaneous field 2 (n/a)";
  $m3label = "DOI";
}
else if ($ref_type == "MAP") {
  $m1label = "Area";
  $m2label = "Type";
  $m3label = "DOI";
}
else if ($ref_type == "MPCT") {
  $m1label = "Classification";
  $m2label = "Running time";
  $m3label = "Media type";
}
else if ($ref_type == "MUSIC") {
  $m1label = "Miscellaneous field 1 (n/a)";
  $m2label = "Miscellaneous field 2 (n/a)";
  $m3label = "DOI";
}
else if ($ref_type == "NEWS") {
  $m1label = "Issue";
  $m2label = "Section";
  $m3label = "DOI";
}
else if ($ref_type == "PAMP") {
  $m1label = "Pamphlet number";
  $m2label = "Miscellaneous field 2 (n/a)";
  $m3label = "DOI";
}
else if ($ref_type == "PAT") {
  $m1label = "Class code (international)";
  $m2label = "Class code (US)";
  $m3label = "Document type";
}
else if ($ref_type == "PCOMM") {
  $m1label = "Type";
  $m2label = "Miscellaneous field 2 (n/a)";
  $m3label = "DOI";
}
else if ($ref_type == "RPRT") {
  $m1label = "Type";
  $m2label = "Miscellaneous field 2 (n/a)";
  $m3label = "DOI";
}
else if ($ref_type == "SER") {
  $m1label = "Number of volumes";
  $m2label = "Miscellaneous field 2 (n/a)";
  $m3label = "DOI";
}
else if ($ref_type == "SLIDE") {
  $m1label = "Miscellaneous field 1 (n/a)";
  $m2label = "Miscellaneous field 2 (n/a)";
  $m3label = "DOI";
}
else if ($ref_type == "SOUND") {
  $m1label = "Classification";
  $m2label = "Playing time";
  $m3label = "Media type";
}
else if ($ref_type == "STAT") {
  $m1label = "Miscellaneous field 1 (n/a)";
  $m2label = "Miscellaneous field 2 (n/a)";
  $m3label = "DOI";
}
else if ($ref_type == "THES") {
  $m1label = "Degree";
  $m2label = "Type";
  $m3label = "DOI";
}
else if ($ref_type == "UNBILL") {
  $m1label = "Miscellaneous field 1 (n/a)";
  $m2label = "Miscellaneous field 2 (n/a)";
  $m3label = "DOI";
}
else if ($ref_type == "UNPB") {
  $m1label = "Miscellaneous field 1 (n/a)";
  $m2label = "Miscellaneous field 2 (n/a)";
  $m3label = "DOI";
}
else if ($ref_type == "VIDEO") {
  $m1label = "Classification";
  $m2label = "Running time";
  $m3label = "Media type";
}
else {
  $m1label = "Miscellaneous field 1";
  $m2label = "Miscellaneous field 2";
  $m3label = "Miscellaneous field 3";
}

		    //names related to fields (scope)
		       $scopes=array("AU" => "Author(s)", 
		                               "TI" => "Title", 
		                               "N2" => "Abstract",
				         "KW" => "Keywords/Subject terms", 
				         "A2" => "Editor(s)",
				         "JF" => "Full Title", 
				         "JO" => "Official Abbreviation", 
				         "J1" => "Custom Abbreviation 1", 
				         "J2" => "Custom Abbreviation 2",
				         "T2" => "Secondary Title", 
				         "A3" => "Tertiary Contributor(s)",
				         "T3" => "Tertiary Title", 
				         "VL" => "Volume", 
				         "IS" => "Issue",
				         "CY" => "City of Publication", 
				         "PB" => "Publisher", 
				         "SN" => "ISBN/ISSN",
				         "AD" => "Contact address", 
				         "PY" => "Publication Year<br/>(most recent)",
				         "Y2" => "Publication Year<br/>(earlier or  additional)", 
				         "SP" => "Starting page",
				         "EP" => "Ending page", 
				         "N1" => "Bibilographic Notes", 
				         "RP" => "Reprint status",
				         "AV" => "Local copy", 
				         "UR" => "Public URL",
                                         "L1" => "Local URL",
				         "U1" => "User defined field 1",
				         "U2" => "User defined field 2", 
				         "U3" => "User defined field 3",
				         "U4" => "User defined field 4", 
				         "U5" => "User defined field 5", 
				         "M1" => $m1label, 
				         "M2" => $m2label,
				         "M3" => $m3label
				    );
		       $scope = $scopes[$field];
		       $scope=ucfirst($scope);
		       //tips for field entry
		       $author="Use the following format, separating multiple authors by semicolons: <code>Lastname, Firstname I. Jr.; Lastname, Sir Firstname I. IV</code>.";
		       $title="Use sentence case as appropriate to the language in question: e.g. <code>For whom the bell tolls</code> vs. <code>Altenglische Grammatik nach der angelsächsischen Grammatik von Eduard Sievers</code>.";
		       $keywords="Use semicolons to separate terms: <code>Old English language; Book History</code>.";
		       $journalWarning=": You <strong>must</strong> provide at least one of the Journal's full title, official abbreviation, or custom abbreviation.";
		       $journalFull="Enter the full name of the journal" . $journalWarning;
		       $publicationYear="Use this field for year the copy you are cataloguing was published; use the \"Other:\" textbox to record additional date-related information; use <strong>Other publication date</strong> for the date of original publication if this is different and of interest.";
		       $otherYear="Use this if the publication has a date of original publication that is of interest and different from the copy you are cataloguing";
		       $note1="Tip! Use this field for bibliographic notes: e.g. <code>Includes CD-ROM</code>.";
		       $availability="Use this to indicate where your physical copy (if any) can be found: <code>office filing cabinet</code>, <code>call number";
		       $URL="This refers to a URL that you could use in a published citation. It should <strong>not</strong> refer to a private copy.";
		       $L1="This refers to a URL of a private copy. Use <code>file://path</code> for the local filesystem, or <code>http://path</code> for a local web server";
		       $journalAbbrOfficial="This is the standard abbreviation for the journal as it appears in standard bibliographies" . $journalWarning;
		       $journalAbbrCustom="This is a custom or alternate abbreviation for the journal" . $journalWarning;
		       $tips = array("AU" => $author,
		                     "TI" => $title,
				     "KW" => $keywords,
				     "A2" => $author,
				     "JF" => $journalFull,
				     "T2" => $title,
				     "T3" => $title,
				     "A3" => $author,
				     "PY" => $publicationYear,
				     "Y2" => $otherYear,
				     "N1" => $note1,
				     "AV" => $availability,
				     "UR" => $URL,
                                     "L1" => $L1,
				     "JO" => $journalAbbrOfficial,
				     "J1" => $journalAbbrCustom,
				     "J2" => $journalAbbrCustom
				    );
			// For multi row fields, we can set the row number here
			// Then, a textarea instead of an input will be created
			$rows = array("N2" => 10, "AD" => 5);

			// For date fields

			$is_date = array("PY" => True, "Y2" => True);


			//For field labels,
			//we chan use the either the scope only(scopeOnly=True)

			//or use the referencetype to 
			//define a single text pattern where
			// _scope is replaced by the scope

			// or the most flexible way is to define an array
			// within $texts with
			// the scope as index
			$scopeOnly = array("N2" => True,
					   "KW" => True,
					   "CY" => True,
					   "PB" => True,
					   "SN" => True,
					   "AD" => True,
					   "PY" => True,
					   "Y2" => True,
					   "EP" => True,
					   "SP" => True,
					   "N1" => True,
					   "RP" => True,
					   "AV" => True,
					   "UR" => True,
					   "L1" => True,
					   "U1" => True,
					   "U2" => True,
					   "U3" => True,
					   "U4" => True,
					   "U5" => True,
					   "M1" => True,
					   "M2" => True,
					   "M3" => True
					  );

			// Some fields are of interest only for certain reference types
			// for examlpe various journal titles for journals only
			$ty_all= array("JOUR", "JOURshort","JFULL", "MGZN", "NEWS",
				       "", "ABST","ADVS","ART", "BOOK",
				       "BOOKshort", "CHAP", "CHAPshort",
				       "COMP", "CONF", "CTLG", "DATA", "ELECT",
				       "ICOMM", "INPR", "MAP", "MPCT", "MUSIC",
				       "PAMP", "PAT", "PCOMM", "RPRT", "SER",
				       "SLIDE", "SOUND", "THES", "UNPB", "VIDEO");

			$ty_pages= array("JOUR", "JOURshort", "MGZN", "NEWS",
					 "", "ABST","ADVS","ART", "CHAP",
					 "CHAPshort", "COMP", "CONF", "CTLG",
					 "INPR", "MAP",  "MUSIC",  "PAT", "PCOMM",
					 "RPRT", "UNPB");

			$ty_jour =array("JOUR", "JOURshort","JFULL", "MGZN", "NEWS");
			$ty_no_jour = array("", "ABST","ADVS","ART", "BOOK",
					    "BOOKshort", "CHAP", "CHAPshort",
					    "COMP", "CONF", "CTLG", "DATA",
					    "ELECT", "ICOMM", "INPR", "MAP",
					    "MPCT", "MUSIC", "PAMP", "PAT",
					    "PCOMM", "RPRT", "SER", "SLIDE",
					    "SOUND", "THES", "UNPB", "VIDEO");

			$someTypesOnly = array("JF"=> $ty_jour,
					       "JO"=> $ty_jour,
					       "J1"=> $ty_jour,
					       "J2"=> $ty_jour,
					       "IS"=> $ty_jour,
					       "T2" => $ty_no_jour,
					       "CY" => $ty_no_jour,
					       "PB" => $ty_no_jour,
					       "SP" => $ty_pages,
					       "EP" => $ty_pages
			                 );

			$texts = array("" => "_scope",
				       "none" => "_scope",
				       "ABST" => array( "Full Title" => "Journal Name",
							     "Editor(s)" => "Journal editor(s)",
							     "Official Abbreviation" => "Journal Abbreviation (official)",
							     "Custom Abbreviation 1" => "Journal Abbreviation (custom 1)",
							     "Custom Abbreviation 2" => "Journal Abbreviation (custom 2)",
							     "Tertiary Contributor(s)" => "Series Editor(s)",
							     "Tertiary Title" => "Series Title",
							     "default" => "Article _scope"),
				       "ADVS" => "_scope",
				       "ART" => "_scope", 
				       "BOOK" => array( "Secondary Title" => "n/a",
							     "Editor(s)" => "Book editor(s)",
							     "Tertiary Contributor(s)" => "Series Editor(s)",
							     "Tertiary Title" => "Series Title",
							     "default" => "Book _scope"),
				       "BOOKshort" => array( "Secondary Title" => "n/a",
							     "Editor(s)" => "Book editor(s)",
							     "Tertiary Contributor(s)" => "Series Editor(s)",
							     "Tertiary Title" => "Series Title",
							     "default" => "Book _scope"),
				       "CHAP" => array( "Secondary Title" => "Book Title",
							     "Editor(s)" => "Book editor(s)",
							     "Tertiary Contributor(s)" => "Series Editor(s)",
							     "Tertiary Title" => "Series Title",
							     "default" => "Chapter _scope"),
				       "CHAPshort" => array( "Secondary Title" => "Book Title",
							     "Editor(s)" => "Book editor(s)",
							     "Tertiary Contributor(s)" => "Series Editor(s)",
							     "Tertiary Title" => "Series Title",
							     "default" => "Chapter _scope"),
				       "COMP" => "_scope",
				       "CONF" => "Proceedings _scope",
				       "CTLG" => "Catalogue _scope",
				       "DATA" => "_scope of File",
				       "ELECT" => "Web Page _scope", 
				       "ICOMM" => array( "title" => "Email Subject",
							 "default" => "Email _scope"), 
				       "INPR" => array( "Full Title" => "Journal Name",
							     "Editor(s)" => "Journal editor(s)",
							     "Official Abbreviation" => "Journal Abbreviation (official)",
							     "Custom Abbreviation 1" => "Journal Abbreviation (custom 1)",
							     "Custom Abbreviation 2" => "Journal Abbreviation (custom 2)",
							     "Tertiary Contributor(s)" => "Series Editor(s)",
							     "Tertiary Title" => "Series Title",
							     "default" => "Article _scope"),
				       "JOUR" => array( "Full Title" => "Journal Name",
							     "Editor(s)" => "Journal editor(s)",
							     "Official Abbreviation" => "Journal Abbreviation (official)",
							     "Custom Abbreviation 1" => "Journal Abbreviation (custom 1)",
							     "Custom Abbreviation 2" => "Journal Abbreviation (custom 2)",
							     "Tertiary Contributor(s)" => "Series Editor(s)",
							     "Tertiary Title" => "Series Title",
							     "default" => "Article _scope"),
				       "JOURshort" => array( "Full Title" => "Journal Name",
							     "Editor(s)" => "Journal editor(s)",
							     "Official Abbreviation" => "Journal Abbreviation (official)",
							     "Custom Abbreviation 1" => "Journal Abbreviation (custom 1)",
							     "Custom Abbreviation 2" => "Journal Abbreviation (custom 2)",
							     "Tertiary Contributor(s)" => "Series Editor(s)",
							     "Tertiary Title" => "Series Title",
							     "default" => "Article _scope"),
				       "JFULL" => array( "Full Title" => "Journal Name",
							     "Editor(s)" => "Journal editor(s)",
							     "Official Abbreviation" => "Journal Abbreviation (official)",
							     "Custom Abbreviation 1" => "Journal Abbreviation (custom 1)",
							     "Custom Abbreviation 2" => "Journal Abbreviation (custom 2)",
							     "Tertiary Contributor(s)" => "Series Editor(s)",
							     "Tertiary Title" => "Series Title",
							     "default" => "Article _scope"),
				       "MAP" => "Map _scope",
				       "MGZN" => array( "Full Title" => "Magazine Name",
							     "Editor(s)" => "Magazine editor(s)",
							     "Official Abbreviation" => "Magazine Abbreviation (official)",
							     "Custom Abbreviation 1" => "Magazine Abbreviation (custom 1)",
							     "Custom Abbreviation 2" => "Magazine Abbreviation (custom 2)",
							     "Tertiary Contributor(s)" => "Series Editor(s)",
							     "Tertiary Title" => "Series Title",
							     "default" => "Article _scope"),
				       "MPCT" => "Motion Picture _scope",
				       "MUSIC" => "_scope of Composition",
				       "NEWS" => array( "Full Title" => "Newspaper Name",
							     "Editor(s)" => "Newspaper editor(s)",
							     "Official Abbreviation" => "Newspaper Abbreviation (official)",
							     "Custom Abbreviation 1" => "Newspaper Abbreviation (custom 1)",
							     "Custom Abbreviation 2" => "Newspaper Abbreviation (custom 2)",
							     "Tertiary Contributor(s)" => "Series Editor(s)",
							     "Tertiary Title" => "Series Title",
							     "default" => "Article _scope"),
				       "PAMP" => "Pamphlet _scope", 
				       "PAT" => "Patent _scope", 
				       "PCOMM" => "_scope of Communication (if applicable)", 
				       "RPRT" => "Report _scope",
				       "SER" => "Series _scope", 
				       "SLIDE" => "_scope of Slide/Slide Show",
				       "SOUND" => "Recording _scope",
				       "THES" => "Thesis/Dissertation _scope",
				       "UNPB" => "_scope of Composition",
				       "VIDEO" => "_scope");
			if(isset($someTypesOnly[$field])){
				if(!in_array($ref_type, $someTypesOnly[$field])){
					//do not display certain fields for some reference types
					return;
				}
			}


			if(isset($scopeOnly[$field])){
				$label=$scope;
			} else {
				if(is_array($texts[$ref_type])){
					if(isset($texts[$ref_type][$scope])){
					     $label =$texts[$ref_type][$scope];
					}elseif(isset($texts[$ref_type]['default'])){
					     $label = str_replace("_scope", $scope, $texts[$ref_type]['default']);
					}
				} else {
					$label = str_replace("_scope", $scope, $texts[$ref_type]);
				}
			}
			//Generate the formfield
			echo "                        <tr class=\"formfield\" id=\"form$field\">\n";
			echo "                            <td class=\"formlabel\"><strong> $label </strong></td>\n";
			echo "                            <td class=\"forminput\">\n";
			if(isset($rows[$field])){
				echo "                                <textarea class=\"searchText\" type=\"text\" name=\"form$field\" cols=\"70\"  rows=\"".$rows[$field]."\"/>" . $default. "</textarea>\n";
			} else if($field=="RP"){
					echo "                                <select name=\"formRP\">\n";
					echo "                                         <option value=\"IN FILE\"";
					if ($default=="IN FILE") {
					    echo " selected=\"selected\" ";
					}
					echo ">IN FILE</option>\n";
					echo "                                         <option value=\"NOT IN FILE\"";
					if ($default=="NOT IN FILE") {
					    echo " selected=\"selected\" ";
					}
					echo ">NOT IN FILE</option>\n";
					echo "                                         <option value=\"ON REQUEST\"";
					if ($default=="ON REQUEST") {
					    echo " selected=\"selected\" ";
					}
					echo ">ON REQUEST</option>\n";
					echo "                                </select>\n"; 
					echo "                                (Requested:"; 
					$datetype="onrequestday";
					$date=date("d");
					dateChooser($datetype,$date);
					echo "/"; 
					$datetype="onrequestdatemonth";
					$month=date("F");
					monthChooser($datetype,$month);                                                        
					echo "/";
					echo "                            <input class=\"searchText\" type=\"text\" name=\"onrequestdateyear\" size=\"4\" value=\"" . date("y") . "\"/>)";

			} else if(isset($is_date[$field])){
				echo "                                <input class=\"searchText\" type=\"text\" name=\"form".$field."year\" size=\"4\"";
                                                        if ($default['year']=="") {
                                                            echo " value=\"YYYY\"";
                                                        } else {
                                                            echo " value=\"".$default['year']."\"";
                                                        }
                                                        echo "/>&#x00A0;";
                                                        echo "                            (";
                                                        monthChooser("form".$field."month",$default['month']);
                                                        echo "&#x00A0;";
                                                        dateChooser("form".$field."day",$default['day']);
                                                        echo "/";  
                                                        echo "                            <input class=\"searchText\" type=\"text\" name=\"form".$field."other\"";
                                                        if ($default['other']=="") {
                                                            echo " value=\"Other:\"";
                                                        } 
                                                        else {
                                                            echo " value=\"".$default['other']."\"";
                                                        } 
                                                        echo "/>)";


			} else {
				echo "                                <input class=\"searchTex\" type=\"text\" name=\"form$field\" size=\"70\" value=\"" . $default . "\"/>\n";
			}
			if(isset($tips[$field])){
			     echo "                                <seg class=\"tip\">$tips[$field]</seg>\n";
			}
			echo "                            </td>\n";
			echo "                        </tr>\n";


		}
        }
        
function  monthChooser($datetype,$month) {
  echo "<select name=\"$datetype\">\n";
  echo "                                <option value=\"NoMonth\" selected=\"selected\">Month (optional)</option>\n";
  $months=array("January" => "01",
    "February" => "02",
    "March" => "03",
    "April" => "04",
    "May" => "05",
    "June" => "06",
    "July" => "07",
    "August" => "08",
    "September" => "09",
    "October" => "10",
    "November" => "11",
    "December" => "12");

  foreach($months as $month_label => $month_number){
    echo "                                <option value=\"$month_number\"";
    if ($month==$month_number) {
      echo " selected=\"selected\"";
    }
    echo ">$month_label</option>\n";
  }
  echo "                            </select>";
}

                function  dateChooser($datetype,$date) {
                                                        echo "                                <select name=\"$datetype\">\n";
                                                        echo "                                    <option value=\"NoDay\"";
                                                        if ($date=="NoDay") {
                                                            echo " selected=\"selected\"";
                                                        } 
                                                        echo ">Day (optional)</option>\n";
                                                        echo "                                    <option value=\"01\"";
                                                        if ($date=="01") {
                                                            echo " selected=\"selected\"";
                                                        } 
                                                        echo ">01</option>\n";
                                                        echo "                                    <option value=\"02\"";
                                                       if ($date=="02") {
                                                            echo " selected=\"selected\"";
                                                        }
                                                        echo ">02</option>\n";
                                                        echo "                                <option value=\"03\"";
                                                        if ($date=="03") {
                                                            echo " selected=\"selected\"";
                                                        }
                                                        echo ">03</option>\n";
                                                        echo "                                <option value=\"04\"";
                                                        if ($date=="04") {
                                                            echo " selected=\"selected\"";
                                                        }
                                                        echo ">04</option>\n";
                                                        echo "                                <option value=\"05\"";
                                                        if ($date=="05") {
                                                            echo " selected=\"selected\"";
                                                        }
                                                        echo ">05</option>\n";
                                                        echo "                                <option value=\"06\"";
                                                        if ($date=="06") {
                                                            echo " selected=\"selected\"";
                                                        }
                                                        echo ">06</option>\n";
                                                        echo "                                <option value=\"07\"";
                                                        if ($date=="07") {
                                                            echo " selected=\"selected\"";
                                                        }
                                                        echo ">07</option>\n";
                                                        echo "                                <option value=\"08\"";
                                                        if ($date=="08") {
                                                            echo " selected=\"selected\"";
                                                        } 
                                                        echo ">08</option>\n";
                                                        echo "                                <option value=\"09\"";
                                                        if ($date=="09") {
                                                            echo " selected=\"selected\"";
                                                        } 
                                                        echo ">09</option>\n";
                                                        echo "                                <option value=\"10\"";
                                                        if ($date=="10") {
                                                            echo " selected=\"selected\"";
                                                        }
                                                        echo ">10</option>\n";
                                                        echo "                                <option value=\"11\"";
                                                        if ($date=="11") {
                                                            echo " selected=\"selected\"";
                                                        }
                                                        echo ">11</option>\n";
                                                        echo "                                <option value=\"12\"";
                                                        if ($date=="12") {
                                                            echo " selected=\"selected\"";
                                                        }
                                                        echo ">12</option>\n";
                                                        echo "                                <option value=\"13\"";
                                                        if ($date=="13") {
                                                            echo " selected=\"selected\"";
                                                        }
                                                        echo ">13</option>\n";
                                                        echo "                                <option value=\"14\"";
                                                        if ($date=="14") {
                                                            echo " selected=\"selected\"";
                                                        }
                                                        echo ">14</option>\n";
                                                        echo "                                <option value=\"15\"";
                                                        if ($date=="15") {
                                                            echo " selected=\"selected\"";
                                                        }
                                                        echo ">15</option>\n";
                                                        echo "                                <option value=\"16\"";
                                                        if ($date=="16") {
                                                            echo " selected=\"selected\"";
                                                        }
                                                        echo ">16</option>\n";
                                                        echo "                                <option value=\"17\"";
                                                        if ($date=="17") {
                                                            echo " selected=\"selected\"";
                                                        }
                                                        echo ">17</option>\n";
                                                        echo "                                <option value=\"18\"";
                                                        if ($date=="18") {
                                                            echo " selected=\"selected\"";
                                                        }
                                                        echo ">18</option>\n";
                                                        echo "                                <option value=\"19\"";
                                                        if ($date=="19") {
                                                            echo " selected=\"selected\"";
                                                        }
                                                        echo ">19</option>\n";
                                                        echo "                                <option value=\"20\"";
                                                        if ($date=="20") {
                                                            echo " selected=\"selected\"";
                                                        }
                                                        echo ">20</option>\n";
                                                        echo "                                <option value=\"21\"";
                                                        if ($date=="21") {
                                                            echo " selected=\"selected\"";
                                                        }
                                                        echo ">21</option>\n";
                                                        echo "                                <option value=\"22\"";
                                                        if ($date=="22") {
                                                            echo " selected=\"selected\"";
                                                        }
                                                        echo ">22</option>\n";
                                                        echo "                                <option value=\"23\"";
                                                        if ($date=="23") {
                                                            echo " selected=\"selected\"";
                                                        }
                                                        echo ">23</option>\n";
                                                        echo "                                <option value=\"24\"";
                                                        if ($date=="24") {
                                                            echo " selected=\"selected\"";
                                                        }
                                                        echo ">24</option>\n";
                                                        echo "                                <option value=\"25\"";
                                                        if ($date=="25") {
                                                            echo " selected=\"selected\"";
                                                        }
                                                        echo ">25</option>\n";
                                                        echo "                                <option value=\"26\"";
                                                        if ($date=="26") {
                                                            echo " selected=\"selected\"";
                                                        } 
                                                        echo ">26</option>\n";
                                                        echo "                                <option value=\"27\"";
                                                        if ($date=="27") {
                                                            echo " selected=\"selected\"";
                                                        }
                                                        echo ">27</option>\n";
                                                        echo "                                <option value=\"28\"";
                                                        if ($date=="28") {
                                                            echo " selected=\"selected\"";
                                                        }
                                                        echo ">28</option>\n";
                                                        echo "                                <option value=\"29\"";
                                                        if ($date=="29") {
                                                            echo " selected=\"selected\"";
                                                        }
                                                        echo ">29</option>\n";
                                                        echo "                                <option value=\"30\"";
                                                        if ($date=="30") {
                                                            echo " selected=\"selected\"";
                                                        } 
                                                        echo ">30</option>\n";
                                                        echo "                                <option value=\"31\"";
                                                        if ($date=="31") {
                                                            echo " selected=\"selected\"";
                                                        }
                                                        echo ">31</option>\n";
                                                        echo "                            </select>";
                                                }
                                                
                                                
                                                
                                               
                                               function parseRSS($lines) {
                                                                                       // initialialise form variables
                                            $formfields['AU']=""; // Author of catalogued material (article/chapter for analtyic, book for monographic, etc.
                                            $formfields['A2']=""; // Secondary Contributor (i.e. Editor of Book)
                                            $formfields['A3']=""; // Series editor
                                            $formfields['N2']=""; // Abstract
                                            $formfields['AD']=""; // Contact Address
                                            $formfields['AV']=""; // AVAILABILITY. Can be prose description of a physical copy, or call number
                                            $formfields['CY']=""; // CITY of Publication (Book)
                                            $formfields['EP']=""; //END PAGE
                                            $formfields['ID']=""; // CITATION (Supplied by RefDB
                                            $formfields['IS']=""; // ISSUE of Volume Periodical
                                            $formfields['J1']=""; // Additional User Supplied Journal Abbreviation
                                            $formfields['J2']="";  // Additional User Supplied Addition
                                            $formfields['JF']=""; //Full Journal Name
                                            $formfields['JO']=""; // Abbreviated Journal Name (official)
                                            $formfields['KW']=""; // Subject descriptors or Keywords
                                            $formfields['M1']=""; //Miscellaneous Field 1
                                            $formfields['M2']="";  //Miscellaneous Field 1
                                            $formfields['M3']="";  //Miscellaneous Field 1
                                            $formfields['N1']=""; //Notes (any type)
                                            $formfields['N2']=""; // Abstract
                                            $formfields['PB']=""; // PUBLISHER
                                            $PY=""; //original RIS form of publication year
                                            $formfields['PYyear']=""; // Publication Year: YYYY
                                            $formfields['PYmonth']=""; // Publication Month: MM
                                            $formfields['PYday']=""; // Publication Day: DD
                                            $formfields['PYother']=""; // Publication Other: Otherinfo
                                            $Y2=""; //original RIS form of publication year 2
                                            $formfields['Y2year']=""; // Publication Year: YYYY
                                            $formfields['Y2month']=""; // Publication Month: MM
                                            $formfields['Y2day']=""; // Publication Day: DD
                                            $formfields['Y2other']=""; // Publication Other: Otherinfo
                                            $formfields['RP']=""; //Reprint status: IN FILE, NOT IN FILE, ON REQUEST MM/DD/YY
                                            $formfields['SN']=""; //ISSN or ISSB number
                                            $formfields['SP']=""; //START PAGE 
                                            $formfields['TI']=""; //Primary Title
                                            $formfields['T2']=""; // Secondary Title
                                            $formfields['T3']=""; // Teritary Title
                                            $formfields['TY']=""; //Citation Type
                                            $formfields['U1']=""; //User Defined Field 1
                                            $formfields['U2']=""; //User Defined Field 2
                                            $formfields['U3']=""; //User Defined Field 3
                                            $formfields['U4']=""; //User Defined Field 4
                                            $formfields['U5']=""; //User Defined Field 5
                                            $formfields['UR']=""; //URL (official) of an On-line Reference
                                            $formfields['L1']=""; //URL (local) of a private copy
                                            $formfields['VL']=""; //Volume of Journal/Periodical
                                                    // Set some switches we'll be using below in combining multiple fields into a single form variable.
                                                    $firstAU="true";
                                                    $firstA2="true";
                                                    $firstA3="true";
                                                    $firstKW="true";                                                    
                                                    // Cycle through resulting array
                                                    if (isset($lines)) {
                                                    foreach ($lines as $line) {
                                                        // Check the type of each line and extract the content
                                                            $test=substr($line,0,2);
                                                            $content=htmlentities(substr($line,6));

                                                        // Assign the form variables based on the value of the test variable
                                                            if ($test=="N2") {
                                                                $formfields['N2']=$content;
                                                            }
                                                            if ($test=="AU"||$test=="A1") {
                                                                $content=str_replace(",", ", ", $content);
                                                                    if ($firstAU=="true") {
                                                                        $formfields['AU']=$content;
                                                                        $firstAU="false";
                                                                    }
                                                                    else {
                                                                        $formfields['AU']=$formfields['AU'] . "; " . $content;
                                                                    }
                                                            }
                                                            if ($test=="A2") {
                                                                $content=str_replace(",", ", ", $content);                            
                                                                if ($firstA2=="true") {
                                                                    $formfields['A2']=$content;
                                                                    $firstA2="false";
                                                                }
                                                                else {
                                                                    $formfields['A2']=$formfields['A2'] . "; " . $content;
                                                                }
                                                            }
                                                            if ($test=="A3") {
                                                                $content=str_replace(",", ", ", $content);                            
                                                                if ($firstA3=="true") {
                                                                    $formfields['A3']=$content;
                                                                    $firstA3="false";
                                                                }
                                                                else {
                                                                    $formfields['A3']=$formfields['A3'] . "; " . $content;
                                                                }
                                                            }
                                                            if ($test=="AD") {
                                                                $formfields['AD']=$content; // Contact Address
                                                            }
                                                            if ($test=="AV") {
                                                                $formfields['AV']=$content; // AVAILABILITY. Can be prose description of for internal URL: PATH:
                                                            }
                                                            if ($test=="BT") {
                                                                if ($formfields['TI']!="") {
                                                                    if ($formfields['T2']=="") {
                                                                    $formfields['T2']=$content;
                                                                    }
                                                                }
                                                                else {
                                                                    $formfields['TI']=$content;
                                                                }
                                                            }
                                                            if ($test=="CY") {
                                                                $formfields['CY']=$content; // CITY of Publication (Book)
                                                            }
                                                            if ($test=="EP") {
                                                                $formfields['EP']=$content; //END PAGE
                                                            }
                                                            if ($test=="ID") {
                                                                $formfields['ID']=$content; // CITATION (Supplied by RefDB
                                                            }
                                                            if ($test=="IS") {
                                                                $formfields['IS']=$content; // ISSUE of Volume Periodical
                                                            }
                                                            if ($test=="J1") {
                                                                $formfields['J1']=$content; // Additional User Supplied Journal Abbreviation
                                                            }
                                                            if ($test=="J2") {
                                                                $formfields['J2']=$content;  // Additional User Supplied Addition
                                                            }
                                                            if ($test=="JF") {
                                                                $formfields['JF']=$content; //Full Journal Name
                                                            }
                                                            if ($test=="JO") {
                                                                $formfields['JO']=$content; // Abbreviated Journal Name (official)
                                                            }
                                                            if ($test=="KW") {
                                                                if ($firstKW=="true") {
                                                                    $formfields['KW']=$content;
                                                                    $firstKW="false";
                                                                }
                                                                else {
                                                                    $formfields['KW']=$formfields['KW'] . "; " . $content;
                                                                }
                                                            }
                                                            if ($test=="M1") {
                                                                $formfields['M1']=$content; //Miscellaneous Field 1
                                                            }
                                                            if ($test=="M2") {
                                                                $formfields['M2']=$content;  //Miscellaneous Field 1
                                                            }
                                                            if ($test=="M3") {
                                                                $formfields['M3']=$content;  //Miscellaneous Field 1
                                                            }
                                                            if ($test=="N1") {
                                                                $formfields['N1']=$content; //Notes (any type)
                                                            }
                                                            /* if ($test=="N2") {
                                                                $formfields['N2']=$content; // Abstract
                                                            } */
                                                            if ($test=="PB") {
                                                                $formfields['PB']=$content; // PUBLISHER
                                                            }
                                                            if ($test=="PY") {
                                                                $PY=explode("/",$content);
                                                                list($formfields['PYyear'], $formfields['PYmonth'], $formfields['PYday'], $formfields['PYother'])=$PY;
                                                            }
                                                            if ($test=="Y2") {
                                                                $Y2=explode("/",$content);
                                                                list($formfields['Y2year'], $formfields['Y2month'], $formfields['Y2day'], $formfields['Y2other'])=$Y2;
                                                            }
                                                            if ($test=="RP") {
                                                                $formfields['RP']=$content; //Reprint status: IN FILE, NOT IN FILE, ON REQUEST MM/DD/YY
                                                            }
                                                            if ($test=="SN") {
                                                                $formfields['SN']=$content; //ISSN or ISSB number
                                                            }
                                                            if ($test=="SP") {
                                                                $formfields['SP']=$content; //START PAGE 
                                                            }
                                                            if ($test=="TI") {
                                                                $formfields['TI']=$content; //Primary Title
                                                            }
                                                            if ($test=="T2") {
                                                                $formfields['T2']=$content; // Secondary Title
                                                            }
                                                            if ($test=="T3") {
                                                                $formfields['T3']=$content; // Teritary Title
                                                            }
                                                            if ($test=="TY") {
                                                                $formfields['TY']=$content; //Citation Type
                                                            }
                                                            if ($test=="U1") {
                                                                $formfields['U1']=$content; //User Defined Field 1
                                                            }
                                                            if ($test=="U2") {
                                                                $formfields['U2']=$content; //User Defined Field 2
                                                            }
                                                            if ($test=="U3") {
                                                                $formfields['U3']=$content; //User Defined Field 3
                                                            }
                                                            if ($test=="U4") {
                                                                $formfields['U4']=$content; //User Defined Field 4
                                                            }
                                                            if ($test=="U5") {
                                                                $formfields['U5']=$content; //User Defined Field 5
                                                            }
                                                            if ($test=="UR") {
                                                                $formfields['UR']=$content; //URL (official) of an On-line Reference
                                                            }
                                                            if ($test=="L1") {
                                                                $formfields['L1']=$content; //URL (official) of an On-line Reference
                                                            }
                                                            if ($test=="VL") {
                                                                $formfields['VL']=$content; //Volume of Journal/Periodical
                                                            }
                                                        }

                                                        }
                                                        else {
                                                        echo "<p>No content in variable</p>";
                                                        }
							       /*
                                                               $RIS = array("formAB"=>$formAB,
                                                                            "formAU"=>$formAU, 
                                                                            "formA2"=>$formA2, 
                                                                            "formA3"=>$formA3, 
                                                                            "formAD"=>$formAD, 
                                                                            "formAV"=>$formAV, 
                                                                            "formCY"=>$formCY, 
                                                                            "formEP"=>$formEP,
                                                                            "formID"=>$formID, 
                                                                            "formIS"=>$formIS, 
                                                                            "formJ1"=>$formJ1, 
                                                                            "formJ2"=>$formJ2,
                                                                            "formJF"=>$formJF,
                                                                            "formJO"=>$formJO,
                                                                            "formKW"=>$formKW, 
                                                                            "formM1"=>$formM1, 
                                                                            "formM2"=>$formM2, 
                                                                            "formM3"=>$formM3, 
                                                                            "formN1"=>$formN1, 
                                                                 /*           "formN2"=>$formN2, / 
                                                                            "formPB"=>$formPB, 
                                                                            "formPY"=>$PY,
                                                                            "formPYyear"=>$formPYyear, 
                                                                            "formPYmonth"=>$formPYmonth, 
                                                                            "formPYday"=>$formPYday,
                                                                            "formPYother"=>$formPYother,
                                                                            "formY2"=>$Y2,
                                                                            "formY2year"=>$formY2year, 
                                                                            "formY2month"=>$formY2month, 
                                                                            "formY2day"=>$formY2day,
                                                                            "formY2other"=>$formY2other,
                                                                            "formRP"=>$formRP, 
                                                                            "formSN"=>$formSN, 
                                                                            "formSP"=>$formSP, 
                                                                            "formT1"=>$formTI, 
                                                                            "formT2"=>$formT2, 
                                                                            "formT3"=>$formT3, 
                                                                            "referencetype"=>$referencetype, 
                                                                            "formU1"=>$formU1, 
                                                                            "formU2"=>$formU2, 
                                                                            "formU3"=>$formU3, 
                                                                            "formU4"=>$formU4, 
                                                                            "formU5"=>$formU5, 
                                                                            "formUR"=>$formUR, 
                                                                            "formVL"=>$formVL);
									    */
                                                            return $formfields;

}
?>