/*
decor.js
Functions to add [DECOR]ations to document

REQUIRES: dom.js
*/

// ONLOAD...
//addLoadEvent(replaceTextLoader);
addLoadEvent(makeRounded);

// Initiates function to replace text headings with images
function replaceTextLoader() {
	if (!W3CDOM) return;
	var test = new Image();
	var tmp = new Date();
	var suffix = tmp.getTime();
	test.src = '/img/test.gif?'+suffix;
	test.onload = replaceTextInit;
}

// Which groups of elements to replace...
function replaceTextInit() {
	replaceText(document.getElementsByTagName('h1'));
	replaceText(document.getElementsByTagName('h2'));
}

// Look for elements with id attribute within group
// Future: maybe only for id=*_overlay
function replaceText(x) {
  var txtnode;
	var replace = document.createElement('img');
	for (var i=0; i<x.length; i++) {
		if (x[i].id) {
			// Quicker than creating element from scratch each time
			var y = replace.cloneNode(true);
			y.src = '/img/' + x[i].id + '.png';
			y.setAttribute('border','0');
			// Find first textNode, as we might have an anchor within this one!
			txtnode = findTextNode(x[i]);
		  y.alt = txtnode.nodeValue;
			txtnode.parentNode.replaceChild(y,txtnode);
		}
	}
}

// Searches dom for DIV elements with class 'rounded'
// Adds extra elements to make rounded corners
// <div class="rounded">
//   <div class="top"></div>
//   Other content...
//   <div class="bottom"><div class="right"></div></div>
// </div>
function makeRounded() {
	if (!W3CDOM) return;
	var adiv = document.createElement('div');
	var divs = document.getElementsByTagName('div');
	for (var i=0; i<divs.length; i++) {
		if (divs[i].className.indexOf('rounded') > -1) {
			// Insert 'top' div before firstChild of rounded div
			var newdiv = adiv.cloneNode(true);
			newdiv.className = 'top';
			divs[i].insertBefore(newdiv,divs[i].firstChild);
			
			// Bottom div
			newdiv = adiv.cloneNode(true);
			newdiv.className = 'bottom';
			
			// Right (bottom) div and append to bottom div
			var subdiv = adiv.cloneNode(true);
			subdiv.className = 'right';
			newdiv.appendChild(subdiv);
			
			// Append bottom div to main div
			divs[i].appendChild(newdiv);
		}
	}
}
