/*
 * smartLinks.js
 * Smart links library for Sundial
 *
 * Author: Zach van Schouwen
 * Date: 01-05-2007
 *
 * Standardize the various fancy links that occur across the site.
 * Things like openViewWindow() are made automatic here, to avoid redundant
 * inline JavaScript. See individual functions for documentation.
 */

/* Scans through the body for links with any of the classes that have special
 * behavior, and calls the function associated with that behavior. */
 function initializeLinks() {
 	var links = document.getElementsByTagName('a');
 	for (var i = 0; i < links.length; i++) {
 		if (hasClass(links[i], 'guidelines')) guidelinesLink(links[i]);
 		if (hasClass(links[i], 'viewWindow')) viewWindowLink(links[i]);
 		if (hasClass(links[i], 'sectionSwitch'))
 			sectionSwitchLink(links[i]);
 		if (hasClass(links[i], 'more')) condenserLink(links[i]);
 		if (hasClass(links[i], 'tableOrder')) orderingLink(links[i]);
 		if (hasClass(links[i], 'flexible')) flexibleLink(links[i]);
 	}
 }

/* JS-failure-friendly: Associate an action with all "Guidelines" links */
 function guidelinesLink(tag) {
 	addElementEvent(tag, 'click', function(ev) {
 		showGuidelines(tag.getAttribute('href'));
 		return false;
 	}, true);
 }

/* Associate an action and a title with all viewWindow links. */
 function viewWindowLink(tag) {
 	addElementEvent(tag, 'click', function(ev) {
 		if (oldClick) oldClick(ev);
		openViewWindow(tag.getAttribute('href'),
			       tag.getAttribute('alt'));
		return false;
 	}, true);
 }

function sectionSwitchLink(tag) {
	var switchSection = function(ev) {
		var elder = tag.parentNode;
		toggleClass(elder, 'closed', 'open');
		return false;
	};
	addElementEvent(tag, 'click', switchSection, true);
}

function condenserLink(tag) {
	var toggleCondensed = function(ev) {
		var elder = tag.parentNode;
		toggleClass(elder, 'condensed', 'expanded');
		if (containsClass(elder, 'condensed'))
			tag.innerHTML = '&gt;&gt; Tell me more...';
		else
			tag.innerHTML = '&lt;&lt; Tell me less...';
			
		return false;
	};
	addElementEvent(tag, 'click', toggleCondensed, true);
}

function flexibleLink(tag) {
	var targetID = tag.getAttribute('shows');
	if (!targetID) {
		alert('Must specify "shows" attribute!');
		return;
	}
	var target = document.getElementById(targetID);
	if (!target) {
		alert('Bad target for flexible link! (' +
		      tag.getAttribute('shows') + ')');
		return;
	}
	target.style.display = 'none';
	var showTarget = function(ev) {
		target.style.display = 'block';
		tag.style.display = 'none';
		if (hasClass(tag.parentNode, 'helpful') ||
		    hasClass(tag.parentNode, 'dependent'))
			tag.parentNode.style.display = 'none';
		return false;
	};
	addElementEvent(tag, 'click', showTarget, true);
}

addOnload(initializeLinks);