/*
* Thesaurus
*
* @package thesaurus
* @author $Author: sheiko $  
* @since v.2.0.3 
* @copyright (c) Dmitry Sheiko http://www.cmsdevelopment.com 
*/ 
var THConfig = { 
		CaseSensitive: "off", 
		Charset: "UTF-8",
		Copyrights: '<div class="header"><a href="/sp/tools/glossary/">Glosario</a><div class="hr"></div></div>',
		CtrlURL: "/sp/tools/glossary/db_controller.php",
		divName: 'InstantMessage',
		MemoryCache: 'on',
		parseElements: []
};

var Timer = null;
var Cache = [];
var AcceptMessage=true;

var SubstitutionTable = new Array();

if(document.implementation && document.implementation.createDocument) var isMozilla=true;
	else var isMozilla=false;

	
document.write('<div id="'+THConfig.divName+'" onmouseover="clearTimer()" onmouseout=\"setTimer();\" class="instant_message">&nbsp;</div>');

// Short name of function
function $(divName) {
	return document.getElementById(divName);
}

function hideMessage(){
	var MessageObj=$(THConfig.divName);
	MessageObj.style.visibility="hidden";
}

function clearTimer() {
 if (Timer) {
   clearTimeout(Timer);
   Timer = null;
 }
}

function setTimer() {
 	Timer = window.setTimeout('hideMessage()', 250);
}

window.size = function()
{
	var w = 0;
	var h = 0;
	//IE
	if(!window.innerWidth)
	{
		//strict mode
		if(!(document.documentElement.clientWidth == 0)) {
			w = document.documentElement.clientWidth;
			h = document.documentElement.clientHeight;
		}
		//quirks mode
		else {
			if(document.body.clientWidth) {
				w = document.body.clientWidth;
				h = document.body.clientHeight;
			} else {
				w = window.document.body.offsetWidth;
				h = window.document.body.offsetHeight;
			}
		}
	}
	//w3c
	else {
		w = window.innerWidth;
		h = window.innerHeight;
	}
	return {width:w,height:h};
}

function adjustMessage(evt) {
	var left;
	var top;
	clearTimer();
	MessageObj = $(THConfig.divName);
	if (isMozilla) event=evt;

	wsize = window.size();
	var rightedge = wsize.width-event.clientX;
	var bottomedge = wsize.height-event.clientY;
	
	// Compliance with HTML 4/XHTML
	if(document.documentElement && document.documentElement.scrollTop)
		scrollTop = document.documentElement.scrollTop;
	else
		scrollTop = document.body.scrollTop;
		
	// Compliance with HTML 4/XHTML
	if(document.documentElement && document.documentElement.scrollLeft)
		scrollLeft = document.documentElement.scrollLeft;
	else
		scrollLeft = document.body.scrollLeft;
		
	
	if (rightedge < MessageObj.offsetWidth)
		left = scrollLeft + event.clientX - MessageObj.offsetWidth;
	else
		left = scrollLeft + event.clientX;
		
	if (bottomedge < MessageObj.offsetHeight)
		top = scrollTop + event.clientY - MessageObj.offsetHeight;
	else
		top = scrollTop + event.clientY;

		MessageObj.style.top = (top)+"px";
		MessageObj.style.left = (left)+"px";
		MessageObj.innerHTML = THConfig.Copyrights + '<div class="body"><img src="/images/loading.gif"> Loading...</div>';	
		MessageObj.style.visibility = "visible";
}

function deliveryMessage(text) {
	MessageObj.innerHTML = THConfig.Copyrights + '<div onclick="return calcClick();" class="body">'+text+'</div>';	
}

function showMessage(json) {
	var respondStructure = eval( '(' + json + ')' ); 
	deliveryMessage(respondStructure.content);
	if(THConfig.MemoryCache=="on") Cache[respondStructure.term] = respondStructure.content;
	return false;
}

var handleSuccess = function(o){
	if(o.responseText !== undefined){
		showMessage(o.responseText);
	}
};

var handleFailure = function(o){
	if(o.responseText !== undefined){
		showMessage("Connection Error");
	}
};

var callback =
{
  success:handleSuccess,
  failure:handleFailure,
  argument:['foo','bar']
};

function getDefinition(term,evt){
	adjustMessage(evt);	
	if(Cache[term]!=undefined) { return deliveryMessage(Cache[term]);  }
	var request = YAHOO.util.Connect.asyncRequest('POST', THConfig.CtrlURL, callback, 'call=getDataAndFitlering&term='+encodeURIComponent(term)+'&charset='+THConfig.Charset+'&casesensitive='+THConfig.CaseSensitive);
}


