var MKPConfig = {
		CaseSensitive: "off",
		Charset: "UTF-8",
		CtrlURL: "http://www.mykeyphrase.com/script/mkp_controller.php",
		divName: 'divMKPScript',
		MemoryCache: 'on',
		parseElements: []
};
var MKPTimer = null;
var MKPCache = [];
var MKPSubstitutionTable = new Array();
var MKPScript = null;
var MKPDiv = document.createElement('DIV');
MKPDiv.id = MKPConfig.divName;
MKPDiv.className ='mkpScript';
MKPDiv.onmouseover = function(event){MKPclearTimer();};
MKPDiv.onmouseout = function(event){MKPsetTimer();};

// we disabled the javascript errors for avoiding document structure errors
// interfering with mkp script :P
function handleError() {
	return true;
}

window.onerror = handleError;
// until here error control


if(document.implementation && document.implementation.createDocument) var MKPisMozilla=true;
else var MKPisMozilla=false;

// Short name of function
function $(divName) {
	return document.getElementById(divName);
}

function MKPhideMessage(){
	var MessageObj=$(MKPConfig.divName);
	MessageObj.style.visibility="hidden";
}

function MKPclearTimer() {
 if (MKPTimer) {
   clearTimeout(MKPTimer);
   MKPTimer = null;
 }
}

function MKPsetTimer() {
 	MKPTimer = window.setTimeout('MKPhideMessage()', 250);
}

window.MKPSize = 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 MKPadjustMessage(evt) {
	var left;
	var top;
	MKPclearTimer();
	MessageObj = $(MKPConfig.divName);
	if (MKPisMozilla) event=evt;

	wsize = window.MKPSize();
	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 = '';
		MessageObj.style.visibility = "visible";
}
function MKPdeliveryMessage(respondStructure) {
	MessageObj.innerHTML = MKPdiv_content(respondStructure);
}

function MKPshowMessage(respondStructure) {
	MKPdeliveryMessage(respondStructure);
	if(MKPConfig.MemoryCache=="on") MKPCache[respondStructure.term] = respondStructure;
	return false;
}

var handleSuccess = function(respondStructure){
	if(respondStructure !== undefined){
		MKPshowMessage(respondStructure);
	}
};

function MKPgetDefinition(term,evt){
	MKPadjustMessage(evt);
	if(MKPCache[term]!=undefined) { return MKPdeliveryMessage(MKPCache[term]);  }
	MKPserverRequest(MKPConfig.CtrlURL, 'call=getDataAndFitlering&term='+encodeURIComponent(term)+'&charset='+MKPConfig.Charset+'&casesensitive='+MKPConfig.CaseSensitive+'&sourceurl='+MKPGetDocumentURL(true)+'&PubId='+MKPConfig.PubID, 'handleSuccess');
}

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

var MKPphandleSuccess = function(respondStructure){
	if(respondStructure !== undefined){
		MKPSubstitutionTable = respondStructure.termlist;
		if(MKPConfig.parseElements.length>0) {
			// Elements to parse are defined
			for(var Inx in MKPConfig.parseElements) {
				MKPparseChildNodes($(MKPConfig.parseElements[Inx]));
			}
		} else {
			// Otherwise parse whole BODY content
			MKPparseChildNodes(document.body);
		}
	}
};

function MKPparseContent(){
	document.body.appendChild(MKPDiv);
	MKPserverRequest(MKPConfig.CtrlURL, 'PubWpID='+MKPConfig.PubWpID+'&charset='+MKPConfig.Charset+'&casesensitive='+MKPConfig.CaseSensitive+'&call=getDataAndParsing', 'MKPphandleSuccess');
}

function MKPcalcClick(term){
	if(MKPConfig.MemoryCache!="on") return true;
	MKPserverRequest(MKPConfig.CtrlURL, 'call=MKPcalcClick&casesensitive='+MKPConfig.CaseSensitive+'&term='+term+'&sourceurl='+MKPGetDocumentURL(true)+'&PubId='+MKPConfig.PubID, 'MKPphandleSuccess');
	return true;
}

