
var THConfig = { 
		CaseSensitive: "off", 
		Charset: "UTF-8",
		PubID: "1",
		Copyrights: '<div align="left" class="header"><a style="color:#ffffff;" href="http://Q2Click.com" target="_blank">Q2Click.com</a><div class="hr"></div></div>',		
		CtrlURL: "http://q2click.com/itxt/db_controller.php",
		divName: 'InstantMessage',
		MemoryCache: 'off',
		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 style="color:black;" class="body">Loading...</div>';	
		MessageObj.style.visibility = "visible";
}

function deliveryMessage(term, text) {
	MessageObj.innerHTML = THConfig.Copyrights+'<div onclick="return calcClick(\''+term+'\');" class="body">'+text+'</div>';	
}

function showMessage(respondStructure) {
	deliveryMessage(respondStructure.term, respondStructure.content);
	if(THConfig.MemoryCache=="on") Cache[respondStructure.term] = respondStructure.content;
	return false;
}

function handleSuccess(json){
	if(json.errormsg) alert('ERROR: '+json.errormsg);
	if(json) showMessage(json);
}
function empty(json) {
	return true;
}

function getDefinition(term,evt){
	adjustMessage(evt);	
	if(Cache[term]!=undefined) { return deliveryMessage(Cache[term]);  }
	serverRequest(THConfig.CtrlURL, 'call=getDataAndFitlering&term='+encodeURIComponent(term)+'&charset='+THConfig.Charset+'&casesensitive='+THConfig.CaseSensitive+"&pub_id="+THConfig.PubID+"&callback=handleSuccess");	
}

function stripSlashes(content) {
		// Strip Slashes
		re = /\\\"/gi;
		content = content.replace(re, '"');
		re = /\\\'/gi;
		content = content.replace(re, "'");
		return content;
}



function unique(a) {
	tmp = new Array(0);
	for(i=0;i<a.length;i++){
		if(!contains(tmp, a[i])){
			tmp.length+=1;
			tmp[tmp.length-1]=a[i];
		}
	}
	return tmp;
}


function contains(a, e) {
	for(j=0;j<a.length;j++)if(a[j]==e)return true;
	return false;
}



function parseContent(){

	//mytitle=document.title;
	//my_array=mytitle.split(" ");
	//title_keywords='&additional=';
	//for (t=0; t<my_array.length; t++) {
	//	if (my_array[t].length > 3) {

	//		ddd=my_array[t];
	//		ddd=ddd.replace(/,/, "");
	//		ddd=ddd.replace(/\?/, "");
	//		ddd=ddd.replace(/\./, "");
	//		ddd=ddd.replace(/!/, "");
	//		ddd=ddd.toLowerCase();
	//		title_keywords= title_keywords + ddd +'|';
	//	}
	//}

	//additionals=title_keywords.replace(/\|$/, "");
	//check_arr=additionals.split("|");

	//document.write(additionals);    
	//document.write("<br>");
	//if (check_arr.length > 0) {
	//serverRequest(THConfig.CtrlURL, 'charset='+THConfig.Charset+'&casesensitive='+THConfig.CaseSensitive+'&pub_id='+THConfig.PubID+'&call=getDataAndParsing&callback=phandleSuccess'+additionals);	
	//}
	//else {
	serverRequest(THConfig.CtrlURL, 'charset='+THConfig.Charset+'&casesensitive='+THConfig.CaseSensitive+'&pub_id='+THConfig.PubID+'&call=getDataAndParsing&callback=phandleSuccess');		
	//}
}

function calcClick(term){
	//if(THConfig.MemoryCache!="on") return true;
	// for(var term in Cache) {}
	serverRequest(THConfig.CtrlURL, 'call=calcClick&casesensitive='+THConfig.CaseSensitive+'&term='+term+'&pub_id='+THConfig.PubID+'&callback=empty');	
	return true;
}

// Parse page content functions

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);
			outside = SubstitutionTable.splice(i, 2); 
			text_str = obj.nodeValue;
		}
	}
}

function applyTerm(term, text_str) {

	if(!text_str) return text_str;
	if(!term) return text_str;
	re = /[ \r\n]/gi;
	if( !text_str.replace(re, "") ) return text_str;


	if(term+''==text_str+'') return "{th}"+text_str+"{/th}";
	re = new RegExp("^("+term+")([ \r\n\.!;,%\"'])",(THConfig.CaseSensitive=="on"?"i":"i")); 
	text_str = text_str.replace(re, "{th}$1{/th}$2");
	re = new RegExp("([ \r\n\.!;,%\"'])("+term+")$",(THConfig.CaseSensitive=="on"?"i":"i")); 
	text_str = text_str.replace(re, "$1{th}$2{/th}");
	re = new RegExp("([ \r\n\.!;,%\"'])("+term+")([ \r\n\.!;,%\"'])",(THConfig.CaseSensitive=="on"?"i":"i")); 
	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!="H3" && 
				obj.childNodes[i].nodeName!="H2" &&
				obj.childNodes[i].nodeName!="H1" &&
				obj.childNodes[i].nodeName!="script" &&
				obj.childNodes[i].nodeName!="form" &&
				obj.childNodes[i].nodeName!="FORM")
				parseChildNodes( obj.childNodes[i] );
				else parseText( obj.childNodes[i] ) ;

	}

}

// Controller respond handler

function phandleSuccess(respondStructure){
		if(respondStructure.errormsg) alert('ERROR: '+respondStructure.errormsg);
		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;
				var 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;
			var text_str = BodyObj[0].innerHTML + '';
			BodyObj[0].innerHTML = text_str.replace(re, "<a class=\"thesaurus\" onmouseover=\"getDefinition('$1', event);\" onmouseout=\"setTimer();\">$1</a>");
		}
}


// Psevdo AJAX section

function serverRequest(url, params) {
    aObj = new JSONscriptRequest(url+"?"+params);
    aObj.buildScriptTag();
    aObj.addScriptTag();
}

// Constructor -- pass a REST request URL to the constructor
//
function JSONscriptRequest(fullUrl) {
    // REST request path
    this.fullUrl = fullUrl; 
    // Keep IE from caching requests
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    // Get the DOM location to put the script tag
    this.headLoc = document.getElementsByTagName("head").item(0);
    // Generate a unique script tag id
    this.scriptId = 'YJscriptId' + JSONscriptRequest.scriptCounter++;
}

// Static script ID counter
JSONscriptRequest.scriptCounter = 1;

// buildScriptTag method
//
JSONscriptRequest.prototype.buildScriptTag = function () {

    // Create the script tag
    this.scriptObj = document.createElement("script");
    
    // Add script object attributes
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
    this.scriptObj.setAttribute("id", this.scriptId);
}
 
// removeScriptTag method
// 
JSONscriptRequest.prototype.removeScriptTag = function () {
    // Destroy the script tag
    this.headLoc.removeChild(this.scriptObj);  
}

// addScriptTag method
//
JSONscriptRequest.prototype.addScriptTag = function () {
    // Create the script tag
    this.headLoc.appendChild(this.scriptObj);
}

