//******************************************************************************
// Navigation

// Popup contents. An array of (section) arrays of (page title) strings.
var sectionPages = [
	[], // (0. Home)
	[ // 1. Your Host
		"My Background",
		"What I'm Interested In"
	],
	[ // 2. Leather
		"Code of Leathermen",
		"Dispelling the Myths about Leather",
		"&quot;Old Guard&quot; Leather",
		"Leather Pride Flag",
		"Appropriate Attire",
		"Leathercare",
		"Whip Care",
		"Bondage Introduction",
		"An Intro Course in Bondage",
		"Bondage Safety I.Q. Test",
		"Ropes and Knots"
	],
	[ // 3. BDSM
		"BDSM: An Introduction",
		"The Master",
		"The slave",
		"boy/slave Commitment",
		"Master's and slave's Rights",
		"Pain For Pleasure",
		"Serious Scenes and Play",
		"First Contact",
		"The Law vs BDSM"
	],
	[ // 4. Scenes
		"Definitions",
		"Cock and Ball Torture",
		"Electroplay",
		"An Introduction to Flogging",
		"Mummification",
		"Spanking and Whipping",
		"Tit Play / Torture",
		"Watersports",
		"Scene Gallery"
	],
	[ // 5. Fetishes
		"Hanky Code",
		"Boots",
		"Rubber and PVC",
		"Just for Leather"
	],
	[ // 6. Resources
		"Suggested Reading",
		"Gear",
		"Places",
		"Documents",
		"Link to this site"
	]
];

// Adds one page to a popup page list.
var currentPage = window.location.pathname.split ("/").pop ();
function addPage (list, title, href)
{
	var page = document.createElement ("li");
	var link = document.createElement ("a");
	if (href == currentPage)
		page.className = "current";
	else
		link.href = href;
	link.innerHTML = title;
	page.appendChild (link);
	list.appendChild (page);
}

// Updates the visibility of a popup page list.
function checkSectionPages (pages, overSection, overPages)
{
	if (overSection !== null) pages.overSection = overSection;
	if (overPages !== null) pages.overPages = overPages;
	pages.style.visibility =
		(pages.overSection || pages.overPages) ? "visible" : "hidden";
}

// Adds a popup list of pages to each section tab.
var navigationPrepared = false;
function prepareNavigation ()
{
	var sectionsEl = document.getElementById ("sections")
	if (navigationPrepared || !sectionsEl) return;
	var sections = sectionsEl.getElementsByTagName ("li");
	for (var i = 0; i < sections.length; ++i) {
		var section = sections[i];
		if (section.id.match (/^section.$/)) {
			var sectnum = parseInt (section.id.charAt (section.id.length - 1));
			var pages = document.createElement ("ul");
			pages.className = "pages";
			pages.overSection = false; // Whether hovering over section tab
			pages.overPages = false; // Whether hovering over page list
			addPage (pages, "<em>Section Index</em>",
				"section" + sectnum + ".html");
			for (var j = 0; j < sectionPages[sectnum].length; ++j) {
				addPage (pages, sectionPages[sectnum][j], "page" + sectnum +
					(j < 9 ? "0" : "") + (j + 1) + ".html");
			}
			pages.onmouseover = function (e)
				{ checkSectionPages (this, null, true); };
			pages.onmouseout = function (e)
				{ checkSectionPages (this, null, false); };
			section.pages = pages;
			section.appendChild (pages);
			section.onmouseover = function (e)
				{ checkSectionPages (this.pages, true, null); }
			section.onmouseout = function (e)
				{ checkSectionPages (this.pages, false, null); };
			var arrow = document.createElement ("img");
			arrow.src = "images/arrow-down.gif";
			var sectionLink = section.getElementsByTagName ("a")[0];
			sectionLink.appendChild (arrow);
		}
	}
	navigationPrepared = true;
}

//******************************************************************************
// Section indices

var sectionImage;
var sectionImageSrc = "";
var sectionImageText = "";

// Replaces the generic image with an image for the hovered section or page.
function showPageImage (e)
{
	if (sectionImage) {
		sectionImage.src = this.image.src;
		sectionImage.setAttribute ("alt", this.textContent);
	}
}

