//CUSTOM
//CUSTOM_SUMMARY whole file is custom

function debug(msg) {
    //alert(msg);
}

function trim(string){
     //return string.replace(new RegExp("\s+("+string+")\s+","g"), string);
	return string.replace(/^\s */g,'').replace(/\s *$/g,'');
}

function com_stewartspeak_replacement() {
    /*
	Dynamic Heading Generator
	By Stewart Rosenberger
	http://www.stewartspeak.com/headings/

	This script searches through a web page for specific or general elements
	and replaces them with dynamically generated images, in conjunction with
	a server-side script.
	*/

	function initiateImageReplacement() {
		debug('initiateImageReplacement');
        /*
		Note: the selector function doesnt work well with id's
		- this function is here in order that the
		*/

		//var URLbase = "http://tom.dyson.name/dynamic-text/heading.php?";
		var URLbase = "http://www.rethink.org/applications/dynamicText/heading.php?";
		var h1Color = '';
		var h1BgColor = '';
		var h1Selector = '';

        // H1 - implemnting fake inheritance for h1's (based on one h1 per page)
		if(testSelector("div.involved div.themeDarkFill h1")) {
            // h1 styles for the section indexes - purple for involved
			h1Color = 'ffffff';
			h1BgColor = 'B43C96';
			h1Selector = "div.involved div.themeDarkFill h1";

		} else if(testSelector("div.help div.themeDarkFill h1")) {
            // h1 styles for the section indexes - orange for help
			h1Color = 'ffffff';
			h1BgColor = 'FBB031';
			h1Selector = "div.help div.themeDarkFill h1";

		} else if(testSelector("div.about div.themeDarkFill h1")) {
            // h1 styles for the section indexes - green for about
			h1Color = 'ffffff';
			h1BgColor = '8CC63E';
			h1Selector = "div.about div.themeDarkFill h1";

		} else if(testSelector("div.living div.themeDarkFill h1")) {
            // h1 styles for the section indexes - pink for living
			h1Color = 'ffffff';
			h1BgColor = 'ed008c';
			h1Selector = "div.living div.themeDarkFill h1";

		} else if(testSelector("div.root div.themeDarkFill h1")) {
            // h1 styles for the section indexes - dk blue for root
			h1Color = 'ffffff';
			h1BgColor = '005DAB';
			h1Selector = "div.root div.themeDarkFill h1";

		} else if(testSelector("div.rethink div.themeDarkFill h1")) {
            // h1 styles for the section indexes - dk blue for rethink
			h1Color = 'ffffff';
			h1BgColor = '005DAB';
			h1Selector = "div.rethink div.themeDarkFill h1";

		} else if(testSelector("div.news div.themeDarkFill h1")) {
            // h1 styles for the section indexes - orange for news
			h1Color = 'ffffff';
			h1BgColor = 'Fbb031';
			h1Selector = "div.news div.themeDarkFill h1";

		} else if(testSelector("div.account div.themeDarkFill h1")) {
            // h1 styles for the section indexes - default to pink for inthink
			h1Color = 'ffffff';
			h1BgColor = '005DAB';
			h1Selector = "div.account div.themeDarkFill h1";

		} else if(testSelector("div.membership div.themeDarkFill h1")) {
            // h1 styles for the section indexes - default to blue for membership
			h1Color = 'ffffff';
			h1BgColor = '005DAB';
			h1Selector = "div.themeDarkFill h1";

		} else if(testSelector("div.activists div.themeDarkFill h1")) {
            // h1 styles for the section indexes - default to green for activists
			h1Color = 'ffffff';
			h1BgColor = '8CC63E';
			h1Selector = "div.themeDarkFill h1";

		} else if(testSelector("div.groups div.themeDarkFill h1")) {
            // h1 styles for the section indexes - default to orange for groups
			h1Color = 'ffffff';
			h1BgColor = 'FBB031';
			h1Selector = "div.themeDarkFill h1";

		} else if(testSelector("div.governance div.themeDarkFill h1")) {
            // h1 styles for the section indexes - default to pink for governance
			h1Color = 'ffffff';
			h1BgColor = 'ed008c';
			h1Selector = "div.themeDarkFill h1";

		} else if(testSelector("div.themeDarkFill h1")) {
            // h1 styles for the section indexes - default to pink for inthink
			h1Color = 'ffffff';
			h1BgColor = 'ed008c';
			h1Selector = "div.themeDarkFill h1";

		} else if(testSelector("div.involved h1")) {
            // h1 styles - purple for involved
			h1Color = 'B43C96';
			h1BgColor = 'ffffff';
			h1Selector = "div.involved h1";

		} else if(testSelector("div.help h1")) {
            // h1 styles - orange for help
			h1Color = 'FBB031';
			h1BgColor = 'ffffff';
			h1Selector = "div.help h1";

		} else if(testSelector("div.about h1")) {
            // h1 styles - green for about
			h1Color = '8CC63E';
			h1BgColor = 'ffffff';
			h1Selector = "div.about h1";

		} else if(testSelector("div.living h1")) {
            // h1 styles - pink for living
			h1Color = 'ed008c';
			h1BgColor = 'ffffff';
			h1Selector = "div.living h1";

		} else if(testSelector("div.news h1")) {
            // h1 styles - orange for news
			h1Color = 'Fbb031';
			h1BgColor = 'ffffff';
			h1Selector = "div.news h1";

		} else if(testSelector("div.membership h1")) {
            // h1 styles - blue for membership
			h1Color = '005DAB';
			h1BgColor = 'ffffff';
			h1Selector = "div.membership h1";

		} else if(testSelector("div.activists h1")) {
            // h1 styles - green for activists
			h1Color = '8CC63E';
			h1BgColor = 'ffffff';
			h1Selector = "div.activists h1";

		} else if(testSelector("div.groups h1")) {
            // h1 styles - orange for groups
			h1Color = 'fbb031';
			h1BgColor = 'ffffff';
			h1Selector = "div.groups h1";

		} else if(testSelector("div.governance h1")) {
            // h1 styles - pink for governance
			h1Color = 'ed008c';
			h1BgColor = 'ffffff';
			h1Selector = "div.governance h1";

		} else if(testSelector("div.root h1")) {
            // h1 styles - dark blue for root
			h1Color = '000000';
			h1BgColor = 'ffffff';
			h1Selector = "div.root h1";

		} else if(testSelector("div.rethink h1")) {
            // h1 styles - dark blue for for rethink
			h1Color = '000000';
			h1BgColor = 'ffffff';
			h1Selector = "div.rethink h1";

		} else if(testSelector("div.account h1")) {
            // h1 styles - dark blue for for rethink
			h1Color = '000000';
			h1BgColor = 'ffffff';
			h1Selector = "div.account h1";

		}else if(testSelector("div.inthinkHomepage h1")) {
            // default h1 styles - default to pink for inthink
			h1Color = '000000';
			h1BgColor = 'ffffff';
			h1Selector = "div.inthinkHomepage h1";
		}else if(testSelector("h1")) {
            // default h1 styles - default to pink for inthink
			h1Color = 'ed008c';
			h1BgColor = 'ffffff';
			h1Selector = "h1";
		}

        // if any of the above were matched then we call the replace selector function to kick off the replacement for our h1
		if((h1Selector !='') && (h1Color != '') && (h1BgColor !='')) {
			replaceSelector(h1Selector,URLbase+"colour="+h1Color+"&background_color="+h1BgColor,true);
		}

         /*// h2
		var h2Color = 'ed008c';
		var h2Size = '15';
		var h2BgColor = 'ffffff';
		var h2Selector = 'h2';
		if(testSelector("h2")) {
            // default h1 styles - default to pink for inthink
			h2Color = 'ed008c';
			h2BgColor = 'ffffff';
			h2Selector = "h2";
			replaceSelector(h2Selector,URLbase+"colour="+h2Color+"&background_color="+h2BgColor+"&size="+h2Size,true);
		} else if(testSelector("h2")) {
            // default h1 styles - default to pink for inthink
			h2Color = 'ed008c';
			h2BgColor = 'ffffff';
			h2Selector = "h2";
			replaceSelector(h2Selector,URLbase+"colour="+h2Color+"&background_color="+h2BgColor+"&size="+h2Size,true);
		}

        // search
		if(testSelector("label.search")) {
             // default h1 styles - default to pink for inthink
			searchColor = 'ed008c';
			searchBgColor = 'ffffff';
			searchSelector = "label.search";
			searchSize = '11';
			replaceSelector(searchSelector,URLbase+"colour="+searchColor+"&background_color="+searchBgColor+"&size="+searchSize,true);
		}
       //re-word

		if(testSelector("p.tagLine")) {
             // default search label styles - white for homepage
			var taglineColor = '00ADEF';
			var taglineBgColor = 'FFFFFF';
			var taglineSelector = "p.tagLine";
			var taglineSize = '11';
			replaceSelector(taglineSelector,URLbase+"colour="+taglineColor+"&background_color="+taglineBgColor+"&size="+taglineSize,true);
		}*/
	}

    // call inner function to initiate
	initiateImageReplacement();

	var testURL = "/display_images/test.png" ;

	var doNotPrintImages = false;
	var printerCSS = "replacement-print.css";

	var hideFlicker = false;
	var hideFlickerCSS = "replacement-screen.css";
	var hideFlickerTimeout = 1000;




    /* ---------------------------------------------------------------------------
	For basic usage, you should not need to edit anything below this comment.
	If you need to further customize this script's abilities, make sure
	you're familiar with Javascript. And grab a soda or something.
	*/

	var items;
	var imageLoaded = false;
	var documentLoaded = false;

	function testSelector(selector) {
        //debug('testSelector('+selector+')');
        /*
		added in order to fake selector inheritance and call the
		image replacement with more than one colour / bg colour
		*/
		var exists = false;
        // set up array
        //replaceSelector(selector,'http://tom.dyson.name/dynamic-text/heading.php',true);
        //replaceSelector(selector,'http://rethink-live.torchboxapps.com/applications/dynamicText/heading.php',true);
        //alert('1 '+items.length);
        //for(var i=0;i<items.length;i++) {
		var matchingElements = getElementsBySelector(selector);
		if(matchingElements.length > 0) {
//                 for(var j=0;j<elements.length;j++){
//                 if(!elements[j]) {
//                     continue ;
//                 }
//                 // the selector has been matched
			exists = true;
			debug('selector '+selector+' exists');
		}
        //}
		// reset items*/
        //items = new Array();
		return exists;
	}

	function replaceSelector(selector,url,wordwrap) {
		debug('replaceSelector('+selector+')');
        //alert(typeof items)
		if(typeof items == "undefined") {
			items = new Array();
		}
        //alert('2'+items.length);
		debug(items.length);
		items[items.length] = {selector: selector, url: url, wordwrap: wordwrap};
		debug(items.length);
	}

	if(hideFlicker) {
		debug('hideFlicker');
		document.write('<link rel="stylesheet" media="screen" href="' + hideFlickerCSS + '" />');
		window.flickerCheck = function() {
			if(!imageLoaded) {
				setStyleSheetState('hide-flicker',false);
			}
		};
		setTimeout('window.flickerCheck();',hideFlickerTimeout)
	}

	if(doNotPrintImages) {
		debug('doNotPrintImages');
		document.write('<link id="print-text" rel="stylesheet" media="print" href="' + printerCSS + '" />');
	}
	
	documentLoad();//to fix the problem with image not loading. Not sure where this should have been called initially.
	var test = new Image();
	test.onload = function() { imageLoaded = true; if(documentLoaded) replacement(); };
	test.src = testURL + "?date=" + (new Date()).getTime();

	addLoadHandler(function(){ documentLoaded = true; if(imageLoaded) replacement(); });


	function documentLoad() {
		debug('documentLoad');
		documentLoaded = true;
		if(imageLoaded) {
			replacement();
		}
	}

	function replacement() {
		debug('replacement');
        //debug('3'+items.length);
		if ((typeof items != 'undefined') && (items.length > 0)) {
			debug(items.length);
			for(var i=0;i<items.length;i++) {
				var elements = getElementsBySelector(items[i].selector);
				if(elements.length > 0) for(var j=0;j<elements.length;j++){
					if(!elements[j]) {
						continue ;
					}
                    //debug(extractText(elements[0]));
					var text = extractText(elements[j]);
					while(elements[j].hasChildNodes()) {
						elements[j].removeChild(elements[j].firstChild);
					}
					var tokens = items[i].wordwrap ? text.split(' ') : [text] ;
					for(var k=0;k<tokens.length;k++) {
						var url = items[i].url + "&text="+escape(tokens[k]+' ')+"&selector="+escape(items[i].selector);
						var image = document.createElement("img");
						image.className = "replacement";
						image.alt = tokens[k] ;
						image.src = url;
						elements[j].appendChild(image);
					}

					if(doNotPrintImages) {
						var span = document.createElement("span");
						span.style.display = 'none';
						span.className = "print-text";
						span.appendChild(document.createTextNode(text));
						elements[j].appendChild(span);
					}
				}
			}
		} else {
			debug('items undefined or null');
		}

		if(hideFlicker)
		setStyleSheetState('hide-flicker',false);
	}

	function addLoadHandler(handler) {
		debug('addLoadHandler');
		if(window.addEventListener) {
			window.addEventListener("load",handler,false);
		} else if(window.attachEvent) {
			window.attachEvent("onload",handler);
		} else if(window.onload) {
			var oldHandler = window.onload;
			window.onload = function piggyback() {
				oldHandler();
				handler();
			};
		} else {
			window.onload = handler;
		}
	}

	function setStyleSheetState(id,enabled) {
		debug('setStyleSheetState');
		var sheet = document.getElementById(id);
		if(sheet) {
			sheet.disabled = (!enabled);
		}
	}

	function extractText(element) {
		debug('extractText');
        //alert(element.tagName);
		if(typeof element == "string") {
			return element;
		} else if(typeof element == "undefined") {
			return element;
		} else if(element.innerText) {
			return element.innerText;
		}
		var elementText = "";
		var kids = element.childNodes;
		for(var i=0;i<kids.length;i++) {
			if(kids[i].nodeType == 1) {
				elementText += extractText(kids[i]);
			} else if(kids[i].nodeType == 3) {
				elementText += kids[i].nodeValue;
			}
		}
        //alert(elementText);
        //alert(trim(elementText));
		return trim(elementText);
	}

    /*
	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.
        See here for original code (with comments and description):
	http://simon.incutio.com/archive/2003/03/25/getElementsBySelector
	*/
	function getElementsBySelector(selector) {
        //debug('getElementsBySelector('+selector+')');
        //alert('looking for selector '+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;
			}

            /* That revolting regular expression explained
			/^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/
			\---/  \---/\-------------/    \-------/
			|      |         |               |
			|      |         |           The value
			|      |    ~,|,^,$,* or =
			|   Attribute
			Tag
			*/
			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++) {
				var elements = currentContext[h].getElementsByTagName(tagName);
				for(var j=0;j<elements.length; j++) {
					found[foundCount++] = elements[j];
				}
			}
			currentContext = found;
		}
		return currentContext;
	}
}// end of scope, execute code

if(document.createElement && document.getElementsByTagName && !navigator.userAgent.match(/opera\/?6/i)) {
    // if able to perform key functions in code and browser is not opera 6
	addEvent(window, 'load', com_stewartspeak_replacement);
}
