

function onBodyLoad(){

convertLettersToLinks('definition');

}



/**
 * Verify if we are inside a "bad" tag, so that the inner content should not be converted
 *
 * @return <Boolean>    True, if it's bad, false otherwise.
 */
function isBadTag(tagName)
{
	tagName=tagName.replace(/[^a-zA-Z0-9]+.*$/i,'');
	//console.log('isBadTag['+tagName0+']['+tagName+']');
	return (tagName=='script'||tagName=='object'||tagName=='embed'
		||tagName=='applet'||tagName=='style'
		||tagName=='canvas'||tagName=='svg'||tagName=='a'||tagName=='iframe'
		||tagName=='input'||tagName=='button'||tagName=='textarea'||tagName=='select');
}

/**
 * Converts single letters from the document into mailto: links
 *
 * @variable    Node            <Entity>    The node to be parsed
 * @variable    htmlContent     <String>    The content of the provided node
 * @variable    i               <Integer>   The iterator over the array of letters
 * @variable    n               <Integer>   Number of letters in the array
 * @variable    tag             <Boolean>   Flag: 1 if we are inside a <tag>, 0 otherwise
 * @variable    tagName         <String>    Name of the current tag being parsed (including / for closing tag)
 * @variable    entity          <Boolean>   Flag: 1 if we are inside an &entity;, 0 otherwise
 * @variable    ch              <String>    Single character being handled at the current position within the letters array
 * @variable    add             <Integer>   Flag: 1 if we should add the content to the resulting html
 * @variable    output          <String>    The resulting HTML output
 *
 * @return      The HTML output
 */
function convertLettersToLinks(myNodeId)
{
	var node=document.getElementById(myNodeId),
		htmlContent=node.innerHTML,
		letters=htmlContent.split(''),
		i=0,
		n=letters.length,
		tag=0,
		tagName='',
		tagStack=[],
		entity=0,
		ch,
		add=0,
		output='';

	for(;i<n;i++)
	{
		ch=letters[i];
		if(ch=='<'){add=tag=1;}
		else if(ch=='>'){add=1;tag=0;
			//console.log('TAG['+tagName+']');
			if(tagName.substr(0,1)=='/')
			{
				//console.log('popT['+tagName+']');
				if(isBadTag(tagName.substr(1)))
					tagStack.pop();
			}
			else
			{
				//console.log('pushT['+tagName+']');
				if(isBadTag(tagName))
					tagStack.push(tagName);
			}

			tagName='';
		}
		else if(ch=='&'){add=entity=1;}
		else if(ch==';'){add=1;entity=0;}
		else if((entity==0&&tag==0&&tagStack.length<1)&&((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')))
		{
			add=0;
			output+="<a href='/index.php/alpha/letter/"+ch+"'>"+ch+"</a>";
		}
		else
		{
			add=1;
			if(tag)tagName+=ch;
		}

		if(add)output+=ch;

		//console.log(i,ch,tag,output);

		//if(i > 100) break;
	}

	return node.innerHTML=output;
}

