///------------------------------------------------------------------------------
/// $Revision$
/// $LastChangedBy$
/// $LastChangedDate$
/// $Copyright: © 2010 TRES internet BV, Online Quality since 1998 $
///------------------------------------------------------------------------------ 

// AJAX
function ajax(){
	this.http_request	= false;
	this.makeRequest	= makeRequest;
	this.getResponseText	= getResponseText;
	this.getReadyState	= getReadyState;
	this.ready			= true;

	function makeRequest(url, onready_function, postvariablen) {
		this.http_request	= false;
		this.ready			= false;
		if (window.XMLHttpRequest) { // Mozilla, Safari,...
			this.http_request = new XMLHttpRequest();
			if (this.http_request.overrideMimeType) {
				this.http_request.overrideMimeType('text/xml');
			}
		} else if (window.ActiveXObject) { // IE
			try {
				//this.http_request = new ActiveXObject("Msxml2.XMLHTTP.5.0");
				this.http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				try {
				this.http_request = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {}
			}
		}
		if (!this.http_request) {
			// ERROR: 
			alert('Giving up1 :( Cannot open the XMLHTTP instance');
		}
		try{
			this.http_request.onreadystatechange = onready_function;
			if(!postvariablen){postvariablen='';}
			if(postvariablen.length>0){
				this.http_request.open('POST', url, true);
				this.http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
				this.http_request.setRequestHeader("Content-length", postvariablen.length);
			}else{
				this.http_request.open('GET', url, true);
			}
		} catch(e) {
			// ERROR: 
			alert('Giving up2 :( Cannot open the XMLHTTP instance');
			return false;
		}
		this.http_request.send( postvariablen );
	}

	function getReadyState()
	{
		return this.http_request.readyState; 
	}

	function getResponseText()
	{
		return this.http_request.responseText;
	}
}

function CreateDelegate(aInstance, aMethod)
{
	return function()
	{
		return aMethod.apply(aInstance, arguments);
	}	
}

AjaxTextArea = function ()
{
	this._Ctrl = false;
}

AjaxTextArea.prototype = 
{
	_Saved : function()
	{
		if (this._Ajax != null)
		{
			if (this._Ajax.getReadyState() == 4)
			{
				var resultText = this._Ajax.getResponseText();
				this._Ajax = null;
				if (resultText != 'OK') 
				{
					alert(resultText);
				} 
				setTimeout('AjaxTextAreaHideProgress(\'' + this._LoaderID + '\')', 1000);
			}
		}
	},
	_Save : function()
	{
		if (this._Ajax == null)
		{	
			document.getElementById(this._LoaderID).style.visibility='visible';
			var textarea = document.getElementById(this._ID);
			this._Ajax = new ajax();
			this._Ajax.makeRequest(this._TargetUrl, CreateDelegate(this, this._Saved) , this._TargetParams + encodeURIComponent(textarea.value));
		}
	},
	_OnKey : function(aE)
	{
		aE = (aE) ? aE : window.event;
		aE.cancelBubble = true;
		var keyNr = (aE.which) ? aE.which : aE.keyCode;
		if (aE.type == 'keydown')
		{
			if (keyNr==9) // tab
			{
				var rng = document.selection.createRange();
				if (rng)
				{
					rng.text ='\t';
				}
				return false;
			}
			else if (keyNr==17) // ctrl
			{ 
				this._Ctrl = true;
			}
			else if (keyNr==83 && this._Ctrl==true) // ctrl-s
			{
				this._Save();	
				return false;
			}
		}
		else if (aE.type == 'keyup')
		{
			if(keyNr==17) //ctrl
			{
				this._Ctrl = false;
			}
		}
	},
	_OnBlur :function(aE)
	{
		aE = (aE) ? aE : window.event;
		this._Ctrl = false;
	},
	Initialize : function(aTextAreaID, aLoaderID, aTargetUrl, aTargetParams)
	{
		this._ID = aTextAreaID;
		this._LoaderID = aLoaderID;
		this._TargetUrl = aTargetUrl;
		this._TargetParams = aTargetParams;

		var textArea = document.getElementById(this._ID);
		if (textArea != null)
		{
			textArea.onkeydown = CreateDelegate(this, this._OnKey);
			textArea.onkeyup = CreateDelegate(this, this._OnKey);
			textArea.onblur = CreateDelegate(this, this._OnBlur);
		}
	}
}

function AjaxTextAreaHideProgress(aID)
{
	document.getElementById(aID).style.visibility='hidden';
}
function AjaxTextAreaHideProgress(aID)
{
	document.getElementById(aID).style.visibility='hidden';
}

TextBoxManager = function(aPasteDivID)
{
	this._LastSelected = null;
	this._PasteDivID = aPasteDivID;
	var pasteDiv = this.get_PasteDiv();
	pasteDiv.contentEditable = true;
	pasteDiv.style.cssText = 'position:absolute;overflow:hidden;height:0px;width:0px';
}

TextBoxManager.prototype =
{
	_IsValidAction : function(aRange, aDivID)
	{
		var check = aRange.parentElement();
		while(check != null) 
		{
			if (check.tagName == 'DIV')
			{
				return check.id == aDivID;
			}
			check = check.parentNode;
		}
		return false;
	},
	CreateTextBox : function(aHiddenFieldID, aContent, aWidth)
	{
		var divTb = new DivTextBox(this);
		divTb.Initialize(aHiddenFieldID, aContent, aWidth, 16, false);
		return divTb;
	},
	CreateMultilineTextBox : function(aHiddenFieldID, aContent, aWidth, aHeight)
	{
		var divTb = new DivTextBox(this);
		divTb.Initialize(aHiddenFieldID, aContent, aWidth, aHeight, true);
		return divTb;
	},
	FontStyle : function(aStyle)
	{
		if (this._LastSelected != null)
		{
			if (document.selection) 
			{
				var divTb = this._LastSelected.get_TextBox();
				divTb.focus();

				var range = document.selection.createRange();
				if (this._IsValidAction(range, divTb.id))
				{
					var commandName = 'Bold';
					switch(aStyle)
					{
						case 'i':
							commandName = 'Italic';
							break;
						case 'u':
							commandName = 'Underline';
							break;
					}
					if (range.queryCommandEnabled(commandName))
					{
						range.execCommand(commandName, false, null);
					}
					this._LastSelected.UpdateHiddenField();
				}
			}
		}
	},
	SetLink : function(aDropDown)
	{
		if (this._LastSelected != null)
		{
			if (document.selection)
			{
				var divTb = this._LastSelected.get_TextBox();
				divTb.focus();

				var range = document.selection.createRange();
				if (this._IsValidAction(range, divTb.id))
				{
					if (aDropDown.value == '00')
					{
						range.execCommand('Unlink', false, null);
					}
					else
					{
						var selectedText = range.text;
						if (selectedText.length == 0)
						{
							alert('Selecteer de tekst waar u de link op wilt zetten.');
						}
						range.pasteHTML('<a href="TRESLink" code="' + aDropDown.value + '">' + selectedText + '</a>');
					}
				}
				this._LastSelected.UpdateHiddenField();
			}
		}	
		aDropDown.selectedIndex = 0;
		aDropDown.blur();
	},
	GetClipboardData : function(aAllowMultiline)
	{
		var pasteDiv = this.get_PasteDiv();
		pasteDiv.focus();
		pasteDiv.innerHTML = '';
		document.execCommand('paste', false, null);
		var clipboardData = new String(pasteDiv.innerText);
		clipboardData = clipboardData.replace(/</g, '&lt;');
		clipboardData = clipboardData.replace(/>/g, '&gt;');
		if (!aAllowMultiline)
		{
			clipboardData = clipboardData.replace(/\n/g, '<br>');
		}
		else
		{
			clipboardData = clipboardData.replace(/\n/g, ' ');
		}
		clipboardData = clipboardData.replace(/\r/g, '');
		return clipboardData;
	},
	FindTextBox : function(aNode)
	{
		for(var i=0; i < aNode.childNodes.length; i++)
		{
			var ret = null;
			if (aNode.childNodes[i].control != null)
			{
				ret = aNode.childNodes[i].control;
			}
			else
			{
				ret = this.FindTextBox(aNode.childNodes[i]);
			}
			if (ret != null)
			{
				return ret;
			}
		}
		return null;
	},
	get_PasteDiv : function()
	{
		return document.getElementById(this._PasteDivID);
	},
	get_LastSelected : function()
	{
		return this._LastSelected;
	},
	set_LastSelected : function(aValue)
	{
		this._LastSelected = aValue;
	}
}

DivTextBox = function(aManager)
{
	this._Manager = aManager
	this._ID = null;
	this._HfID = null;
	this._AllowMultiline = false;
}

DivTextBox.prototype =
{
	_OnKeyUp : function()
	{
		this.UpdateHiddenField();
	},
	_OnKeyDown : function(aEvent)
	{
		aEvent = aEvent ? aEvent : window.event;
		if (aEvent.keyCode == 13)
		{
			if (this._AllowMultiline)
			{
				var range = document.selection.createRange();		
				range.pasteHTML('<br>');
				range.select();
			}
			aEvent.returnValue = false;
			return false;
		} 
	},
	_OnBlur : function()
	{
		this._Manager.set_LastSelected(this);
		this.UpdateHiddenField();
	},
	_OnPaste : function(aEvent)
	{
		aEvent = aEvent ? aEvent : window.event;
		this.get_TextBox().focus();
		var range = null;
		if (document.selection) 
		{
			range = document.selection.createRange();
		}
		var clipboardData = this._Manager.GetClipboardData(this._AllowMultiline);
		if (range != null)
		{
			range.pasteHTML(clipboardData);
			range.select();
		}
		else
		{
			this.get_TextBox().pasteHTML(clipboardData);
		}
		aEvent.returnValue = false;
		return false;
	},
	Initialize : function(aHiddenFieldID, aContent, aWidth, aHeight, aAllowMultiline)
	{
		this._HfID = aHiddenFieldID;
		this._ID = aHiddenFieldID + '_div';
		this._AllowMultiline = aAllowMultiline;

		var hf = this.get_HiddenField();
		if (hf != null)
		{
			var newDiv = document.createElement('div');
			newDiv.id = this._ID;
			newDiv.control = this;
			newDiv.innerHTML = aContent;
			newDiv.contentEditable = true;
			var overflow = this._AllowMultiline ? 'overflow-x:auto' : 'overflow:hidden';
			newDiv.style.cssText = 'padding:1px;border:1px solid #b2b2b2;width:' + aWidth + 'px;height:' + aHeight + 'px;' + overflow + ';white-space: nowrap;cursor:text;background-color:#fefefe;';
			hf.parentNode.insertBefore(newDiv, hf);

			this.UpdateHiddenField();
			newDiv.onkeyup = CreateDelegate(this, this._OnKeyUp);
			newDiv.onkeydown = CreateDelegate(this, this._OnKeyDown);
			newDiv.onblur = CreateDelegate(this, this._OnBlur);
			newDiv.onfocus = CreateDelegate(this, this.Select);
			newDiv.onpaste = CreateDelegate(this, this._OnPaste);
		}
	},
	UpdateHiddenField : function()
	{
		var tb = this.get_TextBox();
		var hf = this.get_HiddenField();
		if (hf != null && tb != null)
		{
			hf.value = tb.innerHTML;
		}
	},
	FindParentNode : function(aTagName)
	{
		aTagName = aTagName.toUpperCase();
		var node = this.get_TextBox().parentNode;
		while (node != null)
		{
			if (node.tagName == aTagName)
			{
				return node;
			}
			node = node.parentNode;
		}
		return null;
	},
	Select : function()
	{
		this._Manager.set_LastSelected(this);
	},
	get_TextBox : function()
	{
		return document.getElementById(this._ID);
	},
	get_HiddenField : function()
	{
		return document.getElementById(this._HfID);
	},
	get_Value : function()
	{
		return this.get_TextBox().innerHTML;
	},
	set_Value : function(aValue)
	{
		this.get_TextBox().innerHTML = aValue;
		this.UpdateHiddenField();
	}
}

function CTextHint(aKeyword, aDescription, aIndex)
{
	this.Keyword = aKeyword;
	this.Description = aDescription;
	this.Index = aIndex;
}

var gTextHintList = null;
var gTextDescription = null;
var gHintTimer = null;
var gCurrentHint = null;
var gAjaxObj = null;

function ShowHint()
{
	var textHint = gTextHintList[gCurrentHint.hintIndex];
	gTextDescription.style.display = 'block';
	gTextDescription.innerHTML = textHint.Description;
	gCurrentHint.nextSibling.appendChild(gTextDescription);
}

function HideHint()
{
	gTextDescription.style.display = 'none';
}

function HintOver()
{
	if (gTextDescription.style.display == 'none')
	{
		gCurrentHint = this;
		gHintTimer = setTimeout('ShowHint()', 500);
	}
	else
	{
		clearTimeout(gHintTimer);
	}
}

function HintOut()
{
	if (gTextDescription.style.display == 'none')
	{
		clearTimeout(gHintTimer);
	}
	else
	{
		gCurrentHint = this;
		gHintTimer = setTimeout('HideHint()', 100);	
	}
}

function ReplaceText(aNode, aTextHintList)
{
	if (aNode)
	{
		if (aNode.nodeType == 3) // TEXT_NODE
		{
			if (aNode.parentNode != null) 
			{
				var nodeValue = aNode.nodeValue;
				if (nodeValue.match('\\b'))
				{
					for(var i=0; i<aTextHintList.length - 1; i++) // -1 because we add a bogus item!
					{
						var regExp = new RegExp('(.*)(\\b' + aTextHintList[i].Keyword + '\\b)(.*)', 'im');
						var matches = nodeValue.match(regExp);
						if (matches != null && matches.length == 4)
						{
							var containerNode = document.createElement('span');
							containerNode.appendChild(document.createTextNode(matches[1]));

							var hintNode = document.createElement('span');
							hintNode.hintIndex = aTextHintList[i].Index;
							hintNode.className = 'texthintKeyword';
							hintNode.innerHTML = matches[2];
							hintNode.onmouseover = HintOver;
							hintNode.onmouseout = HintOut;
							containerNode.appendChild(hintNode);

							var hintContainer = document.createElement('span');
							hintContainer.style.position = 'relative';
							containerNode.appendChild(hintContainer);

							containerNode.appendChild(document.createTextNode(matches[3]));
					
							aNode.parentNode.replaceChild(containerNode, aNode);
							aTextHintList.splice(i, 1);

							// also replace text in pre-post text
							ReplaceText(containerNode.childNodes[0], aTextHintList);
							ReplaceText(containerNode.childNodes[3], aTextHintList);
							break;
						}
					}
				}
			}
		}
		else
		{
			if (aNode.hasChildNodes() && aNode.tagName != 'SCRIPT' && aNode.tagName != 'OBJECT')
			{
				for(var i=0; i<aNode.childNodes.length; i++)
				{
					ReplaceText(aNode.childNodes[i], aTextHintList);
				}
			}
		}
	}
}

function ArrayReceived()
{
	if (typeof(gAjaxObj) != 'undefined')
	{
		if (gAjaxObj.http_request.readyState == 4)
		{
			gTextHintList = eval(gAjaxObj.getResponseText());
			if (gTextHintList.length > 1)
			{
				var contentSpan = document.getElementById('spanContent');
				gTextDescription = document.createElement('div');
				gTextDescription.className = 'texthintDescription';
				gTextDescription.style.position = 'absolute';
				gTextDescription.style.display = 'none';
				contentSpan.appendChild(gTextDescription);
				var textHintList = gTextHintList.slice();
				ReplaceText(contentSpan, textHintList);
			}
		}
	}
}

function GetText(aNode, aTextArray)
{
	if (aNode)
	{
		if (aNode.nodeType == 3 && aNode.parentNode != null) // TEXT_NODE
		{
			if (aNode.parentNode != null) 
			{
				if (aNode.nodeValue.match('\\b'))
				{
					aTextArray[aTextArray.length] = aNode.nodeValue;
				}
			}
		}
		else
		{
			if (aNode.hasChildNodes() && aNode.tagName != 'SCRIPT' && aNode.tagName != 'OBJECT')
			{
				for(var i=0; i<aNode.childNodes.length; i++)
				{
					GetText(aNode.childNodes[i], aTextArray);	
				}
			}
		}
	}
}

function SetTextHints()
{
	var contentSpan = document.getElementById('spanContent');
	if (contentSpan != null)
	{
		var textArray = new Array();
		GetText(contentSpan, textArray);	
		gAjaxObj = new ajax();
		gAjaxObj.makeRequest('/includes/modules/woordhint/getarray.asp', ArrayReceived, 'data=' + escape(textArray.join()));
	}
}

function StartTextHints()
{
	setTimeout('SetTextHints()', 3000);
}

function addLoadEvent(func) 
{
	var oldonload = window.onload;
	if (typeof window.onload != 'function')
	{
		window.onload = func;
	} 
	else
	{
   	window.onload = function()
		{
			if (oldonload) 
			{
				oldonload();
			}
			func();
		}
	}
}

addLoadEvent(StartTextHints);
