
//Constants
var forceUpperCase = false;
var flashPath = "/script/";


//Tags to replace with heading_replace.swf, and font sizes to be used in the flash movie.
var headings = new Array( 
						  ["h1",'<font size="40">','</font>'],
						  ["#publication h3",'<font size="18" face="sans">','</font>'],
						  ["#splash h1", '<p align="center"><font size="40" face="smallcaps"><a href="welcome.htm">','</a></font></p>'],
						  ["#content h2",'<font size="20" face="smallcaps">','</font>'],
						  ["#splash h2",'<p align="center"><font size="16" face="sans"><a href="welcome.htm">','</a></font></p>'],
						  ["#content_header h2",'<font size="24" face="smallcaps">','</font>'],
						  ["#pub_title h2",'<font size="24" face="smallcaps">','</font>'],						 
						  ["h3",'<font size="25">','</font>'],
						  ["h4",'<font size="14" face="sans">','</font>'],
						  [".sb_panel h5",'<font size="10" face="sans">','</font>'],
						  ["#content_header h4",'<font size="12" face="sans">','</font>'],
						  ["#content_header h5",'<font size="10" face="oblique" color="#333333">','</font>'],
						  ["#pub_title h5",'<font size="12" face="oblique" color="#333333">','</font>'],						  
						  ["h6",'<font size="14">','</font>']
						  );

//Hide these elements until the flash is loaded.
document.write('<style type="text/css">');
for(var g=0; g<headings.length; g++)
	document.write(headings[g][0] + " {visibility: hidden;}");
document.write('</style>');


//Code to embed the flash file
var flash = '<div style="height: @height;" id="fdlFlashDiv_@id@" class="hide_print">';
flash += '<object id="fdlFlashObj_@id@" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="100%" height="100%">';
flash += '<param name="movie" value="@movie" />';
flash += '<param name="quality" value="high" />';
flash += '<param name="wmode" value="transparent">';
flash += '<param name=flashvars value="@flashvars" />';
flash += '<embed src="@movie" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="100%" height="100%" wmode="transparent" flashvars="@flashvars"></embed>';
flash += '</object>';
flash += '</div>';

var fdlFlashIdCounter = 0;
										  

//Flash detection script
var MM_contentVersion = 8;
var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;
if ( plugin ) {
		var words = navigator.plugins["Shockwave Flash"].description.split(" ");
	    for (var i = 0; i < words.length; ++i)
	    {
		if (isNaN(parseInt(words[i])))
		continue;
		var MM_PluginVersion = words[i]; 
	    }
	var MM_FlashCanPlay = MM_PluginVersion >= MM_contentVersion;
}
else if (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0 
   && (navigator.appVersion.indexOf("Win") != -1)) {
	document.write('<SCR' + 'IPT LANGUAGE=VBScript\> \n'); //FS hide this from IE4.5 Mac by splitting the tag
	document.write('on error resume next \n');
	document.write('MM_FlashCanPlay = ( IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & MM_contentVersion)))\n');
	document.write('</SCR' + 'IPT\> \n');
}


function doReplace(){

	var els;
	var el;
	var hTagName;
	var fontTag;
	var fontEndTag;
	var embedCode;
	
	var height;
	var c;
	var _origText;
	var _replaceText;
	for(var j=0; j<headings.length; j++){
		hTagName = headings[j][0];
		fontTag = headings[j][1];
		fontEndTag = headings[j][2];
		//els = document.getElementById("main").getElementsByTagName(hTagName);
		els = getElementsBySelector(hTagName);
		if(MM_FlashCanPlay){
			for(var i=0; i<els.length; i++){
				el = els[i];
				if(el.innerHTML.toLowerCase().indexOf('<object')==-1){
					height = el.offsetHeight;
					
					//Pull the text out of the node
					_origText = getInnerText(el);
					_replaceText = fontTag + _origText + fontEndTag;
					//Write some new HTML
					
					embedCode = flash.replace(/@flashvars/g, "replacecontent=" + escape(_replaceText) + "&fdlFlashID=" + fdlFlashIdCounter);
					embedCode = embedCode.replace(/@height/g, height + "px");
					embedCode = embedCode.replace(/@movie/g, flashPath + "heading_replace.swf");
					embedCode = embedCode.replace(/@id@/g, fdlFlashIdCounter);
					
					el.innerHTML = embedCode + "<span class='hide'>" + _origText + "</span>";
					el.style.visibility = "visible";
					
					fdlFlashIdCounter ++;
				}
				}
		}else{
			for(var i=0; i<els.length; i++){
				el = els[i];
				el.style.visibility = "visible";
			}
		}
			
	}

}

