var EditMode = {
	Html: 1,
	Ubb: 2
};

$.fn.htmlbox = function()
{
	if (undefined === window.glob_ha) {
		glob_ha = [];
	}
	var d = {
		buttons: [],
		rows: [],
		images: [],
		toolbar: '',
		dir: "./images/",
		output: "xhtml",
		success: function(data){
			alert(data);
		},
		error: function(a, b, c){
			this;
		}
	};

	this.smilies = [];
	this.imgRoot = '';
	this.currentToolbar = '';
	this.getToolbarSpace = getToolbarSpace;
	this.setupToolbarButton = setupToolbarButton;
	this.mode = EditMode.Html;
	this.language = 'nl';
	this.smileyMode = '';
	this.presetContents = '';
	this.presetAttempts = 0;
	
	var checkedState = new Array();
	var checkingEnabled = new Array();

	if (!$(this).attr("id")) {
		$(this).attr("id", "jqha_" + glob_ha.length);
		d.id = "jqha_" + glob_ha.length;
		glob_ha[glob_ha] = glob_ha;
	}
	else {
		d.id = $(this).attr("id");
	}
	if (undefined === glob_ha[d.id]) {
		glob_ha[d.id] = this;
	}

	this.getContents = function() {
		var iframe = document.getElementById("hb_html");
 
		return d.iframe.contentWindow.document.body.innerHTML;
	}
	this.setContents = function(contents)
	{
		if (this.mode == EditMode.Html)
		{
			var elBody;
			var iframe = document.getElementById("hb_html");
			if (iframe.contentWindow.document.body == undefined)
			{
				elBody = document.createElement('body');
				elBody.innerHTML = contents;
				iframe.contentWindow.document.appendChild(elBody);	
			}
			else
			{
				elBody = iframe.contentWindow.document.body;
			}
			elBody.innerHTML = contents;
		}
		else
		{
			document.getElementById('hb_source').value = contents;
		}
	}

	this.enable = function(flag)
	{
		//
		$('#tblToolbar').css('height', flag ? '200px' : '30px');
		$('#hb_html').css('display', flag ? '' : 'none').parent().parent().css('display', flag ? '' : 'none');
		
		if (!flag)
		{
			var smileybar = document.getElementById('divSmileybar');
			if (smileybar)
			{
				smileybar.style.display = 'none';
			}
		}
	}

	this.imgroot = function(imgRoot){
		this.imgRoot = imgRoot;
		
		return this;
	};
	
	this.editmode = function(mode)
	{
		this.mode = mode;
		return this;
	};
	
	this.contents = function(text)
	{
		this.presetContents = text;
		return this;
	};
	
	this.init = function(is_init){
		// START: Timeout to allow creation of DesignMode
		if (undefined === is_init) {
			setTimeout("glob_ha['" + d.id + "'].init(true)", 250);
			return false;
		}
		// END: Timeout to allow creation of DesignMode
		
		var w = $(this).css("width");
		var h = $(this).css("height");
		$(this).wrap("<table width='" + w + "' style='height:" + h + "; border:1px solid #E9EAEF; border-collapse: collapse; padding: 0; margin: 0;' id='tblToolbar'><tr><td style='padding: 0; margin: 0;'></td></tr></table>");
		
		// START: Appending toolbar
		d.toolbar = toolbar(this.imgRoot);
		
		$(this).parent().parent().parent().parent().prepend(d.toolbar);
		$("." + d.id + "_tb").css("background-image", "url('" + this.imgRoot + "images/bg_silver.jpg')").css("height", "30px");

		$("." + d.id + "_tb").find("button").each(function(index, element)
		{
			var elementId = element.getAttribute('id');

			$(this).css("border", "1px solid #E9EAEF").css("background", "transparent").css("margin", "1px 1px 1px 1px").css("padding", "1px");

			$(this).mouseover(function()
			{
				$(this).css("border", "1px solid #BFCAFF").css("background", "#EFF2FF");
			});
			
			$(this).mouseout(function()
			{
				if (checkedState[elementId])
				{
					$(this).css("border", "1px solid #BFCAFF").css("background", "#f2f2f2");
				}
				else
				{
					$(this).css("border", "1px solid #E9EAEF").css("background", "transparent");
				}
			});
			
			$(this).mousedown(function()
			{
				if (checkingEnabled[elementId])
				{
					if (checkedState[elementId])
					{
						checkedState[elementId] = false;
					}
					else
					{
						checkedState[elementId] = true;
					}
				}
			});
		});
		
		$("." + d.id + "_tb").find("select").each(function()
		{
			$(this).css("border", "1px solid #E9EAEF").css("background", "transparent").css("margin", "2px 2px 3px 2px");
		
			if ($.browser.mozilla)
			{
				$(this).css("padding", "0").css("position", "relative").css("top", "-2px");
			}
		});
		// END: Appending toolbar
		
		//try
		//{
			var iframe = document.createElement("IFRAME");
			var doc = null;
			$(iframe).attr("frameborder", "0").attr("width", w).css("height", h).attr("id", d.id + "_html").attr("border", "0").css("border", "1px solid #cccccc").css("background-color", "#ffffff").css("padding", "0");
			$(this).parent().prepend(iframe);
			d.iframe = iframe;
			if ($.browser.msie === false) {
				iframe.contentWindow.document.body.contentEditable = true;
			}
			iframe.contentWindow.document.designMode = "on";
			iframe.contentWindow.document.execCommand("undo", false, null);
			var text = ($(this).val() === "") ? "" : $(this).val();
			if ($.browser.mozilla) {
				if (text === "") {
					text = "";
				}
				iframe.contentWindow.document.open('text/html', 'replace');
				iframe.contentWindow.document.write(text);
				iframe.contentWindow.document.close();
			}
			else {
				if (text !== "") {
					iframe.contentWindow.document.write(text);
				}
			}

			
			
			// START: Adding events
			if (iframe.contentWindow.document.attachEvent)
			{
				// IE
				iframe.contentWindow.document.attachEvent("onkeyup", function(){
					var html = ($("#1" + d.id).is(":visible")) ? $("#" + d.id).val() : html = d.iframe.contentWindow.document.body.innerHTML;
					html = (typeof getXHTML === 'function') ? getXHTML(html) : html;
					$("#" + d.id).val(html);
				});
			}
			else
			{
				// FireFox
				iframe.contentWindow.document.addEventListener("keyup", function(){
					var html = ($("#1" + d.id).is(":visible")) ? $("#" + d.id).val() : html = d.iframe.contentWindow.document.body.innerHTML;
					html = (typeof getXHTML === 'function') ? getXHTML(html) : html;
					$("#" + d.id).val(html);
				}, false);

				d.iframe.contentWindow.document.execCommand("useCSS",false,"false");
				d.iframe.contentWindow.document.execCommand("styleWithCSS","",false);
				d.iframe.contentWindow.document.execCommand("enableInlineTableEditing",false,"false");
				d.iframe.contentWindow.document.execCommand("enableObjectResizing",false,"false");
			}
			/* FF-Security exception
			 $(this).keyup(function(){
			 var html = $("#"+d.id).val();
			 if($.browser.mozilla){ if(html==""||html==" ")html="&nbsp;";
			 d.iframe.contentWindow.document.open('text/html', 'replace');
			 d.iframe.contentWindow.document.write(html);
			 d.iframe.contentWindow.document.close();
			 }else{
			 d.iframe.contentWindow.document.body.innerText="";
			 if(html!="")d.iframe.contentWindow.document.write(html);
			 }
			 });
			 */
			// END: Adding events
			
			// Create smiley list
			this.createSmileyList();

			$(this).hide();
		//}
		//catch (e) {
		//	alert("This rich text component is not supported by your browser.");
		//	$(this).show();
		//}
		
		if (navigator.appName == "Microsoft Internet Explorer" && this.language == 'en')
		{
			var cssStr = "p { margin: 0; padding: 0; }";
			var style = document.createElement("style");
			style.setAttribute("type", "text/css");
			if(style.styleSheet)
			{
				// IE
				style.styleSheet.cssText = cssStr;
			}
			//iframe.contentWindow.document.appendChild(style);
		}
		
		//
		addListener(d.iframe.contentWindow.document, 'click', editArea_Clicked);
		addListener(d.iframe.contentWindow.document, 'keyup', editArea_KeyPressed);		
		
		// Setup edit mode
		if (this.mode == EditMode.Ubb)
		{
			$('#hb_html').css('display', 'none');
			$('#hb_source').css('display', '');
			$('#tblToolbar').css('height', 0);
		}
		else
		{
			$('#hb_html').css('display', '');
			$('#hb_source').css('display', 'none');
			$('#tblToolbar').css('height', 200);
		}
		this.setEditMode(this.mode);
		
		// Set preset contents
		setTimeout(function() {
						if (iframe.contentWindow.document.body == undefined)
						{
							// Check if we reached the max attempt count
							glob_ha[d.id].presetAttempts++;
							if (glob_ha[d.id].presetAttempts > 10)
							{
								return;
							}
							
							// Just loop it
							setTimeout(this, 100);
						}
						else
						{						
							// Ok, now we're able to set the contents
							glob_ha[d.id].setContents(glob_ha[d.id].presetContents);
						}
					}, 100);
		
		// Call event
		if (document.OnHtmlBoxInitialized)
		{
			document.OnHtmlBoxInitialized(this);
		}
		
		return $(this);
	};

	this.smileytype = function(type)
	{	
		this.smileyMode = type;
		
		return this;
	};
	
	/**
	 * Occurs when the user clicks somewhere in the editor's contents.
	 * @param Onclick parameters.
	 */
	editArea_Clicked = function(e)
	{
		var element;
		if (e.target)
		{
			// Standard
			element = e.target;
		}
		else
		{
			// Internet Explorer
			element = e.srcElement;
		}
		
		// Create a new MarkupParser, and parse all markup for the element
		var parser = new MarkupParser();
		props = parser.getAllMarkup(element);
		
		// And refresh the toolbar
		glob_ha[d.id].refreshToolbar(props);
	};
	
	/**
	 * Occurs when the user presses a key when inside the editor.
	 * @param KeyPress parameters.
	 */
	editArea_KeyPressed = function(e)
	{
		var element;
		
		if (d.iframe.contentWindow.getSelection)
		{
			// Standard
			element = d.iframe.contentWindow.getSelection().anchorNode;
		}
		else
		{
			// IE
			var range = document.selection.createRange();
			element = range.parentElement();
		}
	
		// Create a new MarkupParser, and parse all markup for the element
		//alert(d.iframe.contentWindow.document.body.innerHTML);

		var parser = new MarkupParser();
		props = parser.getAllMarkup(element);
		//props.debug();
		// And refresh the toolbar
		
		glob_ha[d.id].refreshToolbar(props);
	};
	
	/**
	 * Refreshes the toolbar, using the given list of enabled font characteristics.
	 * @param props An array contaning the enabled font characteristics.
	 */
	this.refreshToolbar = function(props)
	{
		this.checkButton('btnBold', props.inArray('bold'));
		this.checkButton('btnItalic', props.inArray('italic'));
		this.checkButton('btnUnderline', props.inArray('underline'));
		this.checkButton('btnStrike', props.inArray('strike'));
	};
	
	/**
	 * Adds an image to the specified toolbar.
	 * @param toolbar The toolbar to add the image to.
	 * @param image The image (filename) to add to the toolbar.
	 */
	this.createToolbarImage = function(toolbar, image)
	{
		var img;
		try
		{
			img = document.createElement('<img src="'+image+'">');
		}
		catch(e)
		{
			img = document.createElement("img");
			img.setAttribute("src", image);
		}

		toolbar.appendChild(img);
	}
	
	/**
	 * Checks or unchecks the specified toolbar button,
	 * @param id The button to check/uncheck.
	 * @param check True if the button should be checked, otherwise false.
	 */
	this.checkButton = function(id, check)
	{
		if (check)
		{
			$('#' + id).css("border", "1px solid #BFCAFF").css("background", "#f2f2f2");
		}
		else
		{
			$('#' + id).css("border", "1px solid #E9EAEF").css("background", "transparent");
		}
		
		checkedState[id] = check;
	};
	
	var toolbar = function(imgRoot)
	{
		// Create toolbar TR
		var trToolbar = document.createElement('tr');
		trToolbar.setAttribute('id', 'trToolbar');

		// Create toolbar TD
		var tdToolbar; 
		var css = 'background: silver; border-bottom: 1px outset white; padding: 0; margin: 0;';
		try
		{
			// IE
			tdToolbar = document.createElement('<td class="'+d.id+'_tb" valign="middle" style="' + css + '" id="buttonBar"></td>');
		}
		catch (e)
		{
			// FireFox
			tdToolbar = document.createElement('td');
			tdToolbar.setAttribute('class', d.id + '_tb');
			tdToolbar.setAttribute('valign', 'middle');
			tdToolbar.setAttribute('style', css);
			tdToolbar.setAttribute('id', 'buttonBar');
		}

		// Add the toolbar TD to its TR
		trToolbar.appendChild(tdToolbar);

		var editor = glob_ha[d.id];
		var colors = ['white','FFFFFF','ivory','FFFFF0','lightyellow','FFFFE0','yellow','FFFF00','snow','FFFAFA','floralwhite','FFFAF0','lemonchiffon','FFFACD', 'cornsilk','FFF8DC','seashell','FFF5EE','lavenderblush','FFF0F5','papayawhip','FFEFD5','blanchedalmond','FFEBCD','mistyrose','F FE4E1', 'bisque','FFE4C4','moccasin','FFE4B5','navajowhite','FFDEAD','peachpuff','FFDAB9','gold','FFD700','pink','FFC0CB','lightpink ','FFB6C1', 'orange','FFA500','lightsalmon','FFA07A','darkorange','FF8C00','coral','FF7F50','hotpink','FF69B4','tomato','FF6347','orangered','FF4500', 'deeppink','FF1493','magenta','FF00FF','fuchsia','FF00FF','red','FF0000','oldlace','FDF5E6','lightgoldenrodyellow','FAFAD2',' linen', 'FAF0E6','antiquewhite','FAEBD7','salmon','FA8072','ghostwhite','F8F8FF','mintcream','F5FFFA','whitesmoke','F5F5F5','beige',' F5F5DC', 'wheat','F5DEB3','sandybrown','F4A460','azure','F0FFFF','honeydew','F0FFF0','aliceblue','F0F8FF','khaki','F0E68C','lightcoral ','F08080', 'palegoldenrod','EEE8AA','violet','EE82EE','darksalmon','E9967A','lavender','E6E6FA','lightcyan','E0FFFF','burlywood','DEB887' ,'plum', 'DDA0DD','gainsboro','DCDCDC','crimson','DC143C','palevioletred','DB7093','goldenrod','DAA520','orchid','DA70D6','thistle','D8BFD8', 'lightgrey','D3D3D3','tan','D2B48C','chocolate','D2691E','peru','CD853F','indianred','CD5C5C','mediumvioletred','C71585','silver', 'C0C0C0','darkkhaki','BDB76B','rosybrown','BC8F8F','mediumorchid','BA55D3','darkgoldenrod','B8860B','firebrick','B22222','powderblue', 'B0E0E6','lightsteelblue','B0C4DE','paleturquoise','AFEEEE','greenyellow','ADFF2F','lightblue','ADD8E6','darkgray','A9A9A9','brown', 'A52A2A','sienna',"A0522D",'yellowgreen',"9ACD32",'darkorchid','9932CC','palegreen','98FB98','darkviolet','9400D3','mediumpurple', '9370DB','lightgreen','90EE90','darkseagreen','8FBC8F','saddlebrown','8B4513','darkmagenta','8B008B','darkred','8B0000','blueviolet', '8A2BE2','lightskyblue','87CEFA','skyblue','87CEEB','gray','808080','olive','808000','purple','800080','maroon','800000','aquamarine', '7FFFD4','chartreuse','7FFF00','lawngreen','7CFC00','mediumslateblue','7B68EE','lightslategray','778899','slategray','708090','olivedrab', '6B8E23','slateblue','6A5ACD','dimgray','696969','mediumaquamarine','66CDAA','cornflowerblue','6495ED','cadetblue','5F9EA0', 'darkolivegreen','556B2F','indigo','4B0082','mediumturquoise','48D1CC','darkslateblue','483D8B','steelblue','4682B4','royalblue' , '4169E1','turquoise','40E0D0','mediumseagreen','3CB371','limegreen','32CD32','darkslategray','2F4F4F','seagreen','2E8B57','forestgreen', '228B22','lightseagreen','20B2AA','dodgerblue','1E90FF','midnightblue','191970','cyan','00FFFF','aqua','00FFFF','springgreen', '00FF7F', 'lime','00FF00','mediumspringgreen','00FA9A','darkturquoise','00CED1','deepskyblue','00BFFF','darkcyan',"008B8B",'teal',"008080",'green', '008000','darkgreen','006400','blue','0000FF','mediumblue','0000CD','darkblue','00008B','navy','000080','black','000000'];

	    for(var k = 1; k < d.rows.length; k++)
		{
		    if(undefined === d.rows[k])
			{
				// Row is NULL
				continue;
			}
		    var buttons = d.rows[k].split(",");

			for(var i = 0; i < (buttons.length + 1); i++)
			{
			    if(undefined === d.buttons[buttons[i]])
				{
					// Button is NULL
					continue;
				}
				
				switch(d.buttons[buttons[i]])
				{
					case "bold":
						editor.createToolbarButton(tdToolbar, "btnBold", "bold", imgRoot + "images/b.gif");
						break;
					case "italic":
						editor.createToolbarButton(tdToolbar, "btnItalic", "italic", imgRoot + "images/i.gif");
						break;
					case "underline":
						editor.createToolbarButton(tdToolbar, "btnUnderline", "underline", imgRoot + "images/u.gif");
						break;
					case "strikethrough":
						editor.createToolbarButton(tdToolbar, "btnStrike", "strikethrough", imgRoot + "images/st.gif");
						break;
					case "marquee":
						editor.createToolbarButton(tdToolbar, "btnMarquee", "marquee", imgRoot + "images/marquee.gif", true);
						break;
					case "hyperlink":
						editor.createToolbarButton(tdToolbar, "btnHyperlink", "createlink", imgRoot + "images/hyperlink.gif", true);
						break;
					case "image":
						editor.createToolbarButton(tdToolbar, "btnImage", "insertimage", imgRoot + "images/img.gif", true);
						break;
					case "smilies":
						editor.createToolbarButton(tdToolbar, "btnSmilies", "smilie", imgRoot + "images/smilies.gif");
						break;
					case "separator_dots":
						editor.createToolbarImage(tdToolbar, imgRoot + "images/separator_dots.gif");
						break;
					case "separator_basic":
						editor.createToolbarImage(tdToolbar, imgRoot + "images/separator_basic.gif");
						break;
				}
			}
		}
		
		return trToolbar;
	};
	
	function getToolbarSpace()
	{
		return document.getElementById('buttonBar');
	}
	
	function setupToolbarButton(btn)
	{
		var elementId = btn.getAttribute('id');

		$(btn).css("border", "1px solid #E9EAEF").css("background", "transparent").css("margin", "1px 1px 1px 1px").css("padding", "1px");
		$(btn).mouseover(function(){
			$(btn).css("border", "1px solid #BFCAFF").css("background", "#EFF2FF");
		});
		$(btn).mouseout(function(){
			if (checkedState[elementId]) {
				$(btn).css("border", "1px solid #BFCAFF").css("background", "#f2f2f2");
			}
			else {
				$(btn).css("border", "1px solid #E9EAEF").css("background", "transparent");
			}
		});
		$(btn).mousedown(function()
		{
			if (checkingEnabled[elementId])
			{
				if (checkedState[elementId])
				{
					checkedState[elementId] = false;
				}
				else
				{
					checkedState[elementId] = true;
				}
			}
		});
	}
	
	this.resetButtonEvents = function()
	{
		this.setButtonEvent(this.getButton('btnBold'), "bold");
		this.setButtonEvent(this.getButton('btnItalic'), "italic");
		this.setButtonEvent(this.getButton('btnUnderline'), "underline");
		this.setButtonEvent(this.getButton('btnStrike'), "strikethrough");
		this.setButtonEvent(this.getButton('btnHyperlink'), "createlink");
		this.setButtonEvent(this.getButton('btnImage'), "insertimage");
		this.setButtonEvent(this.getButton('btnSmilies'), "smilie");
	}
	
	this.getButton = function(name)
	{
		return document.getElementById(name);
	}
	
	this.setEditMode = function(mode)
	{
		this.mode = mode;
		if (mode == EditMode.Html)
		{
			this.resetButtonEvents();
			
			// Enable button checking
			checkingEnabled['btnBold'] = true;
			checkingEnabled['btnItalic'] = true;
			checkingEnabled['btnUnderline'] = true;
			checkingEnabled['btnStrike'] = true;
		}
		else if (mode == EditMode.Ubb)
		{
			// Disable button checking
			checkingEnabled['btnBold'] = false;
			checkingEnabled['btnItalic'] = false;
			checkingEnabled['btnUnderline'] = false;
			checkingEnabled['btnStrike'] = false;

			this.setButtonEvent(this.getButton('btnBold'), function()
			{
				if (glob_ha[d.id].language == "en")
				{
					boldText = prompt("Please insert the text that you want to be bold.", "");
				}
				else
				{
					boldText = prompt("Plaats de tekst die u dik gedrukt wil hebben.", "");
				}
				if (boldText && boldText.length > 0)
				{
					glob_ha[d.id].insertHTML("[b]" + boldText + "[/b]");
				}
			});
			this.setButtonEvent(this.getButton('btnItalic'), function()
			{
				if (glob_ha[d.id].language == "en")
				{
					insertText = prompt("Please insert the text that you want to be italic.", "");
				}
				else
				{
					insertText = prompt("Plaats de tekst die u schuin gedrukt wil hebben.", "");
				}
				if (insertText && insertText.length > 0)
				{
					glob_ha[d.id].insertHTML("[i]" + insertText + "[/i]");
				}
			});
			this.setButtonEvent(this.getButton('btnUnderline'), function()
			{
				if (glob_ha[d.id].language == "en")
				{
					insertText = prompt("Please insert the text that you want to be underlined.", "");
				}
				else
				{
					insertText = prompt("Plaats de tekst die u wil onderstrepen.", "");
				}
				if (insertText && insertText.length > 0)
				{
					glob_ha[d.id].insertHTML("[u]" + insertText + "[/u]");
				}
			});
			this.setButtonEvent(this.getButton('btnStrike'), function()
			{
				if (glob_ha[d.id].language == "en")
				{
					insertText = prompt("Please insert the text that you want to be striked.", "");
				}
				else
				{
					insertText = prompt("Plaats de tekst die u wil doorstrepen.", "");
				}
				if (insertText && insertText.length > 0)
				{
					glob_ha[d.id].insertHTML("[strike]" + insertText + "[/strike]");
				}
			});
			this.setButtonEvent(this.getButton('btnHyperlink'), function()
			{
				if (glob_ha[d.id].language == "en")
				{
					url = prompt("Please insert the address that you want to add.", "http://");
					if(url)
					{
						title = prompt("Please insert the title of the website.", "Page title");
					}
				}
				else
				{
					url = prompt("Plaats het internet adres dat u wil toevoegen.", "http://");
					if(url)
					{
						title = prompt("Plaats hier de titel van die website", "Pagina titel");
					}
				}	
				if(url && title)
				{
					if (url.length > 0 && title.length > 0)
					{
						glob_ha[d.id].insertHTML("[url=" + url + "]" + title + "[/url]");
					}
				}
			});
			this.setButtonEvent(this.getButton('btnImage'), function()
			{
				if (glob_ha[d.id].language == "en")
				{
					imageUrl = prompt("Please insert the url of the image you want to add.", "http://");
				}
				else
				{
					imageUrl = prompt("Plaats het internetadres van het plaatje", "http://");
				}
				if (imageUrl && imageUrl.length > 0)
				{
					glob_ha[d.id].insertHTML("[img]" + imageUrl + "[/img]");
				}
			});
			this.setButtonEvent(this.getButton('btnSmilies'), "smilie");
			
			// Uncheck all toolbar buttons
			this.refreshToolbar(new Array());
		}
	};
	
	this.setButtonEvent = function(button, command, commandParam)
	{
		if (typeof(command) == "function")
		{
			button.onclick = function()
			{
				if (commandParam)
					command(commandParam);
				else
					command();
			};
		}
		else
		{
			if (button)
			{
				button.onclick = function()
				{
					glob_ha[d.id].cmd(command);
				};
			}
		}
	}
	
	this.createToolbarButton = function(parent, id, command, image, disable_checking, commandParam)
	{
		var btn;
		try
		{
			btn = document.createElement("<button type=\"button\" id=\"" + id + "\" style=\"border: 1px solid #cccccc;\"></button>");
		}
		catch(e)
		{
			btn = document.createElement("button");
			btn.setAttribute("type", "button");
			btn.setAttribute("id", id);
			btn.setAttribute("style", "border: 0;");
		}
		
		glob_ha[d.id].setButtonEvent(btn, command, commandParam);
		
		// Create image in button
		var img;
		try
		{
			// IE
			img	= document.createElement("<img src=\"" + image + "\" style=\"border: none;\" />");
		}
		catch (e)
		{
			// FireFox
			img	= document.createElement("img");
			img.setAttribute("src", image);
		}
		btn.appendChild(img);

		// Add to toolbar
		parent.appendChild(btn);

		//
		if (!disable_checking)
		{
			checkingEnabled[id] = true;
		}
		
		return btn;
	};
	
	/**
	 * Creates the smiley array.
	 * @return An array containing all smilies.
	 */
	this.createSmileyList = function()
	{
		// Create smilies
		var smilies = new Array();
		if (this.smileyMode != 'none')
		{
			smilies.push(	[ ':)', 'http://www.tboek.nl/gastenboek/s/19.gif' ],
							[ ':(', 'http://www.tboek.nl/gastenboek/s/18.gif' ],
							[ ':D', 'http://www.tboek.nl/gastenboek/s/28.gif' ],
							[ ';)', 'http://www.tboek.nl/gastenboek/s/13.gif' ],
							[ ':s', 'http://www.tboek.nl/gastenboek/s/35.gif' ],
							[ ':clown:', 'http://www.tboek.nl/gastenboek/s/2.gif' ],
							[ ':tong:', 'http://www.tboek.nl/gastenboek/s/3.gif' ],
							[ '(A)', 'http://www.tboek.nl/gastenboek/s/4.gif' ],
							[ ':o', 'http://www.tboek.nl/gastenboek/s/7.gif' ],
							[ ':roll:', 'http://www.tboek.nl/gastenboek/s/8.gif' ],
							[ ':grr:', 'http://www.tboek.nl/gastenboek/s/9.gif' ],
							[ ':angel:', 'http://www.tboek.nl/gastenboek/s/11.gif' ],
							[ ':-D', 'http://www.tboek.nl/gastenboek/s/12.gif' ],
							[ ':crazy:', 'http://www.tboek.nl/gastenboek/s/14.gif' ],
							[ ':??:', 'http://www.tboek.nl/gastenboek/s/15.gif' ],
							[ '(H)', 'http://www.tboek.nl/gastenboek/s/16.gif' ],
							[ '8o', 'http://www.tboek.nl/gastenboek/s/17.gif' ],
							[ ':alien:', 'http://www.tboek.nl/gastenboek/s/21.gif' ],
							[ '(L)', 'http://www.tboek.nl/gastenboek/s/22.gif' ],
							[ ':frog:', 'http://www.tboek.nl/gastenboek/s/23.gif' ],
							[ ':tech:', 'http://www.tboek.nl/gastenboek/s/24.gif' ],
							[ '(N)', 'http://www.tboek.nl/gastenboek/s/25.gif' ],
							[ '(Y)', 'http://www.tboek.nl/gastenboek/s/26.gif' ],
							[ ':warning:', 'http://www.tboek.nl/gastenboek/s/27.gif' ],
							[ ':arrow:', 'http://www.tboek.nl/gastenboek/s/29.gif' ],
							[ ':koffer:', 'http://www.tboek.nl/gastenboek/s/30.gif' ],
							[ ':P', 'http://www.tboek.nl/gastenboek/s/31.gif' ],
							[ ':butterfly:', 'http://www.tboek.nl/gastenboek/s/32.gif' ],
							[ ':?:', 'http://www.tboek.nl/gastenboek/s/33.gif' ],
							[ ':zzz:', 'http://www.tboek.nl/gastenboek/s/34.gif' ],
							[ ':e', 'http://www.tboek.nl/gastenboek/s/36.gif' ]);
			
			if (this.smileyMode != 'friendly')
			{
				smilies.push(	[ ':devil:', 'http://www.tboek.nl/gastenboek/s/1.gif' ],
								[ ':fu:', 'http://www.tboek.nl/gastenboek/s/5.gif' ],
								[ ':foei:', 'http://www.tboek.nl/gastenboek/s/20.gif' ]);
			}
		}
		
		this.smilies = smilies;
		
		return smilies;
	}
	
	/**
	 * Creates the smiley bar.
	 */
	this.createSmileyBar = function(){
		// Create main smiley bar
		var divContainer;
		var id = 'divSmileybar';
		var elWidth = document.getElementById('tblToolbar').width;
		
		var css = 'background-color: #dedede; border: 1px solid #cccccc; position: relative; height: 75px; margin-top: -75px; top: 150px;';
		if($.browser.msie)
		{
			elWidth -= 4;
			css += " margin-left: 4px;";
		}
		css += " width: " + elWidth + "px;";
		
		try
		{
			// ie
			divContainer = document.createElement('<div id="'+id+'" style="'+css+'">');
		}
		catch(ex)
		{
			// w3c
			divContainer = document.createElement('div');
			divContainer.setAttribute('id', id);
			divContainer.setAttribute('style', css);
		}

		document.getElementById('tblToolbar').parentNode.insertBefore(divContainer, document.getElementById('tblToolbar'));

		// Create smilies
		for(var i = 0; i < this.smilies.length; i++)
		{
			smilie = this.smilies[i];
			this.createSmiley(i, smilie[0], smilie[1]);
		}
	};

	/**
	 * Shows the smiley bar.
	 */
	this.showSmileyBar = function()
	{
		var divSmileybar = document.getElementById('divSmileybar');

		if (!divSmileybar)
		{
			// First time, creater smil;ey bar
			this.createSmileyBar();
		}
		else
		{
			// Later, just show smiley bar
			divSmileybar.style.display = 'block';
		}
	};

	/**
	 * Creates the specified smiley, adding it to the smiley bar.
	 * @param The smiley identifier.
	 * @param The ubb code that corresponds with this smiley.
	 * @param The smiley image.
	 */
	this.createSmiley = function(index, code, img)
	{
		// Create button
		var css = 'cursor: pointer;';
		var id = 'smilie' + index;

		// Create smilie image
		var imgSmiley;
		try
		{
			// FireFox
			imgSmiley = document.createElement('img');
			imgSmiley.setAttribute('src', img);
			imgSmiley.setAttribute('id', id);
			imgSmiley.setAttribute('style', css);
		}
		catch(e)
		{
			// IE
			imgSmiley = document.createElement('<img src="' + img + '" id="'+id+'" style="' + css + '">');
		}

		// Add onclick event
		imgSmiley.onclick = function(e){
			var element;
			if (e)
			{
				// w3c
				element = e.target;
			}
			else
			{
				// IE
				element = event.srcElement;
			}

			var index = element.id.substr(6);
			var smilie = glob_ha[d.id].smilies[index];

			if (glob_ha[d.id].mode == EditMode.Ubb)
			{
				glob_ha[d.id].insertHTML(' ' + smilie[0] + ' ');
			}
			else
			{
				glob_ha[d.id].insertHTML('<img src="' + smilie[1] + '" alt="' + smilie[0] + '" />');
			}

			glob_ha[d.id].checkButton('btnSmilies', false);
			
			this.parentNode.style.display = 'none';
		};

		// Add this button to the button bar
		document.getElementById('divSmileybar').appendChild(imgSmiley);
		
		$(imgSmiley).css("margin", "1px").css("margin-left", "2px").css("cursor", "pointer");
	}

	/**
	 * Inserts raw HTML at the cursor position.
	 * @param The raw HTML code to insert.
	 */
	this.insertHTML = function(html)
	{
		// Ubb mode? Then let something else handle this
		if (this.mode == EditMode.Ubb && document.OnInsertUBB)
		{
			document.OnInsertUBB(this, html);
			return;
		}
		
		var editor = document.getElementById('hb_html');
		editor.contentWindow.focus();

		if (window.getSelection)
		{ //Gecko
			d.iframe.contentWindow.document.execCommand("insertHTML", false, html);
		}
		else if (document.selection)
		{ //IE
			var selRange = editor.document.selection.createRange();
			selRange.pasteHTML(html);
		}
	};

	/**
	 * Checks if there is a user selection.
	 * @return True if there is a user selection, otherwise false.
	 */
	this.textSelected = function() {
		var editor = document.getElementById('hb_html');

		if (window.getSelection)
		{
			//Gecko
			return (editor.contentWindow.document.getSelection() != '');
		}
		else if (document.selection)
		{
			//IE
			return (editor.contentWindow.document.selection.createRange().text != '');
		}
	};

	/**
	 * Inserts raw HTML and selects it.
	 * @param The raw HTML to select and insert.
	 */
	this.insertSelection = function(html) {
		var editor = document.getElementById('hb_html');
		var selectionRange;

		if (window.getSelection)
		{
			//Gecko
			selection = editor.contentWindow.getSelection();
			selectionRange = selection.getRangeAt(0);

			var selOffset = selection.anchorOffset;
			var node = selection.anchorNode;
			
			this.insertHTML(html);

			selectionRange.selectNode(node);
			/*
			selectionRange.setStart(node, selOffset);
			selectionRange.setEnd(node, selectionRange.anchorOffset + html.length);*/
			selection.addRange(selectionRange);
		}
		else if (document.selection)
		{
			//IE
			var selection = editor.contentWindow.document.selection;

			selectionRange = selection.createRange();
			selectionRange.text = html;
		}
	};

	this.getSelectionRange = function(){
		var userSelection;
		if (window.getSelection)
		{
			userSelection = document.getElementById('hb_html').window.getSelection();
		}
		else if (document.selection)
		{
			userSelection = document.getElementById('hb_html').selection.createRange();
		}
	};

	/**
	 * Executes an editor command.
	 * @param The command to execute.
	 * @param The command's arguments.
	 */
	this.cmd = function(cmd,arg1)
	{
		// When user clicks toolbar button make sure it always targets its respective WYSIWYG
		d.iframe.contentWindow.focus();
		if(cmd === "html")
		{
			var text = this.get_html();
			if($("#"+d.id).is(":visible"))
			{
				$("#"+d.id).hide();
				$("#"+d.id+"_html").show();
				this.set_text(text);
			}
			else
			{
				$("#"+d.id).show();
				$("#"+d.id+"_html").hide();
				this.set_text(text);
				$("#"+d.id).focus();
			}
		}
		else if(cmd === "createlink")
		{		
			if (navigator.appName != 'Microsoft Internet Explorer' || true)
			{
				if (!this.textSelected())
				{
					if (this.language == 'en')
					{
						alert('Select text or an image to create a link.');
					}
					else
					{
						alert('Selecteer tekst of een plaatje om er een link van te maken.');
					}
					return;
				}
			
				// Generic implementation
				if (this.language == 'en')
				{
					var url = prompt("Please insert the website URL:", '');
				}
				else
				{
					var url = prompt("Vul de website URL in:", '');
				}
				
				if (url == null || url == undefined)
				{
					return;
				}
				
				if (!url.startsWith('http://'))
				{
					url = 'http://' + url;
				}
				
				d.iframe.contentWindow.document.execCommand(cmd, false, url);
			}
			else
			{
				// Internet Explorer
				d.iframe.contentWindow.document.execCommand(cmd, true, '');
			}
		}
		else if(cmd === "marquee")
		{
			if (this.language == 'en')
			{
				var url = prompt("Insert the text you want to marquee:", '');
			}
			else
			{
				var url = prompt("Vul de tekst in die u wilt laten bewegen:", '');
			}
			if (url)
			{
				this.insertHTML('[m]' + url + '[/m]');
			}
		}
		else if(cmd==="smilie")
		{
			var smileybar = document.getElementById('divSmileybar');
			if (smileybar != undefined)
			{
				if (smileybar.style.display == 'block')
				{
					smileybar.style.display = 'none';
					return;
				}
			}
		
			this.showSmileyBar();
		}
		else if(cmd==="insertimage")
		{
			if (this.language == 'en')
			{
				var img = prompt("Insert the URL of the image:", '');
			}
			else
			{
				var img = prompt("Voer de URL van het plaatje in:", '');
			}
			if (img == '' || img == null)
			{
				return;
			}

			d.iframe.contentWindow.document.execCommand(cmd, false, img);
		}
		else if(cmd==="fontsize"){
			d.iframe.contentWindow.document.execCommand(cmd, false,arg1);
		}else if(cmd==="backcolor"){
			if($.browser.msie)
			{
				d.iframe.contentWindow.document.execCommand("backcolor", false,arg1);
			}
			else
			{
				d.iframe.contentWindow.document.execCommand("hilitecolor", false,arg1);
			}
		}else if(cmd==="fontcolor"){
			d.iframe.contentWindow.document.execCommand("forecolor", false,arg1);
		}else if(cmd==="fontname"){
			d.iframe.contentWindow.document.execCommand(cmd, false, arg1);
		}else if(cmd==="cut"){
			if($.browser.msie === false)
			{
				alert("Available in IExplore only.\nUse CTRL+X to cut text!");
			}
			else
			{
				d.iframe.contentWindow.document.execCommand('Cut');
			}
		}else if(cmd==="copy"){
			if($.browser.msie === false)
			{
				alert("Available in IExplore only.\nUse CTRL+C to copy text!");
			}
			else
			{
				d.iframe.contentWindow.document.execCommand('Copy');
			}
		}else if(cmd==="paste"){
			if($.browser.msie === false)
			{
				alert("Available in IExplore only.\nUse CTRL+V to paste text!");
			}
			else
			{
				d.iframe.contentWindow.document.execCommand('Paste');
			}
		}else{
			d.iframe.contentWindow.document.execCommand(cmd, false, null);
		}
		
		// Setting the changed text to textearea
		if($("#"+d.id).is(":visible") === false)
		{
			$("#"+d.id).val(this.get_html());
		}
	};
	
	/**
	 * Gets all editor contents.
	 * @return The editor's contents.
	 */
	this.get_text = function(){
	   if($("#"+d.id).is(":visible")){
	      return $("#"+d.id).val();
	   }
	   var text;
	   if($.browser.msie){
	       text = d.iframe.contentWindow.document.body.innerText;
	   }else{
	       var html = d.iframe.contentWindow.document.body.ownerDocument.createRange();
		   html.selectNodeContents(d.iframe.contentWindow.document.body);
		   text = html;
	   }
	   return text;
	};
	
	/**
	 * Sets the editor contents.
	 * @param The new editor content.
	 */
	this.set_text = function(txt){
	   var text = (undefined===txt)?"":txt;
	   if($("#"+d.id).is(":visible")){
	      $("#"+d.id).val(text);
	   }else if($.browser.mozilla){
		   if(text===""||text===" "){text="&nbsp;";}
		   d.iframe.contentWindow.document.open('text/html', 'replace');
		   d.iframe.contentWindow.document.write(text);
		   d.iframe.contentWindow.document.close();
		   d.iframe.contentWindow.document.body.normalize();
	   }else{
           d.iframe.contentWindow.document.body.innerText="";
	       if(text!==""){d.iframe.contentWindow.document.write(text);}
	   }
	   return this;
	};
	this.get_html = function(){
	   var html;
	   if($("#"+d.id).is(":visible")){
	      html = $("#"+d.id).val();
	   }else{
	      html = d.iframe.contentWindow.document.body.innerHTML;
	   }
	   if(typeof getXHTML === 'function'){ return getXHTML(html); }else{return html;}
	};
	this.button = function(name,row){
	    d.buttons[d.buttons.length]=name;
		if(undefined===row){
		    if(undefined===d.rows[1]){d.rows[1]="";}
			d.rows[1]=d.rows[1]+","+(d.buttons.length-1);
		}else{
		    if(undefined===d.rows[row]){d.rows[row]="";}
			d.rows[row]=d.rows[row]+","+(d.buttons.length-1);
		}
		return this;
	};

	/**
	  * Adds a separator image to the toolbar
            * @param String "basic" or "dots"
	  * @return this;
	  */
	this.separator = function(type,row){
	    if(undefined===type){type="basic";}
	    this.button("separator_"+type,row);
		return this;
	};
	/**
	  * Posts the form data to the specified URL using Ajax
            * @param The URL to post to
	  * @param The text to be posted, default the (X)HTML text
	  * @return this;
	  */
	this.post=function(url,data){
	    if(undefined===data){data=this.get_html();} data=(d.id+"="+data);
		$.ajax({type: "POST", data: data,url: url,dataType: "html",error:d.error,success:d.success});
	};
	/**
	  * Gets the form data to the specified URL using Ajax
            * @param String the URL to get to
	  * @param String the text to be posted, default the (X)HTML text
	  * @return this;
	  */
	this.get=function(url,data){
	    if(undefined===data){data=this.get_html();} data=(d.id+"="+data);
		$.ajax({type: "GET", data: data,url: url,dataType: "html",error:d.error,success:d.success});
	};
	this.success=function(fn){d.success=fn;return this;};
	this.error=function(fn){d.error=fn;return this;};
	return this;
};