// Restores the generic image, as originally specified in HTML.
function restoreSectionImage ()
{
	if (sectionImage) {
		sectionImage.src = sectionImageSrc;
		sectionImage.setAttribute ("alt", sectionImageText);
	}
}

// Causes links to pages/sections to display their identifying images on hover.
var sectionIndexPrepared = false;
function prepareSectionIndex ()
{
	var sectionIndex = document.getElementById ("section-index");
	sectionImage = document.getElementById ("section-image");
	if (sectionIndexPrepared || !sectionIndex || !sectionImage) return;
	sectionImageSrc = sectionImage.src;
	sectionImageText = sectionImage.getAttribute ("alt");
	var pages = sectionIndex.getElementsByTagName ("dt");
	for (var i = 0; i < pages.length; ++i) {
		var link = pages[i].firstChild;
		if (link.href) {
			var href = link.href.split ("/").pop ();
			switch (href) {
			case "page210.html":
			case "page603.html":
				var imageType = "gif"; // These have GIF identifying images.
				break;
			default:
				var imageType = "jpg"; // Other identifying images are JPEG.
			}
			link.image = new Image ();
			link.image.src = "images/" + href.replace ("html", imageType);
			link.onmouseover = showPageImage;
			link.onmouseout = restoreSectionImage;
		}
	}
	sectionIndexPrepared = true;
}

//******************************************************************************
// Image galleries

// Displays a gallery image in full size.
function showGalleryImage (e)
{
	this.galleryImage.src = this.href;
	return false;
}

// Causes each gallery thumbnail to display the full-size image on the page.
var galleriesPrepared = false;
function prepareGalleries ()
{
	if (galleriesPrepared) return;
	var candidates = document.getElementsByTagName ("div");
	for (var i = 0; i < candidates.length; ++i) {
		if (isOfClass (candidates[i], "gallery")) {
			var galleryImage = candidates[i].getElementsByTagName ("img")[0];
			var links = candidates[i].getElementsByTagName ("a");
			for (var j = 0; j < links.length; ++j) {
				links[j].galleryImage = galleryImage;
				links[j].onclick = showGalleryImage;
			}
		}
	}
	galleriesPrepared = true;
}

//******************************************************************************
// Slideshows

/* Defines and pre-loads a series of sequentially displayed images, where
 *   container is the name of slideshow container element;
 *   format is the format of image filenames, where "%" is the image number;
 *   count is the number of images in the slideshow, numbered 1 to (count);
 *   duration is the time in milliseconds for which each image is displayed;
 *   loop is whether the slideshow loops upon completion; and
 *   captions is an optional array of strings to display with each image.
 * This function must be called before the page has finished loading.
 */
var slideshows = new Array ();
function defineSlideshow (container, format, count, duration, loop, captions)
{
	var slideshow = new Object ();
	slideshow.containerName = container;
	slideshow.imageCount = count;
	slideshow.imageDuration = duration;
	slideshow.loop = loop;
	slideshow.captions = captions;
	slideshows.push (slideshow);

	slideshow.images = new Array ();
	for (var i = 1; i <= count; ++i) {
		slideshow.images[i] = new Image ();
		slideshow.images[i].src =
			format.replace ("%", (i < 10 ? "0" : "") + i); //FIXME more generic
	}
}

// Displays the next image in a slideshow.
function stepSlideshow (i)
{
	var slideshow = slideshows[i];
	if (slideshow.interval == null) {
		slideshow.nextImage = 1;
		slideshow.interval =
			setInterval ("stepSlideshow (" + i + ")", slideshow.imageDuration);
	}

	slideshow.image.src = slideshow.images[slideshow.nextImage].src;
	if (slideshow.caption && slideshow.captions) {
		slideshow.caption.innerHTML =
			slideshow.captions[slideshow.nextImage - 1];
		slideshow.caption.style.width =
			slideshow.images[slideshow.nextImage].width + "px";
	}

	if (++slideshow.nextImage > slideshow.imageCount) {
		if (slideshow.loop)
			slideshow.nextImage = 1;
		else {
			clearInterval (slideshow.interval);
			slideshow.interval = null;
		}
	}
}