function MKPcalcImpression(term){
	if(MKPCache[term]!=undefined) { return MKPdeliveryMessage(MKPCache[term]);  }
	if(MKPConfig.MemoryCache!="on") return true;
	return true;
}

function MKPparseText(obj) {
	var text_str = obj.nodeValue + '';
	if(text_str.length<2 || text_str=="null") return false;
	for(var i=0;i<MKPSubstitutionTable.length;i++) {
		re = new RegExp("[ \r\n\.!;,%\"']?"+MKPSubstitutionTable[i]+"[ \r\n\.!;,%\"']?",(MKPConfig.CaseSensitive=="on"?"g":"gi"));
		if(re.test(text_str)) {
			MKPapplyTerm(MKPSubstitutionTable[i], text_str, obj);
			text_str = ''+obj.nodeValue+'';
		}
	}
}

function MKPReturnLink(term, innerHTML){
	var a = document.createElement('A');
	a.className = 'mkpUnderlined';
	a.href = 'javascript:void(0)';
	a.oncontextmenu = function (event){return false;};
	a.onmouseover = function (event){MKPgetDefinition(term, event); MKPcalcImpression(term);};
	a.onmouseout = function (event){MKPsetTimer();};
	a.onclick = function (event){return MKPcalcClick(term);};
	a.appendChild(document.createTextNode(innerHTML));
	return a;
}

