var uid = "";
var antwoord = "";
var recnr = 0;
var html = "";
var category = 0;
//var matchLayer = 0;

var D = function (id)
{
	return document.getElementById(id);
};

et = {};
et.array = {};
et.array.contains = function (targetArray, value)
{
	for (var i = 0; i < targetArray.length; i++)
	{
		if (targetArray[i] === value)
		{
			return true;
		}
	}
	return false;
};
et.events = {};
et.events.keycodes = {
	TAB: 9,
	ENTER: 13,
	ESC: 27,
	LEFT: 37,
	UP: 38,
	RIGHT: 39,
	DOWN: 40
};
et.events.preventdefault = function (evt)
{
	if (evt.preventDefault)
		evt.preventDefault();
	else
		evt.returnValue = false;
}
et.events.addeventlistener = function (element, eventname, func, isbubbling)
{
	if (typeof attachEvent !== 'undefined')
	{
		element.attachEvent('on' + eventname, func);
	}
	else
	{
		element.addEventListener(eventname, func, isbubbling);
	}
}
et.events.removeeventlistener = function (element, eventname, func, isbubbling)
{
	if (typeof attachEvent !== 'undefined')
	{
		element.detachEvent('on' + eventname, func);
	}
	else
	{
		element.removeEventListener(eventname, func, isbubbling);
	}
}
et.controls = {};
et.controls.findancestor = function (element, ancestortype)
{
	while (element.parentNode.tagName.toLowerCase() !== ancestortype.toLowerCase())
	{
		element = element.parentNode;
	}
	return element;
}
et.controls.autocompletelist = function (targetField)
{
	this.targetField = targetField;
	var suggestionscontainer = null;
	var activesuggestion = null;
	var states = {
		opened: 1,
		closed: 2
	};
	var state = states.closed;

	var repositioncontainer = function ()
	{
		suggestionscontainer.style.position = 'absolute';
		show();

		//				targetField.style.position = 'fixed'; // TODO: check if it has a position already
		//				suggestionscontainer.style.left = targetField.offsetLeft + 'px';
		//				suggestionscontainer.style.top = targetField.offsetTop + targetField.offsetHeight + 2 + 'px';
		//				targetField.style.position = 'static'; // TODO: if it had position, reset it, if it was changed
	};

	var getinputparts = function ()
	{
		return targetField.value.split(' ');
	}

	this.callback = function (suggestions)
	{
		if (suggestions.length == 0)
		{
			hide();
			return;
		}
		var parts = getinputparts();
		var preinput = (function ()
		{
			var result = '';
			for (var i = 0; i < parts.length - 1; i++)
			{
				result += parts[i] + ' ';
			}
			return result;
		})();

		var currentinput = parts[parts.length - 1];

		var s = '';
		for (var i = 0; i < suggestions.length; i++)
		{
			var suggestion = suggestions[i];
			suggestion = '<span class="et_suggestion">' + suggestion.substring(currentinput.length) + '</span>';
			s += '<div onmouseover="window.et.obj.autocompletelist.hoversuggestion(this)" onclick="window.et.obj.autocompletelist.selectsuggestion(this)">'
						+ preinput + currentinput + suggestion + '</div>';
		}

		if (s.length > 0)
		{
			repositioncontainer();
		}
		suggestionscontainer.innerHTML = s;
	}

	var activatesuggestion = function (suggestion)
	{
		if (activesuggestion !== null)
			activesuggestion.className = '';

		activesuggestion = suggestion;
		activesuggestion.className = 'et_activesuggestion';
	}

	this.hoversuggestion = function (sender)
	{
		activatesuggestion(sender);
	}

	this.selectsuggestion = function (sender)
	{
		targetField.value = sender.innerHTML.replace(/\<\/?span[^>]*\>/gi, '');
		hide();
		targetField.focus();
	}

	var show = function ()
	{
		suggestionscontainer.style.display = 'block';
		state = states.opened;
	}

	var hide = function ()
	{
		activesuggestion = null;
		suggestionscontainer.innerHTML = '';
		suggestionscontainer.style.display = 'none';
		state = states.closed;
	}

	var initialize = function ()
	{
		//				et.events.addeventlistener(window, 'load', function ()
		//				{
		suggestionscontainer = document.createElement('div');
		suggestionscontainer.className = 'et_autocompletelist';
		suggestionscontainer.style.display = 'none';

		if (targetField.nextSibling !== null)
			targetField.nextSibling.insertBefore(suggestionscontainer);
		else
			targetField.parentNode.appendChild(suggestionscontainer);
		//					document.getElementsByTagName('body')[0].appendChild(suggestionscontainer);
		//				}, false);

		et.events.addeventlistener(targetField, 'blur', hide, false);

		et.events.addeventlistener(suggestionscontainer, 'mouseover', function ()
		{
			et.events.removeeventlistener(targetField, 'blur', hide);
		}, false);

		et.events.addeventlistener(suggestionscontainer, 'mouseout', function (e)
		{
			if (!e) var e = window.event;
			var t = (window.event) ? e.toElement : e.relatedTarget;

			while (typeof t !== 'undefined' && t !== null && t.className !== 'et_autocompletelist' && t.tagName.toLowerCase() !== 'body')
			{
				t = t.parentNode;
				if (typeof t !== 'undefined' && t !== null && t.className === 'et_autocompletelist')
					return;
			}

			et.events.addeventlistener(targetField, 'blur', hide, false);

		}, false);

		et.events.addeventlistener(targetField, 'keyup', function (e)
		{
			if (!(function ()
			{
				var ignoredkeycodes = [
							et.events.keycodes.UP,
							et.events.keycodes.DOWN,
							et.events.keycodes.LEFT,
							et.events.keycodes.RIGHT,
							et.events.keycodes.TAB,
							et.events.keycodes.ESC,
							et.events.keycodes.ENTER
						];

				var conditions = [
							function () { return !et.array.contains(ignoredkeycodes, e.keyCode); },
							function ()
							{
								if (targetField.value === null ||
								targetField.value === '' ||
								targetField.value.substring(targetField.value.length - 1) === ' ')
								{
									hide();
									return false;
								};
								return true;
							}
						];

				for (var i = 0; i < conditions.length; i++)
				{
					if (!conditions[i]())
					{
						return false;
					}
				}

				return true;
			})()) return;

			if (/[a-z0-9]/gi.test(targetField.value.split(' ')[targetField.value.split(' ').length - 1]))
			{
				activesuggestion = null;
				var s = document.createElement('script');
				s.setAttribute('type', 'text/javascript');
				et.obj
				var languages = {
					NL: 1,
					UK: 2,
					DE: 3,
					FR: 4,
					ES: 5
				};
				s.src = 'http://projecten.elitech.nl/et3/autocomplete/autocomplete.ashx?input=' +
							encodeURIComponent(targetField.value.split(' ')[targetField.value.split(' ').length - 1]) +
							'&langcode=' + languages[et.obj.local.current.langcode] +
							'&callback=et.obj.autocompletelist.callback';
				document.getElementsByTagName('head')[0].appendChild(s);
			}
		});

		et.events.addeventlistener(targetField, 'keydown', function (e)
		{
			if (e.keyCode === et.events.keycodes.UP)
			{
				et.events.preventdefault(e);

				if (activesuggestion === null)
				{
					activesuggestion = suggestionscontainer.firstChild;
				}
				else
				{
					activesuggestion.className = '';

					if (activesuggestion.previousSibling)
						activesuggestion = activesuggestion.previousSibling;
				}

				if (activesuggestion)
					activesuggestion.className = 'et_activesuggestion';

				return;
			}
			else if (e.keyCode === et.events.keycodes.DOWN)
			{
				if (activesuggestion === null)
				{
					activesuggestion = suggestionscontainer.firstChild;
				}
				else
				{
					activesuggestion.className = '';

					if (activesuggestion.nextSibling)
						activesuggestion = activesuggestion.nextSibling;
				}

				if (activesuggestion)
					activesuggestion.className = 'et_activesuggestion';

				return;
			}
			else if (e.keyCode === et.events.keycodes.TAB || e.keyCode === et.events.keycodes.ENTER)
			{
				if (activesuggestion)
				{
					et.events.preventdefault(e);

					targetField.value = activesuggestion.innerHTML.replace(/\<\/?span[^>]*\>/gi, '');
				}
				hide();
				return;
			}
			else if (e.keyCode === et.events.keycodes.ESC)
			{
				hide();
			}
		}, false);
	} ();
}
et.obj = {};
et.obj.local = {
	current: function ()
	{
		if (window.location.href.indexOf('selfservicecompany.fr') > -1 || window.location.href.indexOf('selfservicecompany.com/fr') > -1)
		{
			return {
				customercode: 'TSCS_fr',
				langcode: 'FR',
				agentonlinemsg: 'Peut-&ecirc;tre un de mes coll&egrave;gues peut vous aider. Engagez-vous dans une ' +
					'<a href="https://backchat.lime-com.net/selfservicecompany/default.aspx?UID=[UID]" target="_blank">session de chat</a> ' +
					'avec un de mes coll&egrave;gues.',
				moreinfo: 'En savoir plus',
				loadinganimation: '/img/Sophie_loadinganimation_fr.gif',
				placeholder: unescape('Veuillez me poser une question courte et pr%E9cise.'),
				btnaskquestionon: '/img/demandez_on.gif',
				btnquestionoff: '/img/demandez_off.gif',
				btnquestionalt: 'Posez votre question'
			};
		}
		else if (window.location.href.indexOf('selfservicecompany.com') > -1 || window.location.href.indexOf('selfservicecompany.co.uk') > -1)
		{
			return {
				customercode: 'TSCS_uk',
				langcode: 'UK',
				agentonlinemsg: 'Perhaps one of my colleagues can be of further assistance. ' +
					'<a href="https://backchat.lime-com.net/selfservicecompany/default.aspx?UID=[UID]" target="_blank">Start a chat session</a> ' +
					'with one of my colleagues.',
				moreinfo: 'More information',
				loadinganimation: '/img/Sophie_loadinganimation_uk.gif',
				placeholder: 'Please ask me a clear and concise question.',
				btnaskquestionon: '/img/askquestion_on.gif',
				btnquestionoff: '/img/askquestion_off.gif',
				btnquestionalt: 'Ask question'
			};
		}
		else if (window.location.href.indexOf('selfservicecompany.de') > -1)
		{
			return {
				customercode: 'TSCS_de',
				langcode: 'DE',
				agentonlinemsg: 'Vielleicht kann einer meiner Kollegen Ihnen weiterhelfen. ' +
					'<a href="https://backchat.lime-com.net/selfservicecompany/default.aspx?UID=[UID]" target="_blank">Start einen Chat</a> ' +
					'mit einem Kollegen.',
				moreinfo: 'Wietere Informationen',
				loadinganimation: '/img/Sophie_loadinganimation_de.gif',
				placeholder: 'Bitte stellen Sie mir Ihre Frage...',
				btnaskquestionon: '/img/fragestellen_on.gif',
				btnquestionoff: '/img/fragestellen_off.gif',
				btnquestionalt: 'Frage stellen'
			};
		}
		else
		{
			return {
				customercode: 'TSCS_nl',
				langcode: 'NL',
				agentonlinemsg: 'Wellicht kan &#233,&#233,n van mijn collega\'s u verder helpen. <a href:"https://backchat.lime-com.net/selfservicecompany/default.aspx?UID:[UID]" target:"_blank">Start een chatsessie</a> met een van mijn collega\'s.',
				moreinfo: 'Meer info',
				loadinganimation: '/img/Sophie_loadinganimation.gif',
				placeholder: 'Stel uw vraag kort en bondig.',
				btnaskquestionon: '/img/stelvraag_on.gif',
				btnquestionoff: '/img/stelvraag_off.gif',
				btnquestionalt: 'Stel vraag'
			};
		}
	} ()
};

