(function (global) {
	'use strict';
	
	var forum = {};
	
	var query = {};
	
	(function () {
		var q = global.location.search.substring(1);
		var vars = q.split("&");
		for (var i = 0; i < vars.length; i++) {
			var pair = vars[i].split("=");
			query[decodeURIComponent(pair[0])] = pair[1] ? decodeURIComponent(pair[1]) : "";
		}
	}());
	
	/*var xhr = function (uri, callback) {
		var x = new XMLHttpRequest();
		x.open('get', uri, true);
		x.onload = function () {
			callback(x.response);
		};
		x.onerror = function (e) {
			callback(null);
		};
		x.send();
	};*/
	
	
			
	var on = function (name, elem, callback) {
		if(elem.addEventListener) {
			elem.addEventListener(name, callback, false);
		}
		else if(elem.attachEvent) {
			elem.attachEvent('on'+name, function () {
				callback(global.event);
			});
		}
	};
	
	var XHR = function (url, data, callback) {
		var X = new XMLHttpRequest();
		//var fd = new FormData();
		var params = [];
		for(var i in data) {
			params.push(encodeURIComponent(i)+"="+encodeURIComponent(data[i]));
			//fd.append(i, data[i]);
		}
		params = params.join("&");
		X.open('post', url, true);
		//Send the proper header information along with the request
		X.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
		X.onreadystatechange = function () {
			if(X.status !== 200 || X.readyState !== 4) return;
			
			var response = X.responseText;
			
			callback(response);
		};
		//X.send(fd);
		X.send(params);
		return X;
	};
	
	forum.bbcode2html = function (content) {
		
		// Created by djazz
		
		content = content.replace(/</gi, '&lt;'); // <
		content = content.replace(/>/gi, '&gt;'); // >
		content = content.replace(/\r\n/gi, '\<br\>'); // \r\n
		content = content.replace(/\n/gi, '\<br\>'); // \n
		content = content.replace(/\r/gi, '\<br\>'); // \r
		
		
		// Check for [code] text
		content = content.replace(/\[code\](.+?)\[\/code\]/gi, function (matched, code) {
			
			code = code.replace(/\[/gi, '&#91;');
			code = code.replace(/\]/gi, '&#93;');
			
			var res = [	'<table width="90%" border="0" align="center" cellpadding="0" cellspacing="0">',
							'<tr>',
								'<td class="quotecodeheader" style="color: #666;"><strong> Code</strong></td>',
							'</tr>',
							'<tr>',
								'<td class="codebody" style="background-color: #F9F9F9;color: #333;border: 1px solid #AAA; font-family: Courier new, Courier, monospace;"><pre style="padding: 3px;margin: 0px; max-height: 500px; overflow: auto;">'+code+'</pre></td>',
							'</tr>',
						'</table>'
			].join("\r\n");
			
			return res;
		});
		
		
		// links [url=][/url]
		content = content.replace(/\[url=([a-zA-Z0-9\:\/\-\?\&\.\=\_\~\#\'\ ]+)\](.+?)\[\/url\]/gi, '<a href="$1" target="_blank">$2</a>');
		
		// images [img][/img]
		content = content.replace(/\[img\]([a-zA-Z0-9\:\/\-\?\&\.\=\_\~\#\'\ ]+)\[\/img\]/gi, '<img src="$1" alt="[img]"/>');
		
		
		
		// bold text [b][/b]
		content = content.replace(/\[b\](.+?)\[\/b]/gi, '<b>$1</b>');
		
		// italic text [i][/i]
		content = content.replace(/\[i\](.+?)\[\/i]/gi, '<i>$1</i>');
		
		// underlined text [u][/u]
		content = content.replace(/\[u\](.+?)\[\/u\]/gi, '<u>$1</u>');
		
		// strikethrough text [s][/s]
		content = content.replace(/\[s\](.+?)\[\/s\]/gi,'<span style="text-decoration: line-through;">$1</span>');
		
		// color of text (Warning! CSS injection!) [color=][/color]
		content = content.replace(/\[color=(.+?)\](.+?)\[\/color\]/gi,'<span style="color: $1;">$2</span>');
		
		// set fontsize of text in pixels (Warning! CSS injection!) [size=][/size]
		content = content.replace(/\[size=(.+?)\](.+?)\[\/size\]/gi,'<span style="font-size: $1px">$2</span>');
		
		
		
		// Headings
		// [h1][/h1]
		content = content.replace(/\[h1\](.+?)\[\/h1]/gi, '<h1>$1</h1>');
		// [h2][/h2]
		content = content.replace(/\[h2\](.+?)\[\/h2]/gi, '<h2>$1</h2>');
		// [h3][/h3]
		content = content.replace(/\[h3\](.+?)\[\/h3]/gi, '<h3>$1</h3>');
		// [h4][/h4]
		content = content.replace(/\[h4\](.+?)\[\/h4]/gi, '<h4>$1</h4>');
		// [h5][/h5]
		content = content.replace(/\[h5\](.+?)\[\/h5]/gi, '<h5>$1</h5>');
		// [h6][/h6]
		content = content.replace(/\[h6\](.+?)\[\/h6]/gi, '<h6>$1</h6>');
		
		
		// Tables
		// [table=bordersize][/table]
		content = content.replace(/\[table=(.+?)\](.+?)\[\/table]/gi, '<table border=$1>$2</table>');
		// [table][/table]
		content = content.replace(/\[table\](.+?)\[\/table]/gi, '<table>$1</table>');
		// [tr][/tr]
		content = content.replace(/\[tr\](.+?)\[\/tr]/gi, '<tr>$1</tr>');
		// [th][/th]
		content = content.replace(/\[th\](.+?)\[\/th]/gi, '<th>$1</th>');
		// [td][/td]
		content = content.replace(/\[td\](.+?)\[\/td]/gi, '<td>$1</td>');
		
		
		return content;
	};
	
	var postsInEdit = [];
	forum.editPost = function (post_id) {
		if(postsInEdit.indexOf(post_id) >= 0) return;
		var post = global.document.querySelector('#post_'+post_id+' .postcontent');
		if(post) {
			postsInEdit.push(post_id);
			var old_content = post.innerHTML;
			post.innerHTML = "<strong>Loading...</strong>";
			XHR('dynamic.php?post='+post_id, {}, function (response) {
				var preview = global.document.createElement('div');
				var textarea = global.document.createElement('textarea');
				textarea.id = "ta_"+post_id;
				textarea.value = response;
				textarea.style.width = (post.offsetWidth-16)+"px";
				textarea.style.height = (post.offsetHeight+50)+"px";
				var saveButton = global.document.createElement('button');
				saveButton.textContent = "Save";
				var cancelButton = global.document.createElement('button');
				cancelButton.textContent = "Cancel";
				var deleteButton = global.document.createElement('button');
				deleteButton.textContent = "Delete";
				
				post.innerHTML = '';
				
				post.appendChild(textarea);
				post.appendChild(global.document.createElement('br'));
				post.appendChild(saveButton);
				post.appendChild(cancelButton);
				post.appendChild(deleteButton);
				post.appendChild(global.document.createElement('hr'));
				post.appendChild(preview);
				
				textarea.focus();
				
				on('input', textarea, function () {
					preview.innerHTML = forum.bbcode2html(textarea.value);
				});
				preview.innerHTML = forum.bbcode2html(textarea.value);
				
				on('click', saveButton, function () {
					var content = textarea.value;
					post.innerHTML = "<strong>Saving...</strong>";
					XHR('dynamic.php?post='+post_id, {content: content}, function (response) {
						post.innerHTML = forum.bbcode2html(response);
						postsInEdit.splice(postsInEdit.indexOf(post_id), 1);
						post.focus();
					});
				}, false);
				
				on('click', cancelButton, function () {
					post.innerHTML = old_content;
					postsInEdit.splice(postsInEdit.indexOf(post_id), 1);
				}, false);
				
				on('click', deleteButton, function () {
					if(confirm('Are you sure you want to hide this post?\nA moderator or an admin can restore this post or read it\'s contents')) {
						global.document.location.href = "?post="+post_id+"&delete=1";
					}
				}, false);
			});
		}
	};
	
	on('load', global, function () {
		
		var newpostcontent = global.document.querySelector("#newpostcontent");
		if(newpostcontent) {
			var newpostpreview = global.document.querySelector("#newpostpreview");
			on('input', newpostcontent, function () {
				newpostpreview.innerHTML = forum.bbcode2html(newpostcontent.value);
			});
		}
		
		if(query.thread !== undefined) {
			/*var posts = global.document.querySelectorAll('.post');
			
			for(var i=0; i < posts.length; i++) {
				var post_id = +posts[i].id.split('post_')[1];
				if(post_id) {
					XHR('dynamic.php?post='+post_id, {}, (function () {
						var content = posts[i].querySelector('.postcontent');
						return function (response) {
							if(response) {
								content.innerHTML = forum.bbcode2html(response);
							}
						};
					}()));
				}
			}*/
		
			var raw_hash = document.location.hash;
			if(raw_hash === "#"+parseInt(raw_hash.substring(1), 10)) {
				var post_id = "post_"+parseInt(raw_hash.substring(1), 10);
				var post = global.document.getElementById(post_id);
				if(post) {
					var oldclass = post.className;
					post.className += ' flash';
					//post.scrollIntoView();
					setTimeout(function () {
						post.className = oldclass;
					}, 1000);
				}
			}
			
		}
	});
	setTimeout(function () {
		if(query.thread !== undefined) {
			var thread_rename = global.document.querySelector('#thread_rename');
			var thread_delete = global.document.querySelector('#thread_delete');
			
			if(thread_rename) {
				var thread_title = global.document.querySelector('#thread_title');
				var old_title = thread_title.textContent;
				var threadTitleEdit = global.document.createElement('input');
				var saveButton = global.document.createElement('button');
				saveButton.textContent = 'Save';
				
				var isEditing = false;
				
				on('input', threadTitleEdit, function () {
					saveButton.disabled = threadTitleEdit.value.length === 0;
				});
				
				on('click', saveButton, function () {
					var newtitle = threadTitleEdit.value;
					
					
					
					threadTitleEdit.disabled = true;
					saveButton.disabled = true;
					
					XHR('dynamic.php?thread='+query.thread, {title: newtitle}, function (response) {
						thread_title.textContent = response;
						global.document.title = response + SEPARATOR + TITLE;
						thread_rename.disabled = false;
						threadTitleEdit.disabled = false;
						saveButton.disabled = false;
					});
				});
				
				on('click', thread_rename, function () {
					
					
					thread_rename.disabled = true;
					
					XHR('dynamic.php?thread='+query.thread, {}, function (response) {
						thread_title.textContent = '';
						thread_title.appendChild(threadTitleEdit);
						thread_title.appendChild(saveButton);
						threadTitleEdit.value = response;
						threadTitleEdit.focus();
					});
					
				});
			}
			if(thread_delete) {
				on('click', thread_delete, function () {
					if(confirm("Are you sure you want to delete this thread?\nAll posts in this thread will get permanently deleted aswell")) {
						global.document.location = "?thread="+query.thread+"&delete";
					}
				});
			}
		}
	}, 0);
	
	global.forum = forum;
}(window));