function stripSlashes(content) {
		// Strip Slashes
		re = /\\\"/gi;
		content = content.replace(re, '"');
		re = /\\\'/gi;
		content = content.replace(re, "'");
		return content;
}

var phandleSuccess = function(o){
	if(o.responseText !== undefined){
		var respondStructure = eval( '(' + o.responseText + ')' );
		SubstitutionTable = respondStructure.termlist;
		if(THConfig.parseElements.length>0) {
			// Elements to parse are defined
			for(var Inx in THConfig.parseElements) {		
				parseChildNodes($(THConfig.parseElements[Inx]));
				re = /\{th\}(.*?)\{\/th\}/gi;
				text_str = $(THConfig.parseElements[Inx]).innerHTML + '';
				$(THConfig.parseElements[Inx]).innerHTML = text_str.replace(re, "<a class=\"thesaurus\" onmouseover=\"getDefinition('$1', event);\" onmouseout=\"setTimer();\">$1</a>");
			}
		} else {
			// Otherwise parse whole BODY content
			BodyObj = document.getElementsByTagName("BODY");
			parseChildNodes(BodyObj[0]);
			re = /\{th\}(.*?)\{\/th\}/gi;
			text_str = BodyObj[0].innerHTML + '';
			BodyObj[0].innerHTML = text_str.replace(re, "<a class=\"thesaurus\" onmouseover=\"getDefinition('$1', event);\" onmouseout=\"setTimer();\">$1</a>");
		}
		
	}
};

var phandleFailure = function(o){ alert("It seems as the script can not connect to the server. Please, check if controller exists by URL "+THConfig.CtrlURL); };

var pcallback =
{
  success:phandleSuccess,
  failure:phandleFailure,
  argument:['foo','bar']
};

function parseContent(){
	var request = YAHOO.util.Connect.asyncRequest('POST', THConfig.CtrlURL, pcallback, 'charset='+THConfig.Charset+'&casesensitive='+THConfig.CaseSensitive+'&call=getDataAndParsing');
}

function calcClick(){
	if(THConfig.MemoryCache!="on") return true;
	for(var term in Cache) {}
	var request = YAHOO.util.Connect.asyncRequest('POST', THConfig.CtrlURL, pcallback, 'call=calcClick&casesensitive='+THConfig.CaseSensitive+'&term='+term);
	return true;
}

function parseText(obj) {
	var text_str = obj.nodeValue + '';
	if(text_str.length<2 || text_str=="null") return false;
	for(var i=0;i<SubstitutionTable.length;i++) {
		re = new RegExp(SubstitutionTable[i],(THConfig.CaseSensitive=="on"?"g":"gi")); 
		if(re.test(text_str)) {
			obj.nodeValue = applyTerm(SubstitutionTable[i], text_str);
			text_str = obj.nodeValue;
		}
	}
}

function applyTerm(term, text_str) {
	if(term+''==text_str+'') return "{th}"+text_str+"{/th}";
	re = new RegExp("^("+term+")([ \r\n\.!;,%\"'])",(THConfig.CaseSensitive=="on"?"g":"gi")); 
	text_str = text_str.replace(re, "{th}$1{/th}$2");
	re = new RegExp("([ \r\n\.!;,%\"'])("+term+")$",(THConfig.CaseSensitive=="on"?"g":"gi")); 
	text_str = text_str.replace(re, "$1{th}$2{/th}");
	re = new RegExp("([ \r\n\.!;,%\"'])("+term+")([ \r\n\.!;,%\"'])",(THConfig.CaseSensitive=="on"?"g":"gi")); 
	text_str = text_str.replace(re, "$1{th}$2{/th}$3");
	return text_str;
}

function parseChildNodes(obj) {
	for (var i=0; i<obj.childNodes.length; i++) {
		if(	obj.childNodes[i].childNodes.length>0 && 
			obj.childNodes[i].nodeName!="SCRIPT" && 
			obj.childNodes[i].nodeName!="A" && 
			obj.childNodes[i].nodeName!="H1" && 
			obj.childNodes[i].nodeName!="H2" && 
			obj.childNodes[i].nodeName!="H3" && 
			obj.childNodes[i].nodeName!="H4" && 
			obj.childNodes[i].id!="mainnav" && 
			obj.childNodes[i].id!="glossary" && 
			obj.childNodes[i].id!="frontmenu" && 
			obj.childNodes[i].id!="sidepod" && 
			obj.childNodes[i].id!="nogloss" && 
			obj.childNodes[i].id!="footer" && 
			obj.childNodes[i].id!="breadcrumbs")
				parseChildNodes( obj.childNodes[i] );
		else parseText( obj.childNodes[i] ) ;
	}
}