// Create a page that lists a talble of flowers by color and number of petals.  When user clicks on
// an entry in the table, a "page" of flowers that match the entry appears below the table.  If printing
// this page appears in a separate window.

/* We expect a file in the form:
	  titleEntry(page, common, latin, family, "blue", "green", 4, 5)
	  picEntry(fileName, "comment")
	  picKeyEntry(fileWithFlower, "comment")
	  keyEntry(fileWithFlower, "comment")
   where only one of picKeyEntry or keyEntry should appear per titleEntry.
*/

var page = new Array(); // index is color, value is array indexed by num petals 1-7
						// value in array is array of flowers
var lastPage;

var indexWIndow; // Window for index page target

var pics; // array of 1st arguments to pic() calls for this flower (file names)

var missing = new Array(); // common names of titles that are missing #petals or color

var maxPetals = 8;

// "colorPage" is the id of the div that holds the body of the "page" containing images and
// names of all the flowers matching an the clicked entry in the table
var colorPageText; // string buffer to hold colorPage
				 
// A Flower object has multiple fields:
//	  parsedName comes from parseName (the beautified HTML representation of the common name from the picKeyEntry)
//	  picture is the file name of the thumbnail picture
//    titleName comes from getTitleName (the raw text of the common name in the picKeyEntry with metacharacters removed)
function Flower(page, common, parsedName, label, titleName) {
	this.page = page;
	this.common = common;
	this.parsedName = parsedName;
	this.label = label;
	this.picture = null;
	this.titleName = titleName;
}

var flower; // the most recent Flower processed by entry()
var indexWindow;

var allColors = new Array("Green","White-Cream","Yellow","Orange","Pink","Red","Purple-Maroon",
	"Violet-Lavender","Blue","Brown","Multicolor");
var lcColors = new Array(allColors.length); // the first color in each entry in above list in lowercase
var textColors = new Array("black","black","black","black","black","white","white","white","white","white","white");

function start() {
	var i;
	for (i = 0; i < allColors.length; i++) {
		var color = allColors[i];
		var h = color.indexOf('-'); //	get only the part before the 1st "-"
		if (h > 0) color = color.substr(0,h);
		color = color.toLowerCase();
		lcColors[i] = color;
		lcColors[color] = lcColors[i]; // also make array associative by setting color property nonzero
	}
}

start();
	
// For title():
// Make an entry in page array for flower in file using the specified common and latin name 
// params[i] is the following in any order:
//	begins with uppercase letter: an alternate label (0 or 1 of these)
//	begins with lowercase letter: a color (1 or more of these)
//	begins with number: number of petals, 1-8 (1 or more of these)
function titleEntry(pg, common, latin, family, params) {
	if (flower != null && flower.picture == null) {
		// make a picKey call on one of the flowers if there wasn't one
		if (pics.length == 1) thisPic = pics[0]; // there was only one
		else {
			// Multiple choices; find the best one based on the file name
			thisPic = findFlower(pics, "flower", "flowers");
			if (thisPic == null) thisPic = findFlower(pics, "flower");
			if (thisPic == null) thisPic = findFlower(pics, "close", "very");
			if (thisPic == null) thisPic = findFlower(pics, "close");
			if (thisPic == null) thisPic = findFlower(pics, "top");
			if (thisPic == null) thisPic = findFlower(pics, "head");
			if (thisPic == null) thisPic = pics[0];
		}
		picKeyEntry(lastPage, thisPic);
	}
	lastPage = pg;
	lastPicKey = null;
	pics = new Array();
	parsedName = parseName(common, true);
	titleName = getTitleName(common);
	colors = new Array();
	petals = new Array();
	var altLabel = null;
	for (i = 4; i < arguments.length; i++) {
		arg = arguments[i];
		if (!isNaN(arg)) {
			if (arg < 1 || arg > 8) {
				alert('Bad number of petals "' + arg + '" in "' + common + '"');
				continue;
			}
			petals[petals.length] = arg;
		} else {
			c = arg.substr(0,1);
			if (c >= 'A' && c <= 'Z') {
				if (altLabel != null) 
					alert('Extra label "' + arg + '" for "' + common + '" ignored');
				else altLabel = arg;
				continue;
			}
			if (c >= 'a' && c <= 'z') {
				colors[colors.length] = arg;
			} else {
				alert('Unknown parameter "' + arg + '" in "' + common + '"');
			}
		}
	}
	// need at least one color and one num petals
	if (petals.length == 0 || colors.length == 0) {
		missing[missing.length] = common;
		flower = null;
		return;
	}
	flower = new Flower(pg, common, parsedName, getLabel(introLabel, altLabel), titleName);
	// add flower to every entry for each color and num petals
	for (c = 0; c < colors.length; c++) {
		for (p = 0; p < petals.length; p++) {
			thisColor = colors[c];
			if (lcColors[thisColor] == null) {
				alert('Undefined color "' + thisColor + '" in "' + common + '"');
			}
			petalsArray = page[thisColor];
			if (petalsArray == null) {
				petalsArray = new Array(9);
				page[thisColor] = petalsArray;
			}
			flowersArray = petalsArray[petals[p]];
			if (flowersArray == null) {
				flowersArray = new Array();
				petalsArray[petals[p]] = flowersArray;
			}
			flowersArray[flowersArray.length] = flower;
		}
	}
}

