 #!/cygdrive/c/strawberry/perl/bin/perl -w

# Need to specify the full path of Perl above, e.g. for Windows something like
#!C:\\Perl32\\bin\\perl -w


use strict;

# Set this to 1 to work around IIS 6 craziness
my $iis6_mode = 0;


# IIS 6: for some reason, IIS runs this script with the working directory set to the Greenstone
#   directory rather than the cgi-bin directory, causing lots of stuff to fail
if ($iis6_mode)
{
    # Change into cgi-bin directory
    chdir("cgi-bin");
}


# We use require and an eval here (instead of "use") to catch any errors loading the module (for IIS)
eval("require \"gsdlCGI.pm\"");
if ($@)
{
    print STDOUT "Content-type:text/plain\n\n";
    print STDOUT "ERROR: $@\n";
    exit 0;
}


sub generate_html_form
{
    my ($isGSDL2,$site,$collect,$cl) = @_;

    my $html_form = <<EOT;
<html>
  <head>
    <title>HTML to Expeditee Frames</title>

    <base href=".." />

    <link type="text/css" href="ext/html-to-expeditee/jquery/css/le-frog/jquery-ui-1.8.16.custom.css" rel="stylesheet" />
    <script type="text/javascript" src="ext/html-to-expeditee/jquery/js/jquery-1.6.2.min.js"></script>
    <script type="text/javascript" src="ext/html-to-expeditee/jquery/js/jquery-ui-1.8.16.custom.min.js"></script>
    <script type="text/javascript" src="ext/html-to-expeditee/js/gsajax-min.js"></script>
    <script type="text/javascript" src="ext/html-to-expeditee/js/html-to-expeditee.js"></script>



  </head>
  <body>
    <form class="ui-widget">
      Convert the collection 
        <input type="text" 
	       class="ui-corner-all" style="padding: 4px;"
	       name="collect" value="$collect" id="collect" />
      to Expeditee frames by traversing the classifier 
        <input type="text" 
	       class="ui-corner-all" style="padding: 4px;"
               name="cl" value="$cl" id="cl" />

        <input value="$site" name="site" id="site" type="hidden">
        <input value="Go" id="go" 
               class="ui-button ui-widget ui-state-default ui-corner-all" 
               type="submit">

    </form>
    <script type="text/javascript">
      var docOIDs = [];
      var numDocOIDs;

      \$(function() {
	  \$('#progress').progressbar();
	  
	  \$('#go').button().click(function() { 
	      var collect = document.getElementById("collect").value;
	      if (collect.match(/^\\s*\$/)) {
		  alert("No collection specified");
		  return false;
	      }

	      var cl = document.getElementById("cl").value;
	      if (cl.match(/^\\s*\$/)) {
		  alert("No classifier specified");
		  return false;
	      }
	      if (cl.match(/^\\d+\$/)) {
	          cl = "CL" + cl;
	      }
	      
	      var gs2=$isGSDL2;

	      var url;
	      if (gs2) {
	          url = "library.cgi";
		  url += "?c="+collect +"&a=d&cl=" + cl;
	      }
	      else {
	          url = "library";
	          url += "?c="+collect +"&a=b&rt=s&s=ClassifierBrowse&cl=" + cl;
	          url += "&excerptid=gs_content";
	      }

	      /* processing animation */
		  
	      docOIDs = [];
	      var outstandingURLs = [];
	      var visitedURLs = {};

	      outstandingURLs.push(url);
	      visitedURLs[url] = 1;

	      while (outstandingURLs.length>0) {
		  url = outstandingURLs.shift();
	      
		  var clHtml = urlGetSync(url);
		  		  
		  var aElems;
		  var workingTrav = document.getElementById("workingTraverse");
		  workingTrav.innerHTML = clHtml;
		  aElems = workingTrav.getElementsByTagName("a");
		  
		  
		  /* any links with a=(b|d) ... cl=??? => outstandingURLS */
		  /* any links with a=d ... d=???  => docOIDS */

/*	      
		  var actionRE = new RegExp("(\\\\?|&)a=(?:d|b)(&|\$)");
		  var clRE     = new RegExp("(\\\\?|&)cl=" + cl + "(\\\\.\\\\d+)+(&|\$)");
		  var docRE    = new RegExp("(?:\\\\?|&)d=(.*?)(?:&|\$)");
*/
		  var actionRE = new RegExp("(\\\\/)(?:document|browse)(\\\\/)");
		  var clRE     = new RegExp("(\\\\/)browse\\\\/" + cl + "(\\\\/\\\\d+)+(\$)");
		  var docRE    = new RegExp("(?:\\\\/)document\\\\/(.*?)(?:\$)");
		  
		  for (var i=0; i<aElems.length; i++) {
		      var aElem = aElems[i];
		      var href=aElem.href;
		      if (href && href.match(actionRE)) {
			  if (href.match(clRE)) {
			      if (!visitedURLs[href]) {	     
			          // console.log("found a new CL line: " + href);
			          outstandingURLs.push(href);
				  visitedURLs[href] = 1;
			      } 
			  }
			  else if (href.match(docRE)) {
				if(!visitedURLs[href]){
			      var docMatch = docRE.exec(href);
			      var docOID = docMatch[1];

			      // console.log("found a new doc line: " + docOID);
				  visitedURLs[href] = 1;
			      docOIDs.push(docOID);
			  }
			  }
		      }
		  }
	      }

	      numDocOIDs = docOIDs.length;

	      var iframe = document.getElementById("iframe");

	      var docOID = docOIDs.shift();
	      //console.log("doc oid = " + docOID);
	      
	      var url;
	      if (gs2) {
	          url = "library.cgi";
	          url += "?c="+collect +"&a=d&d=" + docOID;
	      }
	      else {
	          url = "library";
	          url += "?c="+collect +"&a=d&d=" + docOID;
	          
			  /** The line below has been commented out. This is because the incorrect page is being loaded up in the iframe (i.e. just the document image and heading is being displayed but not any html customizations made in the collectionConfig.xml file**/
			  //url += "&ed=1&dt=hierarchy";
	          // url += "&excerptid=gs_content";
	      }
	      
	      //url += "&p.showExpediteeAttributes=1";
		  url += "&p.showAssocFilePath=1";

		  
	      /* load iframe with document drawn from Greenstone collection */
	      iframe.src = url;
	      
	      var progressbar = document.getElementById("progressbar");
	      progressbar.style.display = "block";


	      return false; });
	 });
      
      function pageLoaded() 
      {
	  var iframe = document.getElementById("iframe");	  
	  
	  if (iframe.src) {
	      if (iframe.style.display != "block") {
		  iframe.height = "90%";
		  iframe.style.display = "block";
	      }

	      var iframeDoc;
	      if ( iframe.contentDocument ) 
	      { /* FF */
		    iframeDoc = iframe.contentDocument;
	      }
	      else if ( iframe.contentWindow ) 
	      { /* IE */
		    iframeDoc = iframe.contentWindow.document;
	      }
		  
		  var xmlUrl = iframe.src + "&o=xml";
		  
		  var iter = (numDocOIDs - docOIDs.length);
	      var progressPercent = iter/numDocOIDs * 100;
		  
		  /*Check if a frame-id metadata element already exists, 
		  otherwise generate a new frame number based on the 
		  number of documents to process.*/
		  var frameNum = getMetadata(xmlUrl,'frameID');
		  
		  if(frameNum === null){
			frameNum = iter;
			console.log("no frameNum found, use iter: " + frameNum);
		  }else{
			console.log("frameNum metadata found: " + frameNum);
		  }
		  
	      \$(function() {
		  \$('#progressbar').progressbar({ value: progressPercent })
		 });

	      var gsContent = iframeDoc.getElementById("gs_content");

	      /*
	      var gsContentPos = getElementPosition(gsContent); 
	      var pxl = gsContentPos.xl;
	      var pxr = gsContentPos.xr;
	      */
		  
		  //Check if an assocfilepath annotation already exists on the page, otherwise obtain it from the xml.
		  var assocElem = iframeDoc.getElementById('assocfilepath');
		  var assoc = null;
		  
		  if(assocElem === undefined || assocElem === null){
			assoc = getMetadata(xmlUrl,'assocfilepath');
		  }

	      var expFrameTree = htmlToExpeditee(gsContent);

	      var expFrame = JSON.stringify(expFrameTree);
	      //alert(expFrame);

	      var collect = document.getElementById("collect").value;
	      var site    = document.getElementById("site").value;

	      var url = "cgi-bin/html-to-expeditee.pl";
	      var params = "c=" + collect;
	      if (site.match(/\\w/)) {
			params += "&site=" + site;
   	      }
		  
	      //params += "&a=generate-frame&fn=" + iter;
		  params += "&a=generate-frame&fn=" + frameNum;
	      params += "&json=" + escape(expFrame);
		  
		  //add an assocfilepath parameter but only if it is defined.
		  if(assoc !== null){
			params += "&assoc=" + assoc;
		  }

	      var clHtml = urlPostSync(url,params);

	      if (!clHtml.match(/html-to-expeditee saved frame/)) {
			alert("Error processing url: " + url);
	      }

	      if (docOIDs.length>0) {
		  var docOID = docOIDs.shift();
		  
		  // console.log("doc oid = " + docOID);

		 // is the following line used ????
		  var cl = document.getElementById("cl").value;
		  
		  var gs2 = $isGSDL2;
 	      	  var url;

	      	  if (gs2) {
	              url = "library.cgi";
	              url += "?c="+collect +"&a=d&d=" + docOID;
	     	  }
	     	  else {
	              url = "library";
	              url += "?c="+collect +"&a=d&d=" + docOID;
	              
				  /** Refer to comment earlier in this code in regards to the commented out line below.**/
				  //url += "&ed=1&dt=hierarchy";
	              // url += "&excerptid=gs_content";
	     	  }

		  //url += "&p.showExpediteeAttributes=1";
			url += "&p.showAssocFilePath=1";
		  
			iframe.src = url;
	      }
	      else {
			var progressbar = document.getElementById("progressbar");
			progressbar.style.display = "none";

			iframe.style.display = "none";
			delete iframe.src;
	      }
	  }
	 
      }
	  
	/**
	* Once this is working, remove getAssocFilePath method
	* This method is used at this stage to retrieve assocfilepath
	* and frame number metadata values from the document's xml.
	**/
	function getMetadata(xmlUrl,nameValue){
	  
		var metadata = null;
		
		 \$.ajax({
			type: "GET",
			async: false,
			url: xmlUrl,
			dataType: "xml",
			success: function(xml){
				
								
				\$(xml).find('metadata').each(function(){
					
					var name = \$(this).attr('name');
					
					if(name === nameValue){
						if(metadata === null){
							metadata = \$(this).text();
							//console.log(metadata);
						}
						
					}	
				});
				
			}
			
		  });
		
		return metadata;
	  }

    </script>

    <div id="progressbar" width="100%" 
          style="display: none; margin: 10px; height: 10px;"></div>
    <div id="workingTraverse" style="display: none"></div>

    <hr style="margin: 10px;">

    <iframe width="100%" id="iframe" style="display: none;" 
            onload="pageLoaded()"></iframe>

  </body>
</html>
EOT

    print "Content-type:text/html\n\n";
    print $html_form;
}

