// ==UserScript==
// @name w3c.org - Accessible specs
// @author Mark Schenk 
// @namespace http://www.markschenk.com/ 
// @version 1.0.1
// @description  Makes the anchors in the headers of W3C spec pages
//			clickable, to make it easier to link to
//			sections.
// @ujs:category site: enhancements
// @ujs:published 2005-05-28 08:57
// @ujs:modified 2005-09-19 09:19
// @ujs:documentation http://userjs.org/scripts/site/enhancements/w3c-spec-links 
// @ujs:download http://userjs.org/scripts/download/site/enhancements/accessiblespecs.js 
// @ujs:download.gm http://userjs.org/scripts/download/site/enhancements/accessiblespecs.user.js
// ==/UserScript==

/* 
 * Copyright © 2005 by Mark Schenk
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA
 */


if( location.hostname.match(/\bw3\.org/) && location.pathname.match(/^\/TR\//) ) {

window.addEventListener('load',function(e){

	for (var n = 0; n < 8; n++ ) {
		//for all headers and DTs
		var elements = document.getElementsByTagName((n==7)?'dt':('h'+n));

		for (var i = 0, tmp; tmp = elements[i]; i++) {
			
			var tmp2 = tmp.getElementsByTagName('a')[0];
			if (tmp2 && tmp2.hasAttribute('name') && !tmp2.getAttribute('a') && !tmp2.getAttribute('href')) {

				//if they contain an unlinked anchor, make it into a link pointing to itself
        tmp2.setAttribute('href','#' + tmp2.getAttribute('name'))

			} else if (!tmp2 && tmp.id && !tmp.getAttribute('href')) {

				//if they do not contain an anchor, but they do have an id, make a link pointing to the id
				tmp2 = document.createElement('a');
        if (!tmp.getAttribute('href')) {
          tmp2.setAttribute('href','#' + tmp.getAttribute('id'))
        }
				tmp.insertBefore(tmp2,tmp.firstChild);

				//put the existing contents inside the link
				for (var j; j = tmp.childNodes[1];) {
					try {
						tmp2.appendChild(j);
					} catch(e) { break; } // in case it is not allowed inside a link
				}

			}
		}

	}

},false)

}