// For picKey(): For the most recent flower, make this the picture
function picKeyEntry(page,file) {
	if (flower == null) return; // ignore if title() call was no good
	if (flower.picture != null) {
		alert('Duplicate key picture "' + file + '" for "' + flower.parsedName + '"');
		return;
	}
	flower.picture = file;
	pics = null; // no longer need to save pics for this flower
}

// For key(): Same as picKeyEntry. 
function keyEntry(page, file) {
	picKeyEntry(page,file);
}

// For picKey()
function KeyEntry(page, file) {
	picKeyEntry(page, file);
}

// For pic(): Just save the picture in case we need it
function picEntry(page, file) {
	if (flower == null || flower.picture == null)
		pics[pics.length] = file;
}

// Output a "page" containing a multi-column table for all flowers of the specified color and #petals
// The page actually is the innerHTML for the colorPage div at the bottom of the index page,
// except when printing where it's actually in a separate window.
function writePage(colorIndex, numPetals) {
	doc = null;//indexWindow.document;
	ucColor = allColors[colorIndex];
	if (!printing) {
		colorPageText = '<H2>' + ucColor + ' Flowers with ' + getNameForPetals(numPetals) + ' Petals</H2>';
	} else {
		doc.write('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"' + 
			'"http://www.w3.org/TR/html4/loose.dtd"><html><head><title>' +
			ucColor + ' Flowers with ' + getNameForPetals(numPetals) + ' Petals</title><STYLE>' + 
			'img { width:100 height:100 } ' +
			'<\/STYLE>');
				// For unknown reasons IE6 on some PCs goes into an infinite loop when importing the following
			// from a script file ather than inserted inline like this
		doc.write(
			'<script type="text/javascript">'+
			'var imageWindow; \
			function openImageFile(name, flowerName) {\
				url = "../others/flower.html?" + name + "?" + escape(flowerName);\
				if (imageWindow == null || imageWindow.closed) {\
					imageWindow = window.open(url, "Flower", "resizable,height=750,width=750");\
				} else imageWindow.location = url;\
				imageWindow.focus();\
			}' +
			'<\/script>'+
			//'<script type="text/javascript" src="' + dotdot +
			//'scripts/wildflower_catalog_aux.js"><\/script>' +
			'<\/head>');
	}
    pageBody(colorIndex,numPetals);
	//copyright(doc);
	if (printing) {
		pWrite('</html>');
		doc.close();
	} else {
		// if interactive, set the colorPage div to the text
		colorPage.innerHTML = colorPageText;
	}
}

// Append text to string colorPageText or (if printing) to document
function pWrite(text) {
    if (printing) {
    	doc.write(text);
    } else {
		if (colorPageText == null) colorPageText = text;
		else colorPageText = colorPageText + text;
	}
}


// Write main body of page as a header plus a table
function pageBody(colorIndex, numPetals) {
	flowers = page[lcColors[colorIndex]][numPetals];
	if (flowers == null) return; 
	ucColor = allColors[colorIndex];
	if (printing) {
	    doc.write('<BODY BODY BGCOLOR="#dfe7c6" onload="setupZoom()" onclick="closeZoomIfOpen()" >');
	    doc.write('<h2>' + ucColor + ' Flowers with ' + getNameForPetals(numPetals) + ' Petals</h2>');
	}
	if (!printing) pWrite('<P>Click on picture to see enlargement.	Click on name to go to description.</P>');
	pWrite('<TABLE>');
	var numCols = printing ? 4 : 6;
	var numRows = Math.floor((flowers.length + numCols - 1)/numCols);
	var i, j;
	//alert("Writing to window 2, stop="+stop);
	for (i = 0; i < numRows; i++) {
		pWrite('\n<TR valign="bottom">');
		for (j = 0; j < numCols; j++) {
			index = i*numCols + j;
			if (index < flowers.length) 
				flowerEntry(doc,flowers[index]);  // do flower in col
			else flowerEntry(doc);
		}
		pWrite('</TR>');
	}
	//alert("Done Writing to window");
	pWrite('</TABLE><P align="center">');
}

