#!/usr/bin/perl

# Functions for writing TOCs

# Things to do 1/8/2009
# suppbannerright menu is no longer being used; remove code for it

print "in toc.pl: numChapters = $numChapters\n";
print "in toc.pl: itemType = $itemType\n";
print "in toc.pl: csv = $csv\n";
print "in toc.pl: ccTOCDiv = $ccTOCDiv\n";

# csv was passed in as a series of ASCII values separated by underscores
# we need to translate that back into "pepper's secret code" (the ASCII chars themselves)
$new_csv = "";
@csv = split("_", $csv);
foreach $c (@csv) {
	$new_csv .= chr($c);
}
$csv = $new_csv;
print "csv: $csv\n";
# also need to escape @ lest it be mistaken for an array
$csv =~ s`@`\@`;


require "../_config.pl"; # load config settings.

our ($book, $output_tmp_dir, $ebooks_root_dir, $sections_dir);

# Variables to hold the chapter and title we're working on.
# We'll set them in init_toc_for_chapter
my ($chapter, $chapTitle);

# Variable to hold the elements (sections + supplementals) that
# will go in the TOC.
my @elements;

# Variable to hold the section index of the last-processed section
my $sectionIndex;

# Variable to hold the topTitle of the last-processed (i.e. current) section
my $topTitle;

sub Init_TOC_For_Chapter() {
	# Set $chapter and $chapTitle
	($chapter, $chapTitle) = @_;
	
	# Initialize @elements and $sectionIndex
	@elements = ();
	$sectionIndex = $chapter * 100;
}

sub Add_To_TOC() {
	# 1st argument is always $type; other arguments depend on type
	my ($type, @args) = @_;
	
	# Set up a temporary element, and assign type
	my %element;
	$element{type} = $type;
	
	# Some stuff we do for all sections
	
	# ALL sections are now passing following info
	#	0			1			2			3		4			5			6
	# $sec_page, $top_title, $sec_num,$sec_title, $sec_part, $alt_title, $toc_title
	
	# 2nd argument should always be pageNum and 3rd argument the "topTitle" for the section
	if ($type =~ /^section/) {
		$element{pageNum} = $args[0];
		++$sectionIndex;
		$element{sectionIndex} = $sectionIndex;
		
		# We just need to store the topTitle for supplemental items that are in the section
		$topTitle = $args[1];

		$element{inSuppWindow} = 0;		# Sections don't open in the supp window, so they don't go in its TOCs
		
		# Now do specific stuff for specific sections
		
		################################################################
		# THIS PART NEEDS TO BE GENERALIZED
		################################################################
		# Normal section
		# 4th, 5th, and 6th arguments should be section number, title,
		# and part (if present)
		if ($type eq "sectionnormal" || $type eq "sectionunnumbered") {
			$element{number} = $args[2];
			$element{title} = $args[3]; # we're using titles from toc, not from XML
			# Deal with part. If given, store part and numParts
		      	if ($args[4]) {
				$args[4] =~ m`(\d+)/(\d+)`;
				$element{part} = $1;
				$element{numParts} = $2;
			# Otherwise use 1 for both (i.e. "part 1/1")
			} else {
				$element{part} = 1;
				$element{numParts} = 1;
			}
			
			# For unnumbered section, set fullWidth to 1
			if ($type eq "sectionunnumbered") {
				$element{fullWidth} = 1;
			}

		} elsif ($type =~ /section(\w+)/)  {
			$element{number} = $args[2];
			$element{title} = $args[3];
			$element{fullWidth} = 1;

		}
		
		
	# Supplemental items: We need to do different things for different types, so call a function
	# to parse the args here.
	} else {
		%element = Create_Supp_Element($type, @args);
	}
	
	# Add the newly created element to the global array
	push(@elements, \%element);
}

# Create all the stuff we'll need below for various types of supplemental items
sub Create_Supp_Element() {
	# note that the vars below are the arguments that must be passed in to Add_To_TOC()
	# for supplemental items.
	my ($type, $number, $compTitle, $title, $link, $url, $abbrDesc) = @_;

	my %element;
	$element{type} = $type;				# type as entered in icon tag
	$element{number} = $number;			# number with chapter -- e.g. "3.4"
	$element{compTitle} = $compTitle;	# "[comp]anion website" title -- e.g. "PsychInquiry"
	$element{title} = $title;			# Full title -- e.g. caption for figure; box title for box

	# Note that the following two things are global variables in this file, 
	# which should always be set approprately when Create_Supp_Element is called.
	$element{sectionIndex} = $sectionIndex;	# Section index for the section in whith the item occurs.
	$element{sectionTopTitle} = $topTitle;	# Section number (for numbered section) or name (unnumbered section) in which the item occurs

	$element{inSuppWindow} = 1;			# Supplementals open in the supp window, so they have to go in its TOCs

	# Unless otherwise specified, we WILL add the item to the left TOC (and main text TOC)	
	$element{inLeftTOC} = 1;

	$number =~ /(\d+)\.?(\d+)?/;
	my ($chapter, $suppnumber) = ($1, $2);
	$element{chapter} = $chapter;
	$element{suppnumber} = $suppnumber;

	# web -- these are links to BCS (ideally)
	if ($type =~ /^web/) {
	
		# some are links to BCS, some are URLs not on BCS
		if ($link) {
	
			$element{jsArgs} = "'bcs','$title','$link'";	# arguments for javascript OpenSupp call
			$element{supptocTitle1} = $title;	# First part of title for supp TOC
			$element{supptocTitle2} = "";		# second part of title for supp TOC
			$element{showSection} = 0;		# Whether or not to show the section number in the supp TOC
			$element{suppGroup} = "other";	# supp toc group
			#$element{menuEntry} = qq`<option value="bcs,$title,$link">$abbrDesc</option>`;	# entry for suppbannerright

		} elsif ($url) {
		
				$element{jsArgs} = "'url','$url'";	# arguments for javascript OpenSupp call
			$element{supptocTitle1} = $title;	# First part of title for supp TOC
			$element{supptocTitle2} = "";		# second part of title for supp TOC
			$element{showSection} = 0;		# Whether or not to show the section number in the supp TOC
			$element{suppGroup} = "other";	# supp toc group
			#$element{menuEntry} = qq`<option value="url,$url">$abbrDesc</option>`;	# entry for suppbannerright
			
		}	
	
	# boxes 
	} elsif ($type =~ /^BOX(.*)/) {

		$element{jsArgs} = "'box',$chapter,$suppnumber";

		# instance variables
		my $tmpNumber = $number;
			
		$element{tocTitle1} = $title;
		$element{supptocTitle1} = $title;
		$element{showSection} = 1;
		$element{suppGroup} = "box";
		#$element{menuEntry} = qq`<option value="box,$chapter,$suppnumber">$abbrDesc</option>`;
	
	
	# notes - All notes for chapter
	} elsif ($type =~ /^notes/) {
		$element{jsArgs} = "'notes',$chapter";
		$element{suppnumber} = "";
		$element{tocTitle1} = "Notes";
		$element{tocTitle2} = "";		
		$element{supptocTitle1} = "Notes";
		$element{supptocTitle2} = "";
		$element{showSection} = 0;
		$element{suppGroup} = "other";
		#$element{menuEntry} = qq`<option value="notes">Notes</option>`;
	
	# supptoc - the supplemental TOC
	} elsif ($type =~ /^supptoc/) {
		$element{jsArgs} = "'toc',$chapter";
		$element{suppnumber} = "";
		$element{tocTitle1} = "Resource Table of Contents";
		$element{tocTitle2} = "";		
		$element{suppGroup} = "none";
		# Don't put the supp TOC in the supp TOC, lest we lead students into an infinite loop
		$element{inSuppWindow} = 0;
	
	# Figures
	} elsif ($type =~ /^figure/) {
	
		# instance variables
		my $tmpNumber = $number;
	
		$element{jsArgs} = "'figure',$chapter,$suppnumber";
		$element{inLeftTOC} = 0;
		$element{supptocTitle1} = "Figure $tmpNumber";
		$element{supptocTitle2} = "$title";
		$element{showSection} = 1;
		$element{suppGroup} = "figure";
		#$element{menuEntry} = qq`<option value="figure,$suppnumber">Figure $tmpNumber</option>`;
	
	# Tables
	} elsif ($type =~ /^table/) {
	
		# instance variables
		my $tmpNumber = $number;
		
		$element{jsArgs} = "'table',$chapter,$suppnumber";
		$element{inLeftTOC} = 0;
		$element{supptocTitle1} = "Table $tmpNumber";
		$element{supptocTitle2} = "$title";
		$element{showSection} = 1;
		$element{suppGroup} = "table";
		#$element{menuEntry} = qq`<option value="table,$suppnumber">Table $tmpNumber</option>`;
		
	} else {
		print "Unknown supplemental: '$type' - '$number' - '$title'\n";
		exit;
	}
	
	if (!$element{jsArgs}) {
print "ERROR: must define element{jsArgs} for '$type' - '$number' - '$title'\n";
		exit;
	}

	return %element;
}

# *****************************************************************************
sub Write_TOC_Temps() {
	# Print the elements out to the screen
print "\n\n TOC:\n";
	for my $element (@elements) {		
print "-$element->{type}- $element->{number}: $element->{compTitle} \"$element->{title}\": ($element->{pageNum})\n";
	}
print "\n";

	# Variable to hold content	
	my $content;
			
	# Prepend 0 to chapters < 10, so that the cat will work properly when combining them
	my $chap_fn;
	if ($chapter < 10) {
		$chap_fn = "0$chapter";
	} else {
		$chap_fn = $chapter;
	}
	
	
	# Write temp file for cms_sectioninfo.php
	$content = "\n";
	my $previousSection = "";
	for my $element (@elements) {
		if ($element->{type} =~ /^section/) {
			# key
			(my $key = $element->{number}) =~ s/\./_/g;
			# If section has a part > 1, add it to the filename
			if ($element->{part} > 1) {
				$key .= "-$element->{part}";
			}

			# If previousSection isn't empty, we need to finish the last element's entry
			# with 'nextSection' pointing to this section.
			if ($previousSection ne "") {
				$content .= ", 'nextSection' => '$key'),\n";
			}
			
			# sectionId
			my $sectionId = $element->{sectionIndex};
			
			# sectionTitle
			my $sectionTitle = $element->{title};
			unless ($element->{number} =~ /\.0$/) {
				$sectionTitle = $element->{number} . " " . $sectionTitle;
			}

			if ($element->{numParts} > 1) {
				$sectionTitle .= " ($element->{part} / $element->{numParts})";
			}
			
			# Add content
			$content .= "\t'$key' => array('sectionId' => $sectionId, 'sectionTitle' => '$sectionTitle', 'previousSection' => '$previousSection'";
			
			# Set previousSection to the current key
			$previousSection = $key;
		}
	}
	
	# Add end of last entry
	$content .= ", 'nextSection' => ''),";

	open(TEMP, "> ${output_tmp_dir}cms_sectioninfo_${chap_fn}.tmp") or die("Couldn't open sectionsinfo.php file");
	print TEMP $content;
	close(TEMP);
	
	#--------------------------------
	# Write temp file for sections.js
	$content = "";
	for my $element (@elements) {
		if ($element->{type} =~ /^section/) {
			my $index = $element->{sectionIndex};
			(my $fn = $element->{number}) =~ s/\./_/g;
			# If section has a part > 1, add it to the filename
			if ($element->{part} > 1) {
				$fn .= "-$element->{part}";
			}
			my $pageNum = $element->{pageNum};

			open(TOC, "${output_tmp_dir}/TOC.txt") || die ("Cannot open TOC.txt $!");
			@toc_lines = <TOC>;
			$toc_lines = @toc_lines;
			close TOC;
			
			########################################################
			# COLLAPSIBLE
			########################################################
			if ($left_toc_type eq "collapsible") {

			my $subsections = 0;
			for ($i = 0; $i <= $toc_lines; $i++) {
					
					if ($toc_lines[$i] =~ /^((\d+)\.(\d+))\s+/) {
						
						$toc_file = $1;
						$toc_file =~ s`\.`_`g;
						
						if ($toc_file eq $fn) {
						
							if ($toc_lines[$i + 1] =~ m/^((\d+)\.(\d+))\s+/) {
								$nl = 1;
							} elsif ($toc_lines[$i + 1] =~ m/^((\d+)\.(\d+)\.(\d+))\s+/) {
	
								$nl = 2;
							} else {
								$nl = 0;
							}
						}
						
					}
	
				}		
				
				my $par = "";
				if ($fn =~ m/(\d+)_(\d+)_(\d+)/) {
					$par = $1 . "_" . $2;
					$subsections = 0;
				}
				
			} else {
			
			########################################################
			# BSM-style
			########################################################
				# we need to add attribute jt (jump to) to sections.js, using TOC
				
				# format of TOC is
				# [section number] [section name] [page no]
				
				my $section_name = "";
				my $tmp_section_name = "";
						 
				my $subsections = 0;
				for ($i = 0; $i <= $toc_lines; $i++) {
					
					if ($toc_lines[$i] =~ /^((\d+)([a-z]))\s+(.*?)\s+(\d+)/) {
						
						$toc_file = $1;
						$tmp_section_name = $4; # for jt
	
						$toc_file =~ s`\.`_`g;
						
						if ($toc_file eq $fn) {
						
							$section_name = $tmp_section_name;
						
							if ($toc_lines[$i + 1] =~ m/^((\d+)\.(\d+))\s+/) {
								$nl = 1;
							} elsif ($toc_lines[$i + 1] =~ m/^((\d+)\.(\d+)\.(\d+))\s+/) {
	
								$nl = 2;
							} else {
								$nl = 0;
							}
						}
						
					}
					
					
	
				}	

			}

			my $found_bt = 0;	
			if ($use_special_bookmarks) { # this is set in _config.pl
				
				# bookmark titles
				open (BM, "$bookmarks_csv_file") || die ("Cannot open bookmarks $!");
				my @bm = <BM>;
				close BM;
				
				my $bt;
				
				foreach $bm (@bm) {
				
					my $tmp_fn = $fn;
					if ($tmp_fn =~ /(\d+)_0/) {
						$tmp_fn = $1;
					}
					$tmp_fn =~ s`_`\.`;
				
					if ($bm =~ /"${tmp_fn}","([^"]*)","([^"]*)"/) {
					
						$bt = $2;
						$found_bt = 1;
						
					}
					
				}
			}
			
				
				
			if (!$found_bt && $use_special_bookmarks) {
				print "could not find bookmark title for section $fn\n";
				exit;
			}
			my $par = "";
			
			# for use with collapsible TOCs
			if ($fn =~ m/(\d+)_(\d+)_(\d+)/) {
				$par = $1 . "_" . $2;
			} 

			my $jt = $fn;
			# for intro sections, e.g. 35_0, jt should just be 35
			# these are part openers....what to do?
			if ($fn =~ /^(\d+)_0$/) {
				$jt = "";
			# these are chapter openers
			} elsif ($fn =~ /^(\d+)_0_0$/) {
				$jt = $1;
			}
			
			if (!$fn || !$pageNum) {
				$all_errors .= "Missing fn:$fn and/or pageNum:$pageNum for sections.js\nTry adding a pgnum tag beneath the title of this section in source XML.  Also check TOC.txt";
			}

			$jt =~ s`_`\.`;
			
			# Non-integer page numbers break section.js, they end up
			# as array indicies. Fix page numbers like iii, A-2... -MZ
            # The goto page box in ebook will not work.
			if ( $pageNum !~ m/^\d+$/ ) {
				    $pageNum = 2000 + $index;
			}
			
			
			if ($par) {
		
				$content .= "\tsections[$index] = {fn:'$fn', par:'$par'}; pages[$pageNum] = $index;\n";
				
			} else {
			
				
				$content .= "\tsections[$index] = {fn:'$fn', nl:$nl}; pages[$pageNum] = $index;\n";
			
			}		

			# if nl is undefined, we don't want it in sections.js
			$content =~ s`, nl:0``g;
			$content =~ s`, nl:\}`\}`g;
			

			
			
		}
	}
	
	open(TEMP, "> ${output_tmp_dir}sections_${chap_fn}.tmp") or die("Couldn't open sections.js file");
print TEMP <<EOF;
completedChapters[$chapter] = true;
if (ca($chapter)) {
$content
}

EOF
	close(TEMP);
	
	#-----------------------------------------
	# Write temp file for chapterContents.html
	open(TEMP, "> ${output_tmp_dir}cc_${chap_fn}.tmp") or die("Couldn't open chapterContents file");

	print TEMP cc_Title($chapter, $chapTitle)
		. Contents_Body()
		. "</table>\n</div>\n\n";

	close(TEMP);
	
	#-----------------------------
	# Write temp file for 0_1.php
	open(TEMP, "> ${output_tmp_dir}0_1_${chap_fn}.tmp") or die("Couldn't open 0_1 file");
	
	my $contents_body = Contents_Body();
	$contents_body =~ s`<img src="../common/nothing.gif"[^>]*>``g;
	$contents_body =~ s`<img[^>]*src="pics/dropSmallRight.gif"[^>]*>``g;

	# Start the chapter with a PHP line setting a $c[] element
	print TEMP 
		qq`\$c[$chapter] = <<<EOF\n`
		. TOC_Chapter_Title($chapter, $chapTitle, 1)
		. $contents_body
		. "</table>\n</div>\n\n"
		. "EOF;\n";
	
	close(TEMP);

	#-----------------------------
	# Write temp file for supptoc.php
	open(TEMP, "> ${output_tmp_dir}supptoc_${chap_fn}.tmp") or die("Couldn't open supptoc file");
	print TEMP supptoc_Contents();
	close(TEMP);
}

# *****************************************************************************
# Chapter title for chaptercontents.html
sub cc_Title {
	my ($chapter, $chapterTitle) = @_;
	# instance variables
	my $tmpChapter = $chapter;
	my $tmpChapterTitle = $chapterTitle;

	# for parts, decrement $tmpChapter by $numChapters to get part number
	if ($itemType eq "part") {
		$tmpChapter = $tmpChapter - $numChapters;
	} elsif ($itemType eq "appendix") {
		$tmpChapter = $tmpChapter - $numChapters - $numParts;
	} elsif ($itemType eq "partReview") {
		$tmpChapter = $tmpChapter - $numChapters - $numParts - $numAppendices;
	} elsif ($itemType eq "frontMatter") {
		$tmpChapter = $tmpChapter - $numChapters - $numParts - $numAppendices - $numParts;
	}




	# WHF-style
	if ($publisher eq "WHF" || $publisher eq "WOR") {

		return <<EOF;
<div id="div$chapter" class="na">
<table width="100%" style="margin:0px"><tr><td class="cn">$tmpChapter&nbsp;</td><td width="95%" class="ct">$tmpChapterTitle</td></tr>

EOF

	# BSM-style
	} else {
		return "";
	}

}

# *****************************************************************************
# Chapter title for 0_1.html
sub TOC_Chapter_Title {
	my ($chapter, $chapterTitle, $done) = @_;
	my ($type, $tocimg, $link);
	# instance variables
	my $tmpChapter = $chapter;
	my $tmpChapterTitle = $chapterTitle;


	# for parts, we change $chapter_is_called to Part and decrement $tmpChapter by $numChapters to get part number
	if ($itemType eq "part") {
		$chapter_is_called = "Part";
		$tmpChapter = $chapter - $numChapters;
	} elsif ($itemType eq "appendix") {
		$chapter_is_called = "Appendix";
		$tmpChapter = $chapter - $numChapters - $numParts;
	} elsif  ($itemType eq "partReview") {
		$chapter_is_called = "Part Review";
		$tmpChapter = $chapter - $numChapters - $numParts - $numAppendices;
	} elsif  ($itemType eq "frontMatter") {
		$chapter_is_called = "Front Matter";
		$tmpChapter = $chapter - $numChapters - $numParts - $numAppendices - $numParts;
	}

	
	$link = qq`<a class="cn" href="JavaScript:DD('$chapter')"><img name="dd$chapter" src="../pics/dropBigRight.gif" alt="" width="10" height="10" border="0">&nbsp;${chapter_is_called} $tmpChapter</a>`;
	
	if (!$done) {
		$link = qq`<span class="cn"><img name="dd$chapter" src="../pics/nothing.gif" alt="" width="10" height="10" border="0">&nbsp;$type $chapter.</a>`;
	}
	
		my $html = <<EOF;
<table cellpadding="0" cellspacing="0" border="0">
	$tocimg
	<tr>
		<td class="cttd">
			$link
		</td>
		<td class="cttd" width="95%">
			<a class="ct" href="JavaScript:top.JumpToChapter($chapter)">$chapterTitle</a>
		</td>
	</tr>
</table>
EOF

	if ($done) {
		$html .= <<EOF
<div id="div$chapter" class="cd">
<table>
EOF
	}
	
	return $html;
}

# *****************************************************************************
# Contents body for both the chapterContents file and the 0_1 file
sub Contents_Body {

	# TOC types:
	
	# WHF
	# 1) sections #.# or #-#
	# 2) sections #.# with boxed parts
	# 3) sections #.# with unnumbered sections
	# 4) sections #.#, expandable to #.#.#

	# BSM 
	# 5) a, b heads
	# 6) a, b, c, d heads
	
	# at first, let's just do WHF or BSM, set in _config.pl

	my ($chapTitle) = @_;
	my $contents = "";

	###################################################################
	# Add elements one by one
	###################################################################
	for my $element (@elements) {
		my $type = $element->{type};
	
		# For sections...
		if ($type =~ /^section/) {

			# If the section is multi-part, only do an entry for the first part
			if ($element->{part} > 1) {
				next;
			}
			
			my ($number, $sectionIndex, $title, $fullWidth, $tocTitle) = 
				($element->{number}, $element->{sectionIndex}, $element->{title}, $element->{fullWidth}, $element->{tocTitle});
			
			
			# Form td id - substitute "_" for "." or "-" in $number
			(my $id = $number) =~ s/[.-]/_/g;
			# Remove whitespace, if any, from title
			$title =~ s`^\s*(.*?)\s*$`\1`;
			
			
			########################################################
			# BEDFORD-ish TOCs ... this one taken from Rules 6e/SMH?
			########################################################
			if ($publisher eq "BSM") {

				# title in TOC is different from title only in a few (BSM) books....
				
				if (!$tocTitle) {
					$tocTitle = $title;
					if ($has_toc_titles) { # set in _config.pl
						$all_errors .= "failed to find tocTitle for $title\n";
					}
				}
				
				if (!$title) {
					$all_errors .= "no title for $number\n";
				}
			
				##################### INTRO/PART HEAD
				if ($number =~ /^(\d+)\.0$/) {
				
					my $chap_number = $1;
	
					if ($ahead_div_open) {
						$contents .= qq`</div><!-- closing ahead div-->`;
						$ahead_div_open = 0;
					}
					
					if ($part_div_open) {
						$contents .= qq`</div><!-- closing part div-->`;
						$part_div_open = 0;
					}
					
					$contents .= <<EOF; 
					
					<div class="parthead" id="tda${chap_number}_0"><a href="Javascript:EP($chap_number)"><img name="dd$chap_number" src="pics/dropSmallRight.gif" width="13" height="14" border="0" align="absbottom"></a><a href="Javascript:LS($sectionIndex)" class="partTitle">$title</a></div>
					<div id="div$chap_number" class="na"><!-- opening part div -->
EOF
					$part_div_open = 1;
	
				##################### A-HEAD
				} elsif ($number =~ /^(\d+)\.0\.0$/) {
				
					my $chap_number = $1;
					
					if ($ahead_div_open) {
						$contents .= qq`</div><!-- closing ahead div-->`;
						$ahead_div_open = 0;
					}
					
					$contents .= <<EOF;
					<div class="ahead" id="tda$id"><a href="Javascript:DD('$id')"><img name="dd$id" src="pics/dropSmallRight.gif" width="13" height="14" border="0" align="absbottom"></a><a href="Javascript:LS($sectionIndex)">${chap_number}: ${chapTitle}</a></div>
					<div id="div$id" class="na"><!-- opening ahead div -->
	
EOF
					$ahead_div_open = 1;

				##################### B-HEAD
				} elsif ($number =~ /(\d+)([a-z])/) {
					
					$contents .= qq`<div class="bhead" id="tda$id"><a href="Javascript:LS($sectionIndex)">$number: $tocTitle</a></div>`;
				
				##################### SOURCE MAP
				} elsif ($number =~ /^(\d+)\.5(\d+)$/) {
				
					$contents .= <<EOF;
	<div class="ahead" id="tda$id"><a href="Javascript:LS($sectionIndex)">$title</a></div>
	<div id="div$id" class="na">
	</div>
EOF
				}
				
			########################################################
			# WHFREEMAN-ish TOCs
			########################################################
			} elsif ($publisher eq "WHF" || $publisher eq "WOR") {
			
				if (!$left_toc_type) {
			
					########################################
					# STANDARD WITH POSSIBLE PARTS							
					########################################
					# If the section is multi-part, add numbers for sub-heads
					my $subHeads = "";
					if ($element->{numParts} > 1) {
						$subHeads = '<div class="shaD">';
						for (my $i = 0; $i < $element->{numParts}; ++$i) {
							my $pn = $i + 1;
							$subHeads .= '<span id="tdc' . $id . 'p' . $pn . '" class="shs"><a class="sha" href="JavaScript:LS(' . ($sectionIndex + $i) . ')">' . $pn . '</a></span> ';
						}
						$subHeads .= '</div>';
					}
					
					# For some sections, the title spans both columns
					if ($fullWidth) {
						# And some of these need special formatting
						my $tdClass = "";
						$id =~ /\d+_(\d+)/;
						my $secNum = $1 * 1;
						$contents .= <<EOF;
			<tr>
				<td$tdClass id="tda$id" colspan="2">
					<a href="JavaScript:LS($sectionIndex)">$title</a>$subHeads
				</td>
			</tr>
EOF
					# Numbered sections -- number goes in first column, title in second
					} else {
						 my $tmp_sec_num = $number;
						# If this is a part, not a chapter, adjust sec_num using numChapters
						my ($sec_num_end) = $number=~ /^\d+(.*?)$/;
						if ($itemType eq "part") {
							$tmp_sec_num = ($chapter - $numChapters) . $sec_num_end;
						} elsif ($itemType eq "appendix") {
							$tmp_sec_num = ($chapter - $numChapters - $numParts) . $sec_num_end;
						} elsif ($itemType eq "partReview") {
							$tmp_sec_num = ($chapter - $numChapters - $numParts - $numAppendices) . $sec_num_end;
						} elsif ($itemType eq "frontMatter") {
							$tmp_sec_num = ($chapter - $numChapters - $numParts - $numAppendices - $numParts) . $sec_num_end;
						}


						# For x.x.x, no line above
						my $tdClass = "";
						if ($number =~ /\d+[\.-]\d+[\.-]\d+/) {
							$contents .= <<EOF;
			<tr><td id="tda$id" class="lev2secs" colspan="2"><table><tr>
				<td class="noBorder">
					<span class="sn">$number</span>
				</td>
				<td class="noBorder" width="100%">
					<a href="JavaScript:LS($sectionIndex)">$title</a>$subHeads
				</td>
			</tr></table></td></tr>
EOF
						} else {
							$contents .= <<EOF;
			<tr>
				<td id="tda$id">
					<span class="sn">$tmp_sec_num</span>
				</td>
				<td id="tdb$id" width="100%" class="st a-title">
					<div class="ltoc"><a href="JavaScript:LS($sectionIndex)">$title</a></div>$subHeads
				</td>
			</tr>
EOF
						}
					}
					
				################################################
				# COLLAPSIBLE				
				################################################
				} elsif ($left_toc_type eq "collapsible") {
				
					# For some sections, the title spans both columns
				if ($fullWidth) {
	
				    # chapter 1 has no self-quiz
				    if ($number =~ /(\d+)\.51/ || $number eq "1.52") {
					$contents .= $supplementals;
					$supplementals = "";
				    }
	
					# if this is #.50, need <div id="divT#_XXX"></div> where XXX is most recent section
					
					if ($number =~ /(\d+)\.50/) {
					    if ($supplementals) {
						if ($added_subsection_div) {
						    $contents .= qq`</table></div>`;
						    $added_subsection_div = 0;
						    print "closed subsection div: $number\n";
						}
						$contents .= $supplementals;
					    $supplementals = "";
					    }
	
						$contents .= <<EOF;
					<div id="divT${tmp_id}"></div>
EOF
			
					}
					
					if ($added_subsection_div) {
						
							# close it
							print "closed subsection div: $number\n";
							
							$contents .= <<EOF;
	</table>
	</div>
EOF
	
							$added_subsection_div = 0;
							
					}
					
					if ($table_is_open) {
					
						$contents .= <<EOF;
	<tr><td id="tda$id"><span class="sn"><nobr><img src="../common/nothing.gif" alt="" width="8" height="8" border="0"></nobr></span></td><td id="tdb$id" width="100%"><a href="JavaScript:LS($sectionIndex)">$title</a></td></tr></table>
EOF
	
						$table_is_open = 0;
						
					} else {
					
						$contents .= <<EOF;
	<table><tr><td id="tda$id"><span class="sn"><nobr><img src="../common/nothing.gif" alt="" width="8" height="8" border="0"></nobr></span></td><td id="tdb$id" width="100%"><a href="JavaScript:LS($sectionIndex)">$title</a></td></tr></table>
EOF
	
					}
	
	
				# Numbered sections -- number goes in first column, title in second
				} else {
	
					# For x.x.x, no line above
					my $tdClass = "";
					if ($number =~ /(\d+\.\d+)\.\d+/) {
					
						$tmp_id = $1;
						$tmp_id =~ s`\.`_`;
						
						if (!$added_subsection_div) {
							
							print "opened subsection div: $number\n";
							$contents .= <<EOF;
	<div id="div$tmp_id" class="na subsection">
	<table>
	
EOF
	
							$added_subsection_div = 1;
						}
							
					
						$contents .= <<EOF;
	<tr><td id="tda$id" class="noBorder"><span class="sn">&nbsp;$number</span></td><td id="tdb$id" class="noBorder" width="100%"><a href="JavaScript:LS($sectionIndex)">$title</a></td></tr>
EOF
					} else {
					
						if ($added_subsection_div) {
						
							# close it
							print "closed subsection div: $number\n";
							
							$contents .= <<EOF;
	</table>
	</div>
EOF
	
							$contents .= $supplementals;
							$supplementals = "";
							$added_subsection_div = 0;
							
						}
						
						
						 # if there are subsections, add link & arrow
						 open(TOC, "${output_tmp_dir}TOC.txt");
						 @toc_lines = <TOC>;
						 close TOC;
						 
						 $subsections = 0;
						 foreach $line (@toc_lines) {
						 	if ($line =~ /^${number}\.\d+/) {
						 		$subsections = 1;
						 	}
						 }
						 
						 ($chapter, $divT_no) = $id =~ /(\d+)_(\d+)/;
						 
						 $divT_no--;
						 $divT_no = $chapter . "_" . $divT_no;


						 my $tmp_sec_num = $number;
						# If this is a part, not a chapter, adjust sec_num using numChapters
						my ($sec_num_end) = $number=~ /^\d+(.*?)$/;
						if ($itemType eq "part") {
							$tmp_sec_num = ($chapter - $numChapters) . $sec_num_end;
						} elsif ($itemType eq "appendix") {
							$tmp_sec_num = ($chapter - $numChapters - $numParts) . $sec_num_end;
						} elsif ($itemType eq "partReview") {
							$tmp_sec_num = ($chapter - $numChapters - $numParts - $numAppendices) . $sec_num_end;
						} elsif ($itemType eq "frontMatter") {
							$tmp_sec_num = ($chapter - $numChapters - $numParts - $numAppendices - $numParts) . $sec_num_end;
						}



						 if ($subsections) {
					
							$contents .= <<EOF;
	<div id="divT${divT_no}"></div><table><tr><td id="tda$id"><a class="sn" href="JavaScript:DD('$id')"><nobr><img name="dd$id" src="pics/dropSmallRight.gif" alt="" width="8" height="8" border="0">&nbsp;$tmp_sec_num</nobr></a></td><td id="tdb$id" width="100%"><a href="JavaScript:LS($sectionIndex)">$title</a></td></tr></table>	
EOF
	
						} else {
						
						$contents .= <<EOF;
	<div id="divT${divT_no}"></div><table><tr><td id="tda$id" class="sn"><nobr><img name="dd$id" src="pics/nothing.gif" alt="" width="8" height="8" border="0">&nbsp;$tmp_sec_num</nobr></td><td id="tdb$id" width="100%"><a href="JavaScript:LS($sectionIndex)">$title</a></td></tr></table>	
EOF
						}
					}
				}	
						
			}
			
		}
			
		# Otherwise it's a supplemental, so add it if we're supposed to (for REF we're not)
		# except that now they want directories in left TOC
		
		} 
		
		elsif ($element->{inLeftTOC}) {
			my ($jsArgs, $title1, $title2) = ($element->{jsArgs}, $element->{tocTitle1}, $element->{tocTitle2});
			
			if ($title1 =~ /directory/i) {
				print "adding directory\n";

				# strip coloring from title2
				$title1 =~ s`<span style='color:#000000'>Directory to</span>`Directory to`;

			# Add a link to title2, if given (used for boxes and supps with compTitles)
				if ($title2 ne "") {
					$title2 = qq`<a href="JavaScript:top.OpenSupp($jsArgs)">$title2</a>`;
				}
				
				if ($table_is_open) {
					$contents .= "</table>";
					$table_is_open = 0;
				}
				
				$contents .= <<EOF;
	<div class="directory"><a href="JavaScript:top.OpenSupp($jsArgs)">$title1</a> $title2</div>
EOF
	
			}
		}

	}
	
	if ($added_subsection_div) {
		$contents .= qq`</table></div>`;
		print "closed subsection div\n";
	}

	return ($contents);
}