function MKPapplyTerm(term, text_str, obj) {
	if(term+''==text_str+''){
		MKPReplaceTerm(obj, text_str, '', '');
		return;
	}

	var ct = 0;
	var suffix = text_str.replace(/\&\#39\;/gi, "'");

	var parent = obj.parentNode;
	obj.nodeValue = '';


	foundKeywords = new Array();
	var regex = new RegExp('\\b' + term.replace(/\+/g, '\\+') + '\\b', 'gim');
	var fnd = false;
	var matches, rpoint, lpoint;
	while(matches = regex.exec(suffix)) {
			rpoint = (typeof(matches.lastIndex) == 'undefined'
							? regex.lastIndex
							: matches.lastIndex
							);

			klen = matches[0].length;
			lpoint = rpoint - klen;

			var lchr = suffix.substring(lpoint - 1, lpoint);
			var rchr = suffix.substring(rpoint, rpoint + 1);

			fnd = !((lchr == '-') || (lchr == '.') || (rchr == '-'));

			if (fnd){
				lpoint += (text_str.length - suffix.length);
			}

			//adaug ce e inainte de cuvant
			if(lpoint > 0) parent.insertBefore(document.createTextNode(suffix.substring(0, lpoint)), obj)
			//adaug link
			parent.insertBefore(MKPReturnLink(term, suffix.substring(lpoint, rpoint)), obj)

			suffix = suffix.substring(rpoint);
			regex.lastIndex = 0;
	}
	if(suffix != '') parent.insertBefore(document.createTextNode(suffix), obj);
}

function MKPparseChildNodes(obj) {
	for (var i=0; i<obj.childNodes.length; i++){
		if(obj.childNodes[i].childNodes.length>0 &&
			obj.childNodes[i].nodeName!="IFRAME" &&
			obj.childNodes[i].nodeName!="STYLE" &&
			obj.childNodes[i].nodeName!="A" &&
			obj.childNodes[i].nodeName!="H1" &&
			obj.childNodes[i].nodeName!="H2" &&
			obj.childNodes[i].nodeName!="H3")
				MKPparseChildNodes(obj.childNodes[i]);
		else
			if(obj.childNodes[i].nodeName != "A" && obj.childNodes[i].nodeName != "SCRIPT" && obj.childNodes[i].nodeName != "OPTION" && obj.childNodes[i].nodeName != "TEXTAREA"
      && obj.childNodes[i].nodeName != "IFRAME" && obj.childNodes[i].nodeName != "OBJECT" && obj.childNodes[i].nodeName != "CODE" && obj.childNodes[i].nodeName != "CODE" && obj.childNodes[i].nodeName != "H1" && obj.childNodes[i].nodeName != "H2" && obj.childNodes[i].nodeName != "H3"
      && obj.childNodes[i].nodeName != "H4" && obj.childNodes[i].nodeName != "H5" && obj.childNodes[i].nodeName != "H6" && obj.childNodes[i].nodeName != "#comment")
			{
				MKPparseText(obj.childNodes[i]);
			}
	}
}

function MKPGetDocumentURL(urlencode){
	data = document.URL;
	return urlencode?escape(data):data;
}

function MKPserverRequest(url, data, callback) {
	var fUrl = url+'?'+data+'&callback='+callback;
	MKPScript = document.createElement('script');
	MKPScript.type = 'text/javascript';
	MKPScript.src = fUrl;
	MKPScript.id = 'scrMKPScript';
	document.body.appendChild(MKPScript);
}

function MKPexec_clicks(url, ad_kwo_id){
	window.open(url);
	MKPserverRequest(MKPConfig.CtrlURL, 'call=calcClick&ad_kwo_id='+encodeURIComponent(ad_kwo_id)+'&sourceurl='+MKPGetDocumentURL(true)+'&PubId='+MKPConfig.PubID, 'handleSuccess');
}

function MKPdiv_content(respondStructure){
	text='';
	if(respondStructure.ad_Type==1)//text only
		text = '<div id="mkpIm" class="mkpTxtIm"><div id="mkpBtn"><a href="javascript:void(0);" onclick="javascript:MKPhideMessage()" id="mkpBtnClose">&nbsp;</a><a href="http://www.mykeyphrase.com/" id="mkpBtnHelp" target="_blank">&nbsp;</a></div><div id="mkpTxtBox"><h1>'+respondStructure.ad_Title+'</h1>'+respondStructure.ad_Text+'</div><div id="mkpBtn"><a href="javascript:void(0);" onclick="javascript:MKPexec_clicks(\''+respondStructure.ad_Link+'\', '+respondStructure.ad_kwo_id+')" id="mkpBtnMerLink">'+respondStructure.ad_VisibleUrl+'</a><a href="javascript:void(0);" onclick="javascript:MKPexec_clicks(\''+respondStructure.ad_Link+'\', '+respondStructure.ad_kwo_id+')" id="mkpBtnRMLink">'+respondStructure.ad_butt_text+'</a></div></div>';


	if(respondStructure.ad_Type==2)//image + text
		text = '<div id="mkpIm" class="mkpImgIm"><div id="mkpBtn"><a href="javascript:void(0);" onclick="javascript:MKPhideMessage()" id="mkpBtnClose">&nbsp;</a><a href="http://www.mykeyphrase.com/" id="mkpBtnHelp" target="_blank">&nbsp;</a></div><div id="mkpImgBox"><h1>'+respondStructure.ad_Title+'</h1><div><img src="http://www.mykeyphrase.com/img/ad_imgs/'+respondStructure.ad_Image+'" alt="" /></div>'+respondStructure.ad_Text+'</div><div id="mkpBtn"><a href="javascript:void(0);" onclick="javascript:MKPexec_clicks(\''+respondStructure.ad_Link+'\', '+respondStructure.ad_kwo_id+')" id="mkpBtnMerLink">'+respondStructure.ad_VisibleUrl+'</a><a href="javascript:void(0);" onclick="javascript:MKPexec_clicks(\''+respondStructure.ad_Link+'\', '+respondStructure.ad_kwo_id+')" id="mkpBtnRMLink">'+respondStructure.ad_butt_text+'</a></div></div>';

	return text;
}