// Output a table cell which is a table with 2 rows, top containing the thumbnail and bottom containing the name.
// Clicking on the picture zooms it and the title.  Clicking on the title (in the thumbnail or the zoomed image)
// jumps to the catalog page for the flower.
function flowerEntry(doc,flower) {
	if (flower == null) {
		pWrite('<TD><\/TD>');
		return;
	}
	catLink = '../catalog/' + flower.page + '#' + flower.label;
	// This is the <a> for the image, where clicking causes a zoom 
	// The image has a title which is the text of the name and is a link to the catalog page.
	imageRef = '<a href="' + openImageInWindowLink(flower.picture, flower.titleName) + '" ' + 
					'onclick="return zoomClick(this,event);"' + 
					'title="' + "<a href='" + catLink + "' style='color: white'>" + flower.titleName + '<\/a>" ' +
				   'onmouseover="zoomPreload(this); return true;">';
	pWrite('<TD><TABLE><TR>');
	if (flower.picture == null) {
		alert('Key picture missing for "' + flower.common + '"');
		pWrite('</TR>');
	} else {
		thumbName = dotdot + 'Small_JPEGs/' + flower.picture + '.jpg';
		if (printing && flower.picture.lastIndexOf("Key") != flower.picture.length-3) {
			// When printing, use the full size image unless there isn't one
			thumbName = imagePath(flower.picture);
		}
		pWrite('<TD>' + imageRef + '<img name=' + flower.picture + ' src="' + 
			thumbName + '" alt="' + flower.picture + '"');
		if (printing) pWrite('" width=250');
		else pWrite('" width=160');
		pWrite('  style="border: none;"></a></TD></TR>');
	}
	pWrite('<TR><TD ');
	if (printing) pwrite('>');
	else pWrite('width=160><a href="' + catLink + '" target="catpage">');
	pWrite(flower.parsedName);   // the beautified HTML name
	if (!printing) pWrite('</a>');
	pWrite('</TD></TR></TABLE></TD>');
}

// Output in a new window a page containing the identifier for the color and numPetals
// This function is expected to be in a pseudo-URL for a link:
//	   <a href="javascript:doWindow('blue',5)">X</a>
function doWindow(colorIndex, numPetals) {
	if (indexWIndow == null || indexWindow.closed) {
		writePage(colorIndex, numPetals);
		if (printing) {
		    indexWindow = window.open("", "index", "location,menubar,toolbar,titlebar,scrollbars,resizable");
		    setTimeout("writePage('" + colorIndex + "', " + numPetals + ")", 100);
		}
	} else {
		//alert("Not writing page");
		//indexWindow.focus();
	}
}

// Make a row of the table containing pseudo-URL references to the links for each page
function makeRow(colorIndex) {
	color = allColors[colorIndex];
	lcColor = lcColors[colorIndex];
	document.write('<TR><TH background="../GIFs/' + lcColor + '.gif"><font color="' +
					 textColors[colorIndex] + '" face="sans-serif"><b>' + color + '</b></font></TH>');
	for (i = 1; i <= maxPetals; i++) {
		colorArray = page[lcColor];
		if (colorArray == null) {
			document.write('<TD>&nbsp;</TD>'); // no flowers with this color
		} else {
			flowers = colorArray[i];
			if (flowers == null) {
				document.write('<TD style="background: #cbfcc5">&nbsp;</TD>');	// no flowers with his color and #petals
			} else {
				document.write('<TD  style="background: #cbfcc5" ALIGN="left"><A HREF="javascript:doWindow(' +
						   colorIndex + ',' + i + ')">' + 
						   getNameForPetals(i) + '</A> (' + flowers.length + ')</TD>');
			}
		}
	}
	document.write('</TR>');
}

// Write a single huge page with the entire identifier (used if printing)
function doAll() {
	doc = document;
	var i, j;
	for (i = 0; i < allColors.length; i++) {
		for (j = 1; j <= maxPetals; j++) {
			pageBody(i,j);
		}
	}
}

// Return the name for the code representing number of petals
function getNameForPetals(i) {
	if (i == 1) return "Irregular";
	if (i == 7) return "7 or more";
	if (i == 8) return "Indistinguishable";
	return i; 
}

/** Return the element of pics that contains has but not hasnt */
function findFlower(pics, has, hasnt) {
	for (i = 0; i < pics.length; i++) {
		str = pics[i].toLowerCase();
		if (str.indexOf(has) >= 0 && (hasnt == null || str.indexOf(hasnt) < 0)) return pics[i];
	}
	return null;
}