sub main
{

#    $ENV{'QUERY_STRING'} = "a=...";set-import-metadata&c=espresso-music&d=HASH012d6f72cde5dc48162f4a1d.1&metaname=annotation&metapos=0&metavalue=adfadfad";
#    $ENV{'REQUEST_METHOD'} = "GET";

    my $gsdl_cgi = new gsdlCGI();

    # Load the Greenstone modules that we need to use
    $gsdl_cgi->setup_gsdl();

    my $gsdlhome = $ENV{'GSDLHOME'};    
    $gsdl_cgi->checked_chdir($gsdlhome);

    require cgiactions::HtmlToExpediteeAction;
    
    # Useful debug statement for seeing what packages have been included
####    printf("%-45s%-s\n",$_,$INC{$_}) foreach (sort keys %INC);
    
    $gsdl_cgi->parse_cgi_args();

    # We don't want the gsdlCGI module to return errors and warnings in XML
    $gsdl_cgi->{'xml'} = 0;

    my $fn = $gsdl_cgi->clean_param("fn");     # frame number

    if (defined $fn) {

	my $action = new HtmlToExpediteeAction($gsdl_cgi,$iis6_mode);

	$action->do_action();
    }
    else {
	# generate form, pre-filled out with any useful values such
	# as the collection and classifier value 

	my $collect = $gsdl_cgi->clean_param("collect");   
	my $cl = $gsdl_cgi->clean_param("cl"); 
	
	# Establish collect_dir using defining 'site' along the way if GS3

	my $site = undef; 
	my $isGSDL2 = undef;

	if ($gsdl_cgi->greenstone_version() == 2) { 
	    $isGSDL2 = 1;
	}
	else {
	    $isGSDL2 = 0;
	    
	    # GS3 (and possible future versions) make use of 'site'
	    $site = $gsdl_cgi->clean_param("site");   
	    if (!defined $site) {
		$gsdl_cgi->generate_error("No site specified.");
	    }
	}

	generate_html_form($isGSDL2,$site,$collect,$cl);
    }
}



&main();
