/*  WAFCMS
*   Copyright (C) 2004-2005 W.A. Fisher Interactive-2005
*
*   This software is not free software; you can not redistribute it or
*   modify it under the terms of the W.A. Fisher Interactive Code License
*   version 1.0 of the License, or (at your option) any later version.
*
*   This software 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 W.A.
*   Fisher Interactive Code License for more details.
*
*   You should have received a copy of the W.A. Fisher Interactive Code
*   License along with this software; if not, write to W.A. Fisher Interactive,
*   PO Box 1107, Virginia, MN 55792-1107 USA
*
*   You may also contact W.A. Fisher Interactive via e-mail at info@wafishermn.com
*   with a subject line of "W.A. Fisher Interactive."
*
*   Last Modified: 2/16/2005 8:13AM
*   File: _site_components/js/text_replace.js
*   Searches the document for specified CSS Selectors and replaces their text content with
*   dynamicly-generated images handled by a separate php script.
*
*   Based on Stewart Rosenberger's "Dynamic Heading Generator" 
*   http://www.stewartspeak.com/headings/
*/

function css_selector_image_replacement(cssSel,wordWrap,fontFace,fSize,fColor,fHilite,fTrans) {
    perform_replacement(cssSel,wordWrap,fontFace,fSize,fColor,fHilite,fTrans);
    var testImageUrl = '/_site_components/images/spacer.png';
    var phpScriptUrl = '/_include/loonfest/lol_headline.php'
    
    var skipImageReplacement = false;
//    var printerCSS = "replacement-print.css";

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

    var itemsToReplace;
    var testImageLoaded = false;
    var documentLoaded = false;


    function perform_replacement(selector,wordwrap,font,size,color,hilite,trans){
        // color and hilite need to be hex rgb colors *without* the leading #
        
        // make sure that we have an array to store the items in
	    if(typeof(itemsToReplace)== "undefined") itemsToReplace = new Array();
	    
	    // add the passed parameters to the end of the items array
	    itemsToReplace[itemsToReplace.length] = {selector: selector, wordwrap: wordwrap, font: font, size: size, color: color, hilite: hilite, trans: trans};
    }

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

    var testImage = new Image();
    testImage.onload = function() { testImageLoaded = true; if(documentLoaded) doReplace(); };
    testImage.src = testImageUrl + "?date=" + (new Date()).getTime();
    addLoadHandler(function(){ documentLoaded = true; if(testImageLoaded) doReplace(); });


    function documentLoad(){
	    documentLoaded = true;
	    if(testImageLoaded) doReplace();
    }

    function doReplace(){
	    for(var i=0;i<itemsToReplace.length;i++){
		    var elemsToReplace = getElementsBySelector(itemsToReplace[i].selector);
		    if(elemsToReplace.length > 0)
		        for(var j=0;j<elemsToReplace.length;j++){
			        if(!elemsToReplace[j]) continue;
		
			        var text = getElemText(elemsToReplace[j]);
    		        while(elemsToReplace[j].hasChildNodes())
				        elemsToReplace[j].removeChild(elemsToReplace[j].firstChild);

			        var textPieces = itemsToReplace[i].wordwrap ? text.split(' ') : [text];
			        for(var k=0;k<textPieces.length;k++){
				        var url = phpScriptUrl + "?t="+escape(textPieces[k]+' ')+"&f="+itemsToReplace[i].font+"&s="+itemsToReplace[i].size+"&c="+itemsToReplace[i].color+"&h="+itemsToReplace[i].hilite+"&x="+itemsToReplace[i].trans; //+"&selector="+escape(itemsToReplace[i].selector)
				        var image = document.createElement("img");
				        image.className = "replacement";
				        image.alt = textPieces[k];
				        image.src = url;
				        elemsToReplace[j].appendChild(image);
			        }

			        if(skipImageReplacement){
    				    var span = document.createElement("span");
				        span.style.display = 'none';
				        span.className = "print-text";
				        span.appendChild(document.createTextNode(text));
				        elemsToReplace[j].appendChild(span);
			        }
		        }
	    }

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

    function addLoadHandler(handler){
	    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){
	    var sheet = document.getElementById(id);
	    if(sheet)
		    sheet.disabled = (!enabled);
    }

    function getElemText(element){
	    if(typeof element == "string")
		    return element;
	    else if(typeof element == "undefined")
		    return element;
	    else if(element.innerText)
		    return element.innerText;

	    var text = "";
	    var kids = element.childNodes;
	    for(var i=0;i<kids.length;i++){
		    if(kids[i].nodeType == 1)
		        text += getElemText(kids[i]);
		    else if(kids[i].nodeType == 3)
		        text += kids[i].nodeValue;
	    }
	    return text;
    }

    /*
    	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++){
    			var elements = currentContext[h].getElementsByTagName(tagName);
    			for(var j=0;j<elements.length; j++)
    				found[foundCount++] = elements[j];
    		}
    
    		currentContext = found;
    	}
    
    	return currentContext;
    }


}

// put this in the HTML part of the document after including this file
/*
if(document.createElement && document.getElementsByTagName && !navigator.userAgent.match(/opera\/?6/i))
	css_selector_image_replacement(cssSel,wordWrap,fontFace,fSize,fColor,fHilite,fTrans);
*/