// Begins each defined slideshow.
var slideshowsPrepared = false;
function prepareSlideshows ()
{
	if (slideshowsPrepared) return;
	for (var i = 0; i < slideshows.length; ++i) {
		var slideshow = slideshows[i];
		var container = document.getElementById (slideshow.containerName);
		if (!container) continue;
		slideshow.image = container.getElementsByTagName ("img")[0];
		if (!slideshow.image) continue;
		if (slideshow.captions) {
			slideshow.caption = container.getElementsByTagName ("p")[0];
			if (!slideshow.caption) {
				slideshow.caption = document.createElement ("p");
				slideshow.caption.className = "caption";
				container.appendChild (slideshow.caption);
			}
		} else 
			slideshow.caption = null;
		slideshow.interval = null;
		stepSlideshow (i);
	}
	slideshowsPrepared = true;
}

//******************************************************************************
// Amazon.com glue

/* Replaces abbreviated Amazon links of the form href="asin:0123456789" with
 * proper links to product pages. For image links, references the product
 * thumbnail image. If enabled, loads the Amazon link enhancer to provide
 * popup product details.
 *
 * This function must be called specifically at the end of a page body.
 */
var enhanceAmazon = true;
var amazonPrepared = false;
function prepareAmazon ()
{
	if (amazonPrepared || !needsMet) return;
	var links = document.getElementsByTagName ("a");
	for (var i = 0; i < links.length; ++i) {
		if (links[i].href.match (/^asin:/)) {
			var ASIN = links[i].href.substr (5);
			links[i].href = 'http://www.amazon.com/gp/product/' + ASIN +
				'?ie=UTF8&tag=seattleleatherco&linkCode=as2&camp=1789' +
				'&creative=9325&creativeASIN=' + ASIN;
			links[i].target = "_blank";
			var images = links[i].getElementsByTagName ("img");
			if (images.length == 1) // Only for single thumbnail links
				images[0].src = "amazon/" + ASIN + ".jpg";
		}
	}
	if (enhanceAmazon) includeScript
		('http://www.assoc-amazon.com/s/link-enhancer?tag=seattleleatherco');
	amazonPrepared = true;
}

//******************************************************************************
// Miscellaneous

// Includes an external JavaScript file. Must not be called after page load.
function includeScript (src)
{
	document.write ('<scr' + 'ipt type="text/javascript" src="' + src + 
		'"></scr' + 'ipt>');
}

// Tests whether a page element is of a given class.
function isOfClass (element, className)
{
	if (!element.className) return false;
	var classes = element.className.split (" ");
	for (var i = 0; i < classes.length; ++i) {
		if (classes[i] == className) return true;
	}
	return false;
}

// Plays a sound file, optionally repeating indefinitely.
function playSound (src, loop)
{
	var sound = document.createElement ("embed"); //FIXME Replace with object.
	sound.setAttribute ("src", src);
	sound.setAttribute ("autostart", "true");
	sound.setAttribute ("loop", loop ? "true" : "false");
	sound.setAttribute ("hidden", "true");
	document.body.appendChild (sound);
}

// Returns the current date as a formatted string.
function formatDate ()
{
	var now = new Date ();
	if (now.toLocaleFormat)
		return now.toLocaleFormat ("%A %d %B %Y");

	var months = [ "January", "February", "March", "April", "May", "June",
		"July", "August", "September", "October", "November", "December" ];
	var days = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
		"Friday", "Saturday" ];

	return (days[now.getDay ()] + " " + now.getDate () + " " +
		months[now.getMonth ()] + " " + now.getFullYear ());
}

//******************************************************************************
// Globals

// Redefine this to perform page-specific onload functions.
function pageTasks ()
{}

// Escape from framesets, if any.
if (window != window.top)
	window.top.location = window.location;

// Functions in this file expect W3C DOM support.
var needsMet = (document.getElementById && document.createElement);

window.onload = function ()
{
	if (!needsMet) return;
	prepareNavigation ();
	prepareSectionIndex ();
	prepareGalleries ();
	prepareSlideshows ();
	pageTasks ();
};