var elitechAise = function ()
{
	this.klantcode = et.obj.local.current.customercode;    /* Probeer hier een unieke afkorting te gebruiken voor een klant */
	this.subject = "VA";
	this.state = 1;           /* default status */
	this.frame1 = "";          /* default waarde frame 1 */
	this.frame2 = "";          /* default waarde frame 2 */
	this.frame3 = "";          /* default waarde frame 3 */
	this.useIframeIEfix = false;       /* in IE liggen selectboxen en flash etc. altijd met de hoogste z-index. als deze optie op true wordt gezet, wordt achter de divs een iframe geplaatst. Dit iframe kan wel over deze controls heen worden gelegd. */
	this.loadingHTML = "... ...";    /* Tekst wordt getoond tijdens het laden */
	this.showDivSources = false;       /* voor debug/design true zetten */
	this.doPagePush = true;        /* aanzetten pagepush optie. Handig om uit te zetten tijdens ontwikkelfase */
	this.beoordeling = 0;            /* beoordeling goed is de defaultwaarde */
	this.handigeVragen = false;        /* maak gebruik van handige vragen */
	this.toonvraag = true;        /* De vraag herhalen in aise responsediv */
	this.pagepushiframe = false;       /* De pagepush uitvoeren naar een achtergrond frame (in geval van demo|testen) */
	this.RecNr1 = 'leeg';
	this.RecNr2 = 'leeg';
	this.RecNr3 = 'leeg';
	this.DoorverwijzingContact = true;
	this.lastReceived_uid = "";
	this.lastReceived_antwoord = "";
	this.lastReceived_recnr = 0;
	this.lastReceived_html = "";
	this.lastReceived_category = 0;
	this.lastReceived_character = '';
	this.lastQuestion = "";
	this.StandaardTekst = "";
	this.reloadFromStorage = "1";
	this.defaultvraag = new Array();
	this.callback = "me.putXMLhere();";
	this.oScript = "";
	this.welcomeQuestion = "custom_welcome";
	var me = this;

	this.convertTo = function ()
	{
		me.lastReceived_antwoord = me.lastReceived_antwoord.replace(/&#/gi, "SPECIAL_SIGN");
		me.lastReceived_antwoord = me.lastReceived_antwoord.replace(/;/gi, "PUNT_KOMMA");
	};

	this.convertFrom = function (value)
	{
		value = value.replace(/SPECIAL_SIGN/gi, "&#");
		value = value.replace(/PUNT_KOMMA/gi, ";");
		return value;
	};

	this.storeAllData = function ()
	{
		me.convertTo();
		var aise = D('et_status1div');
		top.window.name = "AISE -!-" + me.klantcode + ";" + me.subject + ";" + aise.style.top + ";" + aise.style.left + ";" + me.state + ";" + me.lastReceived_uid + ";" + me.lastReceived_character + ";" + me.reloadFromStorage + ";" + me.lastQuestion + ";" + me.lastReceived_antwoord;
	};

	this.repositionFromStorage = function ()
	{
		var aise = D('et_status1div');
		var wname = top.window.name.split("-!-");
		if (wname[1])
		{
			if (wname[0].indexOf("AISELINK") > -1)
			{
				D('et_question').value = wname[1].split(";")[0];
				this.email = wname[1].split(";")[1];
				D('et_aiseResponseDiv').innerHTML = '...';
				window.setTimeout("aise.sendQuestionDirect()", 250);
			}
			else
			{
				var storage = wname[1].split(";");
				if (storage[0] == this.klantcode && storage[7] == "1") // && storage[1] == this.subject)
				{
					aise.style.top = storage[2]; //0
					aise.style.left = storage[3]; //1
					this.state = storage[4]; //2
					this.lastReceived_uid = storage[5];
					this.lastReceived_character = this.convertFrom(storage[6]);
					this.lastQuestion = this.convertFrom(storage[8]);
					this.lastReceived_antwoord = this.convertFrom(storage[9]);

					if (this.toonvraag)
					{
						try
						{
							D('et_question').value = "";
						} catch (e) { }
						D('et_aiseResponseDiv').innerHTML = "<strong>" + this.lastQuestion + "</strong><span class='et_ruimtegesteldevraag'><br /></span>" + "" + this.lastReceived_antwoord + "";
					}
					else
					{
						try
						{
							D('et_question').value = this.lastQuestion;
						} catch (e2) { }
						D('et_aiseResponseDiv').innerHTML = this.lastReceived_antwoord;
					}
				}
			}
		} else
		{
			aise.style.top = this.defaultFromtop;
			aise.style.left = this.defaultFromLeft;
			this.sendQuestionInit();
		}
		//		et.perf.log('end reposition', et.obj.stopwatch.reset());
		return true;
	};

	this.changeState = function ()
	{
		if (this.state == 1)
		{
			D('et_status1div').style.display = 'block';
			D('et_status2div').style.display = 'none';
			D('et_status3div').style.display = 'none';
			if (this.useIframeIEfix)
			{
				D('et_status1frame').style.display = 'block';
				D('et_status2frame').style.display = 'none';
				D('et_status3frame').style.display = 'none';
			}
		}
		if (this.state == 2)
		{
			D('et_status1div').style.display = 'block';
			D('et_status2div').style.display = 'none';
			D('et_status3div').style.display = 'none';
			if (this.useIframeIEfix)
			{
				D('et_status1frame').style.display = 'block';
				D('et_status2frame').style.display = 'none';
				D('et_status3frame').style.display = 'none';
			}
			if (D('et_aiseResponseDiv').innerHTML == '')
			{
				this.sendQuestionInit();
				return;
			}
			D('et_question').focus();
		}
		if (this.state == 3)
		{
			D('et_status1div').style.display = 'block';
			D('et_status2div').style.display = 'block';
			D('et_status3div').style.display = 'block'; // TONEN VOOR TEST_DIALOOG wordt dan display='';   verbergen =>  display='none';
			if (this.useIframeIEfix)
			{
				D('et_status1frame').style.display = 'block';
				D('et_status2frame').style.display = 'block';
				D('et_status3frame').style.display = 'block';
			}
		}
	};

	this.changeStateFromTopDiv = function ()
	{
		if ((this.state == 2) || (this.state == 3))
		{
			this.state = 1;
		} else
		{
			this.state = 2;
		}
		this.changeState();
	};

	this.parse = function ()
	{
		document.write('<link rel="stylesheet" type="text/css" href="' + this.css + '">');
		if (this.showDivSources)
		{
			document.write('<textarea style="font-family: Verdana; font-size:11px;width:100%;height:33%">' + this.frame1 + "</textarea>");
			document.write('<textarea style="font-family: Verdana; font-size:11px;width:100%;height:33%">' + this.frame2 + "</textarea>");
			document.write('<textarea style="font-family: Verdana; font-size:11px;width:100%;height:33%">' + this.frame3 + "</textarea>");
		}
		document.write(this.frame1);
		document.write(this.frame2);
		document.write(this.frame3);

		try
		{
			if (DetectFlashVer(9, 0, 0))
			{
				D('sophieImage').parentNode.innerHTML = '<div style="margin:-30px 0 0 -30px">' + AC_FL_RunContent('codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0', 'width', '300', 'height', '300', 'id', 'et_face', 'src', videourl + '/va_player', 'quality', 'high', 'pluginspage', 'http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash', 'movie', videourl + '/va_player', 'wmode', 'transparent', 'allowScriptAccess', 'always', 'allowNetWorking', 'all'); +"</div>";
			}
		}
		catch (ex) { }

		if (!isGeldigeIE()) { this.useIframeIEfix = false; }
		if (this.useIframeIEfix)
		{
			var status1div = D('et_status1div');
			document.write("<iframe name='et_status1frame' id='et_status1frame' frameborder='0' style='moz-opacity:.5;filter:alpha(opacity=0);display:none;z-index:900;position:absolute;' width='" + status1div.style.width + "' height='" + status1div.style.height + "'></iframe>");
		}
		//		et.perf.log('add onload handler', et.obj.stopwatch.reset());
		et.events.addeventlistener(window, 'load', function ()
		{
			et.obj.autocompletelist = new et.controls.autocompletelist(document.getElementById('et_question'));
		}, false);
		window.onload = this.positionAiseOnLoadHandler; // Na het laden aise initialiseren
		window.onunload = this.storeAllData;              // Opslaan positie, vraag en antwoord
	};

	this.checkFaqQuestion = function ()
	{
		var currentFaq = decodeURI(GetFaqFromReferrer());

		if (currentFaq != '' && currentFaq != 'undefined')
		{
			D("et_question").value = currentFaq;
			D('et_aiseResponseDiv').innerHTML = this.loadingHTML;
			this.getDataFromServer("ScriptTagID", this.proxyServer, currentFaq);
		}
	}

	this.positionAiseOnLoadHandler = function ()
	{
		if (me.repositionFromStorage())
		{
			me.checkFaqQuestion();

			if (me.handigeVragen) { me.setDefaultVragen(); }
		}
	};

	this.setDefaultVragen = function ()
	{
		var faqDiv = D('faq');
		faqDiv.innerHTML = "";
		for (var loop = 0; loop < this.defaultvraag.length; loop++)
		{
			faqDiv.innerHTML = faqDiv.innerHTML + "<a href='#' onClick=\"" + this.instanceName + ".vraagHandigeVraag('" + this.defaultvraag[loop] + "')\">" + this.defaultvraag[loop] + '</a><br />';
		}
	};

	this.vraagHandigeVraag = function (vraag)
	{
		D('et_question').value = vraag;
		this.sendQuestion();
	};

	this.verwerkHandigeVragen = function (hvragen)
	{
		var faqDiv = D('faq');
		faqDiv.innerHTML = "";
		for (var loop = 0; loop < hvragen.length; loop++)
		{
			faqDiv.innerHTML = faqDiv.innerHTML + "<a href='#' onClick=\"" + this.instanceName + ".vraagHandigeVraag('" + hvragen[loop] + "')\">" + hvragen[loop] + '</a><br />';
		}
		if (hvragen.length === 0)
		{
			for (var loop = 0; loop < this.defaultvraag.length; loop++)
			{
				faqDiv.innerHTML = faqDiv.innerHTML + "<a href='#' onClick=\"" + this.instanceName + ".vraagHandigeVraag('" + this.defaultvraag[loop] + "')\">" + this.defaultvraag[loop] + '</a><br />';
			}
		}
	};

	this.getDataFromServer = function (id, url, vraag)
	{
		//		et.obj.stopwatch.reset();
		//		et.perf.log('enter getDataFromServer', et.obj.stopwatch.reset());
		if (vraag == this.StandaardTekst)
		{
			vraag = "";
		}

		this.oScript = D(id);
		var head = document.getElementsByTagName("head").item(0);
		if (this.oScript)
		{
			head.removeChild(this.oScript);
		}
		var referrer = "";
		if (document.referrer.indexOf(".google.") > -1)
		{
			referrer = document.referrer;
		}

		this.oScript = document.createElement("script");
		var callURL = url +
			'?projectCode=' + this.projectCode +
			'&projectID=' + this.projectID +
			'&uid=' + this.lastReceived_uid +
			'&vraag=' + escape(vraag) +
			'&referrerPage=' + escape(referrer) +
			'&langCode=' + et.obj.local.current.langcode;

		if (typeof this.email != "undefined" && this.email != null)
		{
			callURL += "&email=" + this.email;
		}

		this.oScript.setAttribute("src", callURL);

		head.appendChild(this.oScript);

		//		if (isGeldigeIE())
		//		{
		//			if (this.oScript.readyState == "loaded")
		//			{
		//				eval(this.callback);
		//				this.oScript.onreadystatechange = null;
		//			} else
		//			{
		//				this.oScript.onreadystatechange = this.CheckAgain;
		//			}
		//		} else
		//		{
		//			aise.mozCheckAgain();
		//		}
	};

	//	this.mozCheckAgain = function ()
	//	{
	//		if (typeof (antwoord) == "string")
	//		{
	//			if (antwoord == "")
	//			{
	//				window.setTimeout("aise.mozCheckAgain()", 250);
	//			} else
	//			{
	//				aise.putXMLhere();
	//			}
	//		} else
	//		{
	//			window.setTimeout("aise.mozCheckAgain()", 250);
	//		}
	//	};

	//	this.CheckAgain = function ()
	//	{
	//		if (me.oScript.readyState == "loaded")
	//		{
	//			eval(me.callback);
	//			me.oScript.onreadystatechange = null;
	//		}
	//	};

	this.getChatStatus = function (id, url, app)
	{
		this.oScriptChat = D(id);
		var head = document.getElementsByTagName("head").item(0);
		if (this.oScriptChat)
		{
			head.removeChild(this.oScriptChat);
		}
		this.oScriptChat = document.createElement("script");
		var callURL = url + '?app=' + app;
		this.oScriptChat.setAttribute("src", callURL);
		this.oScriptChat.setAttribute("id", "chatcheckscript");
		head.appendChild(this.oScriptChat);

		if (isGeldigeIE())
		{
			if (this.oScriptChat.readyState == "loaded")
			{
				this.oScriptChat.onreadystatechange = null;
				eval("me.checkChatStatus();");
			} else
			{
				this.oScriptChat.onreadystatechange = this.CheckAgainChat;
			}
		} else
		{
			aise.mozCheckAgainChat();
		}
	};

	this.checkChatStatus = function ()
	{
		if (aiseAgentIsOnline == "false")
		{
		} else
		{
			antwoord = antwoord + "<br />" + et.obj.local.current.agentonlinemsg.replace('[UID]', this.lastReceived_uid);
		}
		this.lastReceived_antwoord = antwoord;
		this.putXMLherePart2();
	};

	this.mozCheckAgainChat = function ()
	{
		if (typeof (aiseAgentIsOnline) == "string")
		{
			if (aiseAgentIsOnline == "")
			{
				window.setTimeout("aise.mozCheckAgainChat()", 1000);
			} else
			{
				aise.checkChatStatus();
			}
		} else
		{
			window.setTimeout("aise.mozCheckAgainChat()", 1000);
		}
	};

	this.CheckAgainChat = function ()
	{
		if (me.oScriptChat.readyState == "loaded")
		{
			eval("me.checkChatStatus();");
			me.oScriptChat.onreadystatechange = null;
		}
	};

	var custom_welcome_ask = false;
	this.sendQuestion = function ()
	{
		D('et_aiseResponseDiv').innerHTML = this.loadingHTML;
		custom_welcome_ask = false;
		this.getDataFromServer("ScriptTagID", this.proxyServer, RemoveXSS(D('et_question').value));
	};

	this.sendQuestionDirect = function (vraag)
	{
		if (typeof vraag == "undefined" || vraag == null)
		{
			vraag = D("et_question").value;
		}

		D('et_aiseResponseDiv').innerHTML = this.loadingHTML;
		custom_welcome_ask = false;
		this.getDataFromServer("ScriptTagID", this.proxyServer, RemoveXSS(vraag));
	};

	this.sendQuestionInit = function ()
	{
		var referrerquestion = decodeURI(GetGoogleQuestionFromReferrer());
		if (referrerquestion != "")
		{
			this.welcomeQuestion = referrerquestion;
			D("et_question").value = this.welcomeQuestion;
		}

		//		var currentFaq = decodeURI(GetFaqFromReferrer());
		//		
		//		if(currentFaq != "")
		//		{
		//			this.welcomeQuestion = currentFaq;
		//			D("et_question").value = this.welcomeQuestion;	
		//		}

		D('et_aiseResponseDiv').innerHTML = this.loadingHTML;
		custom_welcome_ask = true;
		this.getDataFromServer("ScriptTagID", this.proxyServer, this.welcomeQuestion);
	};

	this.putXMLhere = function ()
	{
		//		et.perf.log('enter putxmlhere', et.obj.stopwatch.reset());
		this.lastReceived_uid = uid;
		this.lastReceived_antwoord = antwoord;
		this.lastReceived_recnr = recnr;
		this.lastReceived_html = html;
		this.lastReceived_category = category;
		this.lastReceived_character = character;
		this.lastQuestion = RemoveXSS(D('et_question').value);

		try
		{
			var etface = document.getElementById('et_face');
			if (etface && etface.changeemotion)
				etface.changeemotion(character);
		}
		catch (ex) { }

		if (this.RecNr1 == 'leeg')
		{         // nog geen vraag gesteld
			this.RecNr1 = recnr;
		} else if (this.RecNr2 == 'leeg')
		{  // pas 1 vraag gesteld
			this.RecNr2 = recnr;
		} else
		{                             //alles gevuld; dus meer dan 2 vragen gesteld
			this.RecNr1 = this.RecNr2;
			this.RecNr2 = recnr;
		}
		if (this.DoorverwijzingContact)
		{
			if (((this.RecNr1 != 'leeg' && this.RecNr2 != 'leeg') && ((isNaN(Number(this.RecNr1)) ? Number("1") : Number(this.RecNr1)) <= 0 && (isNaN(Number(this.RecNr2)) ? Number("1") : Number(this.RecNr2)) <= 0)))
			{
				this.lastReceived_html = html;
				this.lastReceived_antwoord = antwoord;
				this.getChatStatus("ScriptTagIDChat", this.proxychatServer, "ssc");
				return;
			}
		}

		this.putXMLherePart2();
	};

	this.putXMLherePart2 = function ()
	{
		this.lastQuestion = RemoveXSS(this.lastQuestion);

		if (this.toonvraag && this.lastQuestion !== this.StandaardTekst)
		{
			D('et_aiseResponseDiv').innerHTML = "<strong>" + this.lastQuestion + "</strong><span class='et_ruimtegesteldevraag'><br /></span>" + "" + antwoord + "";
		} else
		{
			D('et_aiseResponseDiv').innerHTML = antwoord;
		}
		//		et.perf.log('answer shown', et.obj.stopwatch.reset());
		//		et.perf.createsetid();

		// check matchlayer or kbaid= 0 --> push2call addition
		/*if (this.lastQuestion !== this.StandaardTekst && this.lastQuestion !== "custom_welcome" && (matchLayer >= 6 || recnr === 0)) {
		matchLayerCount++;
		}
		else {
		matchLayerCount = 0;
		}
		if (matchLayerCount >= 2 && typeof (pcscom) != "undefined" && typeof (pcscom.toggleMenu) != "undefined") {
		D('et_aiseResponseDiv').innerHTML += "<br />Wilt u dat wij u terugbellen? klik <a href='javascript:void();' onclick='pcscom.toggleMenu();'>hier</a>";
		}*/

		if (this.handigeVragen)
		{
			this.verwerkHandigeVragen(hvragen);
		}
		if (html != "")
		{
			if (this.doPagePush)
			{
				if (this.pagepushiframe)
				{
					if (D("frame"))
					{
						D("frame").src = html;
					}
				} else
				{
					document.location.href = html;
				}
			} else
			{
				D('et_aiseResponseDiv').innerHTML += '<br /><br /><a href=' + html + '>' + et.obj.local.current.moreinfo + '</a>';
			}
		}

		if (!custom_welcome_ask)
		{
			if (this.testing)
			{
				this.state = 3;
			} else
			{
				this.state = 2;
			}
		}
		this.changeState();
		if (this.state > 1)
		{
			if (this.toonvraag)
			{
				if (this.lastQuestion !== 'Stel uw vraag kort en bondig.' && this.lastQuestion !== 'custom_welcome')
				{
					D('et_question').value = '';
					D('et_question').focus();
				}
			} else
			{
				D('et_question').focus();
				D('et_question').select();
			}
		}
		antwoord = ""; // Leegmaken ivm firefox wait <- Deze controlleerd of antwoord gezet is.
	};

	this.SendOpmerking = function ()
	{
		var rsIframe = D("RSIFrameOpmerking");
		var tmpant = this.lastReceived_antwoord; tmpant = tmpant.replace(/\'/g, "`"); tmpant = tmpant.replace(/\&\#/g, "|"); tmpant = tmpant.replace(/\&/g, " en ");
		var tmphtm = this.lastReceived_html; tmphtm = tmphtm.replace(/\'/g, "`");
		var tmpque = this.lastQuestion; tmpque = tmpque.replace(/\'/g, "`"); tmpque = tmpque.replace(/\&\#/g, "|"); tmpque = tmpque.replace(/\&/g, " en ");
		var tmpopm = D("et_invoerOpmerking").value; tmpopm = tmpopm.replace(/\'/g, "`"); tmpopm = tmpopm.replace(/\&/g, " en ");

		var url = this.opmerkingUrl + '?uid=' + this.lastReceived_uid + '&vraag=' + tmpque + '&antwoord=' + tmpant + '&commentaar=' + tmpopm +
            '&score=' + this.beoordeling + '&rec=' + this.lastReceived_recnr + '&cat=' + this.lastReceived_category + '&pro=' + this.projectID;

		if (rsIframe == null)
		{
			var iframe = document.createElement("iframe");
			iframe.setAttribute("src", url);
			iframe.setAttribute("id", "RSIFrameOpmerking");
			iframe.setAttribute("scrolling", "no");
			iframe.setAttribute("frameBorder", "5");
			iframe.setAttribute("width", "0");
			iframe.setAttribute("height", "0");
			document.body.appendChild(iframe);
		} else
		{
			rsIframe.src = url;
		}
		D('et_divInvoerOpmerking').style.display = 'none';
		D('et_opmerkingtitel').style.display = 'none';
		this.state = 2;
		this.changeState();
		document.getElementsByName('beoordeling')[0].checked = false;
		document.getElementsByName('beoordeling')[1].checked = false;
		document.getElementsByName('beoordeling')[2].checked = false;
		D('et_invoerOpmerking').value = "";
	};

	this.changeBeoordeling = function (newValue)
	{
		this.beoordeling = newValue;
		if (this.beoordeling == '0')
		{
			D('et_divInvoerOpmerking').style.display = 'none';
			D('et_opmerkingtitel').style.display = 'none';
		} else
		{
			D('et_divInvoerOpmerking').style.display = '';
			D('et_opmerkingtitel').style.display = '';
			if (newValue == 1)
			{
				D('et_opmerkingtitel').innerHTML = 'Voeg hier het antwoord voor deze vraag toe:';
			}
			if (newValue == 2)
			{
				D('et_opmerkingtitel').innerHTML = 'Verduidelijk de fout in het antwoord:';
			}
		}
	};
};

var serverPath = "http://projecten.elitech.nl/TSCS";
var basicurl = serverPath + '/js';
var videourl = serverPath + '/video'

var aise = new elitechAise();
aise.projectID = 48; //39;   /* AISE projectID in de database*/
aise.instanceName = 'aise';     /* deze variabele niet veranderen */
aise.defaultFromtop = "0px";    /* startwaarde top van aise */
aise.defaultFromLeft = "0px";    /*307 startwaarde left van aise */
aise.defaultvraag[0] = "FAQ";
aise.defaultvraag[1] = "FAQ";
aise.handigeVragen = false;  	  /* Maak gebruik van handige vragen */
aise.state = 2;     	  /* initiële status op klein blokje. */
aise.doPagePush = true; 	     /* indien false verschijnt onder het antwoord een link naar de page push pagina */
aise.proxyServer = basicurl + "/proxy.asp";
aise.proxychatServer = basicurl + "/proxychat.asp";
aise.css = basicurl + "/sophie.css";
aise.opmerkingUrl = serverPath + "/receiveopmerkingen.aspx";
aise.loadingHTML = '<div id="et_preloadposition"><img src="' + basicurl + et.obj.local.current.loadinganimation + '" border="0" /></div>'; //<p>Ik typ een antwoord...</p> <img src=' + basicurl + '/img/Sophie_loadinganimation.gif' border='0' />";
aise.showDivSources = false;      /* Debug only => laat content van de divs in textarea's zien. Handig tijdens opmaak van div's */
aise.useIframeIEfix = false;  	  /* aan uitzetten IE fix => wel of geen achterliggende iframes bij de divs. Div kan anders niet over selectboxen en flash heen liggen. */
aise.testing = false;      /* Wel of niet weergeven van de beoordelingsdiv na het krijgen van een antwoord; als niet aan, dan dus geen status3div */
aise.pagepushiframe = false;
aise.toonvraag = true;
aise.StandaardTekst = et.obj.local.current.placeholder; //Gebruik voor het beste resultaat een korte vraag.


aise.frame1 += '<div id="et_status1div" class="et_status1" style="display:block;">';
aise.frame1 += '	<div id="et_aiseResponseDiv"></div>';
aise.frame1 += '	<div id="et_totinput">';
aise.frame1 += '		<div id="et_bginput"><input type="text" id="et_question" name="et_question" size="22" value="' + aise.StandaardTekst + '" class="et_tekstinput_start" onClick="javascript:doTextClick()" onFocus="javascript:doTextClick()" onBlur="javascript:undoTextClick()" onKeyPress="return checkEnter(event);" /></div>';
aise.frame1 += '		<div id="et_btnquestion"><a href="javascript:void(0);" onMouseOver="javascript:swap(&#34;btnquestion&#34;,&#34;btnquestionon&#34;);" onMouseOut="javascript:swap(&#34;btnquestion&#34;,&#34;btnquestionoff&#34;);" onClick="aise.sendQuestion()"><img name="btnquestion" src="' + basicurl + et.obj.local.current.btnquestionoff + '" border="0" alt="' + et.obj.local.current.btnquestionalt + '" title="' + et.obj.local.current.btnquestionalt + '" /></a></div>';
aise.frame1 += '	</div>';
aise.frame1 += '</div>';

aise.frame2 += '<div id="et_status2div" class="et_status2" style="display:none;">';
aise.frame2 += '</div>';

aise.frame3 += '<div id="et_status3div"  class="et_status3" style="display:none;">';
aise.frame3 += '	<div class="et_beoordeling">Geef hier per vraag aan wat u van het antwoord van Sophie vindt: <br /><br />';
aise.frame3 += '		<input type="radio" name="beoordeling" id="beoordelingGoed" value="Goed" onClick="aise.changeBeoordeling(0);aise.SendOpmerking();" />De vraag is goed beantwoord.<br />';
aise.frame3 += '		<input type="radio" name="beoordeling" id="beoordelingVerkeerdHerkend" value="Verkeerd herkend" onClick="aise.changeBeoordeling(1)" />De vraag wordt niet goed herkend.<br />';
aise.frame3 += '		<input type="radio" name="beoordeling" id="beoordelingFout" value="Fout" onClick="aise.changeBeoordeling(2)" />Het antwoord is inhoudelijk niet goed.<br /><br />';
aise.frame3 += '		<div id="et_divInvoerOpmerking" style="display:none;">';
aise.frame3 += '				<div id="et_opmerkingtitel"></div>';
aise.frame3 += '				<textarea id="et_invoerOpmerking" name="invoer" cols="20" rows="4" value=""></textarea><br /><br />';
aise.frame3 += '				<button class="et_button" onClick="aise.SendOpmerking();">Opmerking opslaan</button><br /><br />';
aise.frame3 += '		</div>';
aise.frame3 += '	</div>';
aise.frame3 += '</div>';

//et.perf.createsetid();
//et.obj.stopwatch = new et.stopwatch();
//et.perf.log('start parse', et.obj.stopwatch.reset());
aise.parse(); /* Start aise */

/**********************************************************************/
/************** zie ook aise.frame1/2/3 variabelen ********************/
/**********************************************************************/
function isIE50()
{
	return isIE5() && !isIE55();
}
function isIExplore()
{
	return navigator.userAgent.indexOf("MSIE") > -1;
}
function isIE55()
{
	return navigator.userAgent.indexOf("MSIE 5.5") > -1;
}
function isIE5()
{
	return navigator.userAgent.indexOf("MSIE 5") > -1;
}
function isIE6()
{
	return navigator.userAgent.indexOf("MSIE 6") > -1 && navigator.userAgent.indexOf("Opera") == -1;
}
function isIE7()
{
	return navigator.userAgent.indexOf("MSIE 7") > -1;
}
function isGeldigeIE()
{
	return isIE55() || isIE6() || isIE7();
}

function checkEnter(e)
{
	/*versturen van de vraag indien op enter toets wordt gedrukt*/
	var key;

	D('et_question').className = "et_tekstinput";

	if (window.event)
	{
		key = window.event.keyCode; //IE
	} else
	{
		key = e.which;              //firefox
	}
	if (key == 13)
	{
		aise.sendQuestion();
		return false;
	}
	else
	{
		if (D('et_question').value.toString().toLowerCase() == aise.StandaardTekst.toLowerCase())
		{
			D('et_question').value = "";
			D('et_question').focus();
		}
	}
}
function move_up()
{
	/* omhoog scrollen in de Faq div */
	D('faq').scrollTop = D('faq').scrollTop - 15;
}
function move_down()
{
	/* omlaag scrollen in de Faq div */
	D('faq').scrollTop = D('faq').scrollTop + 15;
}

btnquestionon = new Image(); btnquestionon.src = basicurl + et.obj.local.current.btnaskquestionon;
btnquestionoff = new Image(); btnquestionoff.src = basicurl + et.obj.local.current.btnquestionoff;

function swap()
{
	if (document.images)
	{
		for (var x = 0; x < swap.arguments.length; x += 2)
		{
			document[swap.arguments[x]].src = eval(swap.arguments[x + 1] + ".src");
		}
	}
}

function doTextClick()
{
	if (D('et_question').value.toString().toLowerCase() == aise.StandaardTekst.toLowerCase())
	{
		D('et_question').value = "";
		D('et_question').focus();
	}
	else
	{
		D('et_question').select();
	}
}

function undoTextClick()
{
	if (D('et_question').value.toString().replace(" ", "") == "")
	{
		D('et_question').value = aise.StandaardTekst;
	}
}
function RemoveXSS(str)
{
	str = str.replace(/>/gi, " ").replace(/</gi, " ");          // '<' en '>'.
	str = str.replace(/%3e/gi, " ").replace(/%3c/gi, " ");      // url-encodering '<' en '>'.
	str = str.replace(/&#60;/gi, " ").replace(/&#62;/gi, " ");  // html-encodering '<' en '>'.
	str = str.replace(/javascript\:/gi, " ");                   // javascript-startstring.
	str = str.replace(/document\.\S/g, " ");                    // document-startstring.
	return str;
}

// This function gets the referrer string and parses it for a question/search.
// The question/search is denoted by a 'q=' in the URI.
// Each word in the question/search is seperated by a '+' plus.
// Google uses this syntax for searches.
// If there is no matching q=, an empty string is returned and nothing happens.
function GetGoogleQuestionFromReferrer()
{
	if (document.referrer.indexOf("?q=") < 0 && document.referrer.indexOf("&q=") < 0)
	{
		return '';
	}

	// Get the start location of the question
	var startIndex = document.referrer.indexOf("?q=");
	if (startIndex < 0)
	{
		startIndex = document.referrer.indexOf("&q=");
	}

	var endIndex = 0;
	var question = "";
	//Check if really from google
	if (document.referrer.indexOf(".google.") >= 0)
	{
		// Get the end location
		endIndex = document.referrer.indexOf("&", startIndex + 1);
		if (endIndex < 0)
		{
			endIndex = document.referrer.length;
		}
		if (endIndex > startIndex)
		{
			question = document.referrer.substr(startIndex + 3, endIndex - startIndex - 3);
		}
		return question.replace(/\+/g, " "); // remove the '+' pluses from the string - google adds these in place of spaces for their search
	}
	else
	{
		return "";
	}
}

function GetFaqFromReferrer()
{
	if (document.referrer.indexOf('FaqHandler.ashx?Q=') > -1)
	{
		var idx = document.referrer.indexOf('?Q=');

		if (idx > -1)
		{
			return document.referrer.substr(idx + 3, document.referrer.length - (idx - 3));
		}
	}
	return '';
}