# *****************************************************************************
# Combine the TOC temp files from all chapters
sub Combine_TOC_Temps () {
	my $content;

	#print "book_status in Combine_TOC_Temps = $book_status\n";
	# we replaced spaces with underscores in this in the console; remove them now
	$book_status =~ s`_` `g;
	
	
	#================================
	# sectioninfo.php
	#$content = `cat ${output_tmp_dir}cms_sectioninfo_*`; # doesn't work in Windows?
	$content = get_content("cms_sectioninfo_");

	open(OUT, "> ${ebooks_root_dir}cms_sectioninfo.php");
print OUT <<EOF;
<?
\$sections = array(
$content
);
?>
EOF
	print "Wrote cms_sectioninfo.php\n";
	close(OUT);
	
	#================================
	# textboxPrompts.php
	$content = get_content("tbp_"); ### <- `cat ${output_tmp_dir}sections_*`;
	
	open(OUT, "> ${ebooks_root_dir}textboxPrompts.php");
print OUT <<EOF;

<?

\$prompts = Array();

$content

?>

EOF
	print "Wrote textboxPrompts.php\n";
	close(OUT);

	#================================
	# sections.js
	$content = get_content("sections_"); ### <- `cat ${output_tmp_dir}sections_*`;
	
	open(OUT, "> ${ebooks_root_dir}sections.js");
print OUT <<EOF;
var completedChapters = new Array();
var sections = new Array();
var pages = new Array();
	sections[1] = {fn:'../0_0'};
	pages[1] = 1;
	sections[2] = {fn:'0_1'};
	pages[1] = 2;

$content
EOF
	print "Wrote sections.js\n";
	close(OUT);

	#================================
	# chaptercontents.html
	$content = get_content("cc_"); ### <- `cat ${output_tmp_dir}cc_*`;
	
	# PW 9/26/08: moved styles into mainstyles.css
	open(OUT, "> ${ebooks_root_dir}chaptercontents.html");
print OUT <<EOF;
<html>
	<head>
		<title>
			left frame
		</title>
		<script language="JavaScript">
			function DD(fn) {
				top.DropDownLeftSections(fn);
			}
			
			function LS(id) {
                                if (!top.sections[id]) {
                                    id++;
                                }
                                if (!top.sections[id]) {
                                    id++;
                                }
				top.LoadSection(id);
			}
			
			function EP(chapter) {
				top.DropDownChapter(chapter);
			}
		</script> 
	<link rel="stylesheet" href="styles/mainstyles.css" type="text/css">
	<link rel="stylesheet" href="styles/bookstyles.css" type="text/css"> <!-- KC: added 12/16/2008 to address IE bug -->
	</head>
	<body id="chapterContents" class="$publisher">

$ccTOCDiv <!-- ccTOCDiv, defined in config.pl -->

<div style='margin-bottom:20px; margin-left:-15px'><!-- not sure why we need that neg margin-->

$content

</div>

	</body>
</html>

EOF
	print "Wrote chaptercontents.html\n";
	close(OUT);

	#================================
	# 0_1.php
	$content = get_content("0_1_"); ### <- `cat ${output_tmp_dir}0_1_*`;

	# Status message has moved to _config.pl

	# this comes from _config.pl
	if ($make_main_TOC) {

		open(OUT, "> ${sections_dir}0_1.php");
print OUT <<EOF;
<?PHP
# Get the bookId
require_once("../../apis3/bookId.php");
?>
<html>
<head>
	<title>0.1</title>
	<meta name="generator" content="BBEdit 7.1.4">
	<link rel="stylesheet" href="../styles/mainstyles.css" type="text/css">
	<link rel="stylesheet" href="../styles/bookstyles.css" type="text/css"> <!-- KC: added 12/16/2008 to address IE bug -->
	<script language="JavaScript">top.PreInitializeSection('Contents');</script>

	<script language="JavaScript">
	// preload the arrow-bullets for the toc
	var bulrt = new Image(); bulrt.src = "../pics/dropBigRight.gif";
	var buldn = new Image(); buldn.src = "../pics/dropBigDown.gif";
	
	// Drop down the contents of a div
	function DD(div, newState) {
		if (div == "X") {
			return;
		}
		
		var style = document.getElementById("div" + div).style;
		
		// If no state specified, toggle
		if (newState == "toggle" || newState == null) {
			if (style.display == "block") {
				newState = "none";
			} else {
				newState = "block";
			}
		}
		
		// Set the display
		if (newState == "none") {
			style.display = "none";
			if (div.indexOf("_") != -1) {
				styleT.display = "block";
			}
			document["dd" + div].src = bulrt.src;
		} else {
			style.display = "block";
			if (div.indexOf("_") != -1) {
				styleT.display = "none";
			}
			document["dd" + div].src = buldn.src;
		}
	}
	
	function LS(id) {
	  //if (top.sections[id].skip != null) {
          //          id++;
          //      }
	  if (!top.sections[id]) {
	    id++;
	  }
	  if (!top.sections[id]) {
	    id++;
	  }
	  top.LoadSection(id);
	}
		
	</script>
</head>
<body id="mainTOC" onload="top.InitializeSection()">

<div class="bodyHolder1">

<div id="bmicon" style="position:absolute; top:5; left:5; display:none"><img src="../pics/bookmarkicon.gif" width="26" height="26" border="0"></div>

$toc_mast <!-- toc_mast defined in config.pl -->

<script language="JavaScript">top.WriteNotes();</script>

<p style='font-weight:bold'>$book_status</p>

<?PHP
$content

function PartString(\$i) {
	return "";
}

\$customStandardVersion = "$csv";

require_once("../../servercom/databasefns.php");
require_once("../../servercom/printtoc.php");

?>

</div>

<!-- what purpose is the code below serving now? -->
<div class="bodyHolder2" style="padding:10px 5px 0px 0px">
<div style="height:30; text-align:right; float:right">
</div>
</div>

<div style="clear: both;"></div>
</div>
</body>
</html>
EOF
		close OUT;	
	print "Wrote 0_1.php\n";
	} else {
		# don't write 0_1.php; it will be edited statically instead
		print "Did not write 0_1.php.  Using static version instead.  To write 0_1.php, change\n";
		print "setting in console\n";
	}

	#================================
	# suppbannerright.html
	$content = get_content("sbr_"); ### <- `cat ${output_tmp_dir}sbr_*`;
	
	# not writing this for now
		$content = "";

	# $sbrbc defined in _config.pl
	# PW 9/30/2008: styles moved to mainstyles.css
	
	open(OUT, "> ${ebooks_root_dir}suppbannerright.html");
print OUT <<EOF;
<html>
<head>
	<link rel="stylesheet" href="styles/mainstyles.css" type="text/css">
	<link rel="stylesheet" href="styles/bookstyles.css" type="text/css"> <!-- KC: added 12/16/2008 to address IE bug -->
</head>
<body id="suppbannerright">

<table align="right" border="0" cellspacing="0" cellpadding="0"><tr>
	<td valign="middle">
		<form style="margin:0px" name="chapResForm">

$content

		</form>	
	</td>
	
	<td valign="middle" style="padding-right:0; padding-left:7px" height="30"><div id="backvis" style="display:none"><a href="Javascript:top.opener.GoBack('supp')" title="Go back to the last-visited page"><img src="pics/btnBack.gif" width="25" height="25" border="0"></a></div><div id="backdim"><img src="pics/btnBackDim.gif" alt="" width="25" height="25" border="0" title="Go back to the last-visited page (currently dimmed because there is no last-visited page to go back to)"></div></td>

	<td valign="middle" style="padding-left:0"><div id="forwardvis" style="display:none"><a href="Javascript:top.opener.GoForward('supp')" title="Go forward to the page you just returned from"><img src="pics/btnForward.gif" width="25" height="25" border="0"></a></div><div id="forwarddim"><img src="pics/btnForwardDim.gif" alt="" width="25" height="25" border="0" title="Go forward to the page you just returned from (currently dimmed because there is no page to go forward to)"></div></td>

	<td valign="middle" style="padding-left:6px"><div id="keepopen"><nobr><a href="Javascript:top.KeepSuppWindowOpen()" title="Keep this item open">Keep Open</a></nobr></div></td>

	<td valign="middle" align="right" style="padding:0 5px 0 10px"><div id="helpDiv"><a href="Javascript:top.Help()" title="Get help with this item">Help</a></div></td>

</tr></table>

</body>
</html>

EOF
	print "Wrote suppbannerright.html\n";
	close(OUT);

	#================================
	# supptoc.php
	$content = get_content("supptoc_"); ### <- `cat ${output_tmp_dir}supptoc_*`;
	
	open(OUT, "> ${ebooks_root_dir}supptoc.php");
print OUT <<EOF;
<?PHP
# Get the bookId
require_once("../apis3/bookId.php");
?>
<html>
<head>
	<link rel="stylesheet" href="styles/suppstyles.css" type="text/css">
	<style type="text/css">
		.sn	{font-weight:normal}
		.cn {font-weight:bold; white-space:nowrap}
		.pn {font-weight:bold}
	
		a 		{font-weight:normal; color: #000000; text-decoration:none}
		a:hover	{text-decoration:underline}
	
		a.rl	{color: #660000; text-decoration:none}
		a:hover.rl {text-decoration:underline}
		
		a.sl	{color: #660000; text-decoration:nonex}
		a:hover.sl {text-decoration:underline}
		
		table {border-spacing:0; border-collapse:collapse; padding:0; margin-top:2px}
		td {vertical-align:top; border:0px; margin:0px; padding:1px 0px 1px 5px; text-align:left}
		.rt1 {padding:0 5px 0 0; font-size:11px; white-space:nowrap}
		.rt2 {padding:0; font-size:11px}
		.rd {padding:1px 0px 0px 20px}
		.partHeading {padding:5px 0px}
		.cd {display:none; padding-left:15px; padding-top:5px}
		
		.contentGroup {padding-bottom:5px; font-size:11px}
		.cgHead {padding-left:10px; font-weight:bold}

		.na {display:none}
	</style>
	<script language="JavaScript">
	// preload the arrow-bullets for the toc
	var bulrt = new Image(); bulrt.src = "pics/dropBigRight.gif";
	var buldn = new Image(); buldn.src = "pics/dropBigDown.gif";
	
	// Drop down the contents of a div
	function DD(div, newState) {
		var style = document.getElementById("div" + div).style;
		if (div.indexOf("_") != -1) {
			var styleT = document.getElementById("divT" + div).style;
		}
		
		// If no state specified, toggle
		if (newState == "toggle" || newState == null) {
			if (style.display == "block") {
				newState = "none";
			} else {
				newState = "block";
			}
		}
		
		// Set the display
		if (newState == "none") {
			style.display = "none";
			if (div.indexOf("_") != -1) {
				styleT.display = "block";
			}
			document["dd" + div].src = bulrt.src;
		} else {
			style.display = "block";
			if (div.indexOf("_") != -1) {
				styleT.display = "none";
			}
			document["dd" + div].src = buldn.src;
		}
	}
	
	function DropDownCurrentChapter() {
		var c = top.curSuppChapter;
		if (c == 0) {
			return;
		}

		DD("" + top.curSuppChapter);
	}
	
	// OpenSupp -- call top.opener's function
	function OS(a1, a2, a3, a4) {
		top.opener.OpenSupp(a1, a2, a3, a4);
	}
	
	// LoadSection -- call top's function
	function LS(s) {
		top.LoadSection(s);
	}
		

	var ca = top.opener.ca;
	var pa = top.opener.pa;

	</script>
</head>
<body onload="DropDownCurrentChapter()">
<div class="outerDiv">
<?PHP

$content

function PartString(\$i) {
	return "";
}

require_once("../servercom/databasefns.php");
require_once("../servercom/printtoc.php");

?>

</div>
</body>
</html>

EOF
	print "Wrote supptoc.php\n";
	close(OUT);
}

# Contents for the supptoc.php file
sub supptoc_Contents() {
	# Start the contents
	
	# instance variables
	my $tmpChapter = $chapter;
	my $tmpChapterTitle = $chapTitle;

	
	# type is Chapter, MODULE, Appendix or APPENDIX
	# ....1/8/2009: should use chapter_is_called?
	my $type;
		
	$type = "Chapter";
	
	# Start the contents
	
	my $contents;
	
$contents = <<EOF;
\$c[$chapter] = <<<EOF
<table style="margin:0px"><tr>
	<td><a class="cn" href="JavaScript:DD('$chapter')"><img name="dd$chapter" src="pics/dropBigRight.gif" alt="" width="10" height="10" border="0"></a></td>
	<td width="95%">$tmpChapterTitle</td>
</tr></table>
<div id="div$chapter" class="cd">
EOF
	
	
	# Setup a hash with subsupptocs
	my %subsupptoc = (
		"figure" => "",
		"table" => "",
		"tutorial" => "",
		"activity" => "",
		"animation" => "",
		"box" => "",
	);
		
	# Go through elements one by one, adding to the subsupptocs
	for my $element (@elements) {
		if ($element->{inSuppWindow}) {
			my ($jsArgs, $title1, $title2, $sid, $sname) = 
				($element->{jsArgs}, $element->{supptocTitle1}, $element->{supptocTitle2}, $element->{sectionIndex}, $element->{sectionTopTitle});
			
			# We only want section info for certain items
			my $secRef = "";
			if ($element->{showSection}) {
				$secRef = qq` (<a class="sl" href="JavaScript:LS($sid)">$sname</a>)`;
			}
			
			# sometimes we don't use open supp, just href
			
			my $res_url = "";
			
			if ($jsArgs =~ /'url','([^']*)'/) {
				$res_url = $1;

				$subsupptoc{$element->{suppGroup}} .= <<EOF;
<b>&raquo;</b> <a class="rl" href="$res_url">$title1</a>&nbsp; $title2$secRef<br>
EOF
			} else {
			
				$subsupptoc{$element->{suppGroup}} .= <<EOF;
<b>&raquo;</b> <a class="rl" href="JavaScript:OS($jsArgs)">$title1</a>&nbsp; $title2$secRef<br>
EOF

			}

		}
	}
	
	# Add the box, activity, animation, & tutorial submenus if there are any
	if ($subsupptoc{"box"}) {
		$contents .= <<EOF;
	<div class="contentGroup">
$subsupptoc{"box"}
	</div>

EOF
}

	if ($subsupptoc{"activity"}) {
		$contents .= <<EOF;
	<div class="contentGroup">
$subsupptoc{"activity"}
	</div>

EOF
}

	if ($subsupptoc{"animation"}) {
		$contents .= <<EOF;
	<div class="contentGroup">
$subsupptoc{"animation"}
	</div>
EOF
}

	if ($subsupptoc{"tutorial"}) {
		$contents .= <<EOF;
	<div class="contentGroup">
$subsupptoc{"tutorial"}
	</div>

EOF
}
	
	# Add everything else
	$contents .= <<EOF;
	<div class="contentGroup">
$subsupptoc{"other"}
	</div>

	<div class="contentGroup">
$subsupptoc{"table"}
$subsupptoc{"figure"}
	</div>

</div>
EOF;
EOF

	return $contents;
}

# For some reason MCP doesn't want to require this file unless we have a return value
1;
