/*
	© 2008 MJDIGITAL
	Written by Mark Jackson - code@mjdigital.co.uk
		Replaces selected tags with Flash text objects
		Works a bit like sifr - http://en.wikipedia.org/wiki/Scalable_Inman_Flash_Replacement
		but nowhere near as advanced! Before you steal this I would suggest you look at sifr - it's much better!
		If you are hell-bent on stealing this code then please have the decency to let me know that you liked it
		by dropping me a quick email to say - "Hey, I liked it"! Who knows - I may write more and send you the updates!
		If you want the .FLA then let me know.
	All rights reserved

*/
var alreadyrunflag=0 //flag to indicate whether init function has already been run


function getStyle(oElm, strCssRule){
	var strValue = "";
	if(document.defaultView && document.defaultView.getComputedStyle){
		strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
	}
	else if(oElm.currentStyle){
		strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
			return p1.toUpperCase();
		});
		strValue = oElm.currentStyle[strCssRule];
	}
	return strValue;
}

function toHex(N) {
 if (N==null) return "00";
 N=parseInt(N); if (N==0 || isNaN(N)) return "00";
 N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
 return "0123456789ABCDEF".charAt((N-N%16)/16)
      + "0123456789ABCDEF".charAt(N%16);
}

function flashEncode(txt) {
	s = new Array("%","&copy;","&reg;","&trade;",'"',"&amp;","'");
	r = new Array("%25","%26%23169;","%26%23174;","%E2%84%A2","%22","%26","%27");
	// add ampersand last to avoid overwriting HTML coded characters
	s.push("&");
	r.push("%26");
	// replace all special characters
	for(c=0;c<s.length;c++) {
		src = new RegExp(s[c],"gi");
		txt = txt.replace(src,r[c]);
	}
	return txt;
}