function getInnerText(e){

	 var strText = "";
	 var node;
	 for(var i=0; i<e.childNodes.length; i++ )
	 {node = e.childNodes[i];
	  switch(node.nodeType)
	  {
	   case 1: // elements
		strText += getInnerText(node);
		break;
	   case 3: // text
		strText += node.nodeValue;
		break;
	   default: // comments etc
		break;
	  }
	 }
	
	//Strip leading and trailing spaces.
    //var regEx = /^[ \t\r\n]+|[ \t\r\n]+$/g;
	var regEx = /[\r\n\t]+|[ ]{2}/g;
	strText = strText.replace(regEx, " ");
	
	var regEx = /[ ]+/g;
	strText = strText.replace(regEx, " ");
	
	//Force upper case if neccessary
	if(forceUpperCase)strText = strText.toUpperCase();
	return strText;
}

/*
	Finds elements on page that match a given CSS selector rule. Some
	complicated rules are not compatible.
	Based on Simon Willison's excellent "getElementsBySelector" function.
	Original code (with comments and description):
	http://simon.incutio.com/archive/2003/03/25/getElementsBySelector
*/
function getElementsBySelector(selector)
{
	var tokens = selector.split(' ');
	var currentContext = new Array(document);
	for(var i=0;i<tokens.length;i++)
	{
		token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');
		if(token.indexOf('#') > -1)
		{
			var bits = token.split('#');
			var tagName = bits[0];
			var id = bits[1];
			var element = document.getElementById(id);
			if(tagName && element.nodeName.toLowerCase() != tagName)
				return new Array();
			currentContext = new Array(element);
			continue;
		}

		if(token.indexOf('.') > -1)
		{
			var bits = token.split('.');
			var tagName = bits[0];
			var className = bits[1];
			if(!tagName)
				tagName = '*';

			var found = new Array;
			var foundCount = 0;
			for(var h=0;h<currentContext.length;h++)
			{
				var elements;
				if(tagName == '*')
					elements = currentContext[h].all ? currentContext[h].all : currentContext[h].getElementsByTagName('*');
				else
					elements = currentContext[h].getElementsByTagName(tagName);

				for(var j=0;j<elements.length;j++)
					found[foundCount++] = elements[j];
			}

			currentContext = new Array;
			var currentContextIndex = 0;
			for(var k=0;k<found.length;k++)
			{
				if(found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b')))
					currentContext[currentContextIndex++] = found[k];
			}

			continue;
	    }

		if(token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/))
		{
			var tagName = RegExp.$1;
			var attrName = RegExp.$2;
			var attrOperator = RegExp.$3;
			var attrValue = RegExp.$4;
			if(!tagName)
				tagName = '*';

			var found = new Array;
			var foundCount = 0;
			for(var h=0;h<currentContext.length;h++)
			{
				var elements;
	        	if(tagName == '*')
					elements = currentContext[h].all ? currentContext[h].all : currentContext[h].getElementsByTagName('*');
				else
					elements = currentContext[h].getElementsByTagName(tagName);

				for(var j=0;j<elements.length;j++)
					found[foundCount++] = elements[j];
			}

			currentContext = new Array;
			var currentContextIndex = 0;
			var checkFunction;
			switch(attrOperator)
			{
				case '=':
					checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
					break;
				case '~':
					checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
					break;
				case '|':
					checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
					break;
				case '^':
					checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
					break;
				case '$':
					checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
					break;
				case '*':
					checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
					break;
				default :
					checkFunction = function(e) { return e.getAttribute(attrName); };
			}

			currentContext = new Array;
			var currentContextIndex = 0;
			for(var k=0;k<found.length;k++)
			{
				if(checkFunction(found[k]))
					currentContext[currentContextIndex++] = found[k];
			}

			continue;
		}

		tagName = token;
		var found = new Array;
		var foundCount = 0;
			for(var h=0;h<currentContext.length;h++)
			{
				//alert(currentContext[h]);
				if(currentContext[h]){
					var elements = currentContext[h].getElementsByTagName(tagName);
					for(var j=0;j<elements.length; j++)
						found[foundCount++] = elements[j];
				}
			}

		currentContext = found;
	}

	return currentContext;
}



/* @constructor */
function EventUtils() {
	throw 'RuntimeException: EventUtils is a static utility class ' +
		' and may not be instantiated';
}

/**
 *	@access static
 *	@param HTMLElement target
 *	@param string type
 *	@param Function callback
 *	@param boolean captures
 */
EventUtils.addEventListener = function (target,type,callback,captures) {
	if (target.addEventListener) {
			// EOMB
		target.addEventListener(type,callback,captures);
	} else if (target.attachEvent) {
		// IE
		target.attachEvent('on'+type,callback,captures);
	} else {
		// IE 5 Mac and some others
		target['on'+type] = callback;
	}
}

EventUtils.removeEventListener = function (target,type,callback,captures) {
	if (target.removeEventListener) {
			// EOMB
		target.removeEventListener(type,callback,captures);
	} else if (target.detachEvent) {
		// IE
		target.detachEvent('on'+type,callback);
	} else {
		// IE 5 Mac and some others
		target['on'+type] = null;
	}
}

EventUtils.addEventListener(window,'load',doReplace);
//addEvent(window,'load',replaceSectionHeader);
//addEvent(window,'load',replacePromo);