var els = new Array("h1","h2","h3","h4","h5","h6","big");
function init(o,prefix,undo) {
	if(undo) {
		// remove print warning
		document.getElementById('print_warning').style.display = "none";
	}
	for(id in els) {
		tag = els[id];
		if(o!=''&&o!=null) {
			o=(typeof(o)=='object') ? o : document.getElementById(o);	
		} else {
			o=document;	
		}
		es = o.getElementsByTagName(tag);
		if(es.length>0) {
			args = new Object();
			for(i=0;i<es.length;i++) {
				e=es[i];
				if((e.lang!='noreplace')&&(getStyle(e,"caption-side")!='left')) {
					prefix = (prefix) ? prefix : '';
					args.id = prefix+"_"+tag+"_"+i;
					args.txt = e.innerHTML;
					if(!undo) {
						e.txt = e.innerHTML;
					} else {
						if(e.txt) { e.innerHTML = e.txt }
					}
					args.fSize = getStyle(e,"font-size").replace(/px/,""); // get font size
					args.fWeight = getStyle(e,"font-weight"); args.fWeight = (args.fWeight<500) ? 'false' : 'true'; // get font weight - bold or normal only
					args.fItalic = getStyle(e,"font-style"); args.fItalic = (args.fItalic=='italic') ? 'true' : 'false'; // get font weight - bold or normal only
					args.fStyle = getStyle(e,"font-style");
					args.fColor = getStyle(e,"color").replace(/#/,"0x");
					args.fDecor = getStyle(e,"text-decoration"); args.fDecor = (args.fDecor=="underline") ? 'true' : 'false';
					args.fAlign = getStyle(e,"text-align"); args.fAlign = (args.fAlign=="start") ? "left" : args.fAlign;
					args.eBGcolor = getStyle(e,"background-color");
					args.eWidth = getStyle(e,"width").replace(/px/,""); args.eWidth = (args.eWidth=="auto") ? e.offsetWidth : args.eWidth;
					args.eHeight = getStyle(e,"height").replace(/px/,""); args.eHeight = (args.eHeight=="auto") ? e.offsetHeight : args.eHeight;	
					lColor = lDecor = lWeight = '';
					// get link info
						// <tag><a href...>text</a></tag>
						if((args.txt.search(/<a/i)!=-1)&&(args.txt.search(/href=/i)!=-1)) {
							l = e.getElementsByTagName('a')[0];
							args.lHref = l.href;
							args.lTarget = l.target;
							lWeight = getStyle(l,"font-weight"); lWeight = (lWeight<500) ? 'false' : 'true';
							lColor = getStyle(l,"color").replace(/#/,"0x");
							lDecor = getStyle(l,"text-decoration"); lDecor = (lDecor=="underline") ? 'true' : 'false';
						}
						// <a href...><tag>text</tag></a>
						aLink = checkParent(e,'A','obj');
						if(aLink) { 
							args.lHref = aLink.href;
							args.lTarget = aLink.target;
						}
	
					args.fColor = (lColor!='') ? lColor : args.fColor;
					args.fDecor = (lDecor!='') ? lDecor : args.fDecor;
					args.fWeight = (lWeight!='') ? lWeight : args.fWeight;
					
					// process colour for FF
					if(args.fColor.search(/rgb/i)!=-1) {
						fColor = args.fColor.replace(/rgb\(/i,""); fColor = fColor.replace(/\)/,"");	
						r = toHex(fColor.split(", ")[0]);
						g = toHex(fColor.split(", ")[1]);
						b = toHex(fColor.split(", ")[2]);
						args.fColor = "0x"+r+g+b;
					}
					
					// add search highlight
					if(args.txt.search(/searchHighlight/gi)!=-1) {
						//contents = args.txt.substring(args.txt.search(/<span class=searchHighlight>/gi)+28);
						//contents = contents.substring(0,contents.search(/<\/span>/gi));
						//args.txt = args.txt.replace(/<span class=searchHighlight>(.+)<\/span>/gi,'<u>'+contents+'</u>');
						//alert(args.txt)
						// basic replace function - needs fixing
						args.txt = args.txt.replace(/<span class="searchHighlight">/gi,'<u>');
						args.txt = args.txt.replace(/<span class=searchHighlight>/gi,'<u>');
						args.txt = args.txt.replace(/<\/span>/gi,'</u>');
					}
					
					// make text Flash Safe
					args.txt = flashEncode(args.txt);
					
					// strip tags out of text
					//args.txt = escape(cleanUpTxt(args.txt).replace(/(<([^>]+)>)/ig,""));
					args.txt = strip_tags(args.txt, '<u>');

					args.tag = tag;
					
					// Test to make sure the object is actually visible
					if(checkVisibility(e)) {
						if(!undo) {
							insertFlash(e,args);
						}
					}
					args = new Object();
				}
			}
		}
	}
}

function strip_tags(str, allowed_tags) {
    // Thanks to: http://kevin.vanzonneveld.net
    var key = '', allowed = false;
    var matches = [];
    var allowed_array = [];
    var allowed_tag = '';
    var i = 0;
    var k = '';
    var html = '';
 
    var replacer = function(search, replace, str) {
        return str.split(search).join(replace);
    };
 
    // Build allowes tags associative array
    if (allowed_tags) {
        allowed_array = allowed_tags.match(/([a-zA-Z]+)/gi);
    }
  
    str += '';
 
    // Match tags
    matches = str.match(/(<\/?[\S][^>]*>)/gi);
 
    // Go through all HTML tags
    for (key in matches) {
        if (isNaN(key)) {
            // IE7 Hack
            continue;
        }
 
        // Save HTML tag
        html = matches[key].toString();
 
        // Is tag not in allowed list? Remove from str!
        allowed = false;
 
        // Go through all allowed tags
        for (k in allowed_array) {
            // Init
            allowed_tag = allowed_array[k];
            i = -1;
 
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
            if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}
 
            // Determine
            if (i == 0) {
                allowed = true;
                break;
            }
        }
        if (!allowed) { str = replacer(html, "", str); // Custom replace. No regexing
		}
    }
    return str;
}


function checkParent(e,tag,retProp) {
	retVal = false;
	while(e.parentNode){
		if((e.parentNode)&&(e.parentNode.nodeName!='BODY')) {
			if (e.parentNode.nodeName==tag) { 
				if(retProp=='obj') {
					retVal = e.parentNode;
				} else {
					retVal = eval('e.parentNode.'+retProp); 
				}
				break;
			} else {
				break;
			}
		} else { retVal = false; }
	}
	return retVal;
}

function checkVisibility(e) {
	retVal = true;
	while(e.parentNode){
		if((e.parentNode)&&(e.parentNode.nodeName!='BODY')) {
			if (e.parentNode.style.display=='none') { 
				retVal = false; 
				break;
			} else {
				break;
			}
		} else { retVal = false; }
	}
	return retVal;
}

function jsAlert(txt) {
	//txt = ""+txt;
	alert(txt);
}

function flashObj(o) {
		obj = document.getElementById(o+"_obj");
		emb = document.getElementById(o+"_emb");
		if (navigator.appName.indexOf("Microsoft") != -1) {
			return obj; // for IE
		} else {
			return emb; // for FF
		}
}

function cleanUpTxt(txt) {
	replaceThis1 = "%";
	replaceThis2 = "\\+";
	txt = txt.replace( RegExp(replaceThis1,'g'),"%25");
	txt = txt.replace( RegExp(replaceThis2,'g'),"%2B");
	return txt;	
}

function resizeMe(o,h,w) { // called by flash object
	el = document.getElementById(o)	;
	fl = flashObj(o);
	if((fl.offsetHeight>(parseInt(h))) || (fl.offsetHeight<(parseInt(h)-5))) { // allow a 5px buffer
		fl.style.height = h+"px";
	}
	if((fl.offsetWidth>(parseInt(w))) || (fl.offsetWidth<(parseInt(w)-5))) { // allow a 5px buffer
		fl.style.width = w+"px";
	}
}

function insertFlash(obj,args) {
	flashFile = "/images/flash/"; // SWF file directory
	//flashFile += args.tag; // choose swf file (tag name)
	flashFile += "rockwell"; // choose default swf file
	flashFile += ".swf"; // add .SWF 

	flashVars = '';
	for(a in args) {
		flashVars += a+"="+args[a]+"&";	
	}
	flashVars += "fHcolor=0x999999"; // link hover colour
	flashVars += "&obj="+args.id; // pass object
	//alert(flashVars)
	flash = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" width="'+args.eWidth+'" height="'+args.eHeight+'" id="'+args.id+'_obj"><param name="movie" value="'+flashFile+'" /><param name="quality" value="high" /><param name="menu" value="false" /><param name="scale" value="noscale" /><param name="allowScriptAccess" value="always" /><param name="wmode" value="transparent" /><param name="swliveconnect" value="true" /><param name="flashVars" value="'+flashVars+'" /><embed id="'+args.id+'_emb" src="'+flashFile+'" quality="high" menu="false" scale="noscale" wmode="transparent" allowScriptAccess="always" swliveconnect="true" flashVars="'+flashVars+'" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="'+args.eWidth+'" height="'+args.eHeight+'"></embed></object>';
	obj.innerHTML = flash;
	//alert(flash)
	args = '';
}

<!-- DETECT FLASH
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');
}
//-->
if(!MM_FlashCanPlay) { // FLASH IS INSTALLED
	// do something (or nothing) if Flash version is not installed
	document.write('<link href="css/headings.css" rel="stylesheet" type="text/css" media="screen" />');
} else {
	
	// DOM Ready script - to replace on load (faster)
	if (document.addEventListener) { // firefox etc
	  document.addEventListener("DOMContentLoaded", function(){alreadyrunflag=1; init()}, false);
	} else if (document.all && !window.opera){ // crude test for IE
	  document.write('<script type="text/javascript" id="contentloadtag" defer="defer" src="javascript:void(0)"><\/script>')
	  var contentloadtag=document.getElementById("contentloadtag")
	  contentloadtag.onreadystatechange=function(){
		if (this.readyState=="complete"){
		  alreadyrunflag=1
		  init()
		}
	  }
	}
	
	window.onload=function(){
	  setTimeout("if (!alreadyrunflag) init()", 0)
	}
}

