/* SaveNotepad */
function saveNotepad() {
	ajFetch('?proc_footer_element=notepad&notepad_body=' + urlEncode(document.getElementById('notepad_body').value), 'footer_elements', false, 0);
}

function notepadStateChange() {
	document.getElementById('notepad_save_button').className='submit';
	document.getElementById('notepad_save_button').disabled=false;
}


//////////////////////////// TEMP DEBUG /////////////////////////
function showDebug() {
	var debugDiv = document.getElementById('debug'); 
	if (debugDiv.style.visibility == 'hidden') {
		debugDiv.style.visibility = 'visible';
	} 
	
	else debugDiv.style.visibility = 'hidden';
}

function clearDebug() {
	document.getElementById('debug').innerHTML = '<table width="100%" border="0"> <tr> <td><h2>DO NOT REPORT!</h2></td><td align="right"><a href="javascript:clearDebug();">Clear</a></td></tr></table>';
	document.getElementById('debugLink').innerHTML = '<a href="javascript:showDebug();">Debug</a>';
	var debugDiv = document.getElementById('debug');
	debugDiv.style.visibility = 'hidden';
}

/* URL POPPER */
function popUp(URL) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=600,height=550');");
}

function showUserPicture(pictureFile) {
	document.getElementById('shadeWrapper').style.visibility = 'visible';
	document.getElementById('noShadeContent').style.visibility = 'visible';
	document.getElementById('dynamicUserPictureViewer').src = 'system/image.php?file=' + pictureFile + '&width=400';
}

function hideUserPicture() {
	document.getElementById('shadeWrapper').style.visibility = 'hidden';
	document.getElementById('noShadeContent').style.visibility = 'hidden';
}

/* Ranking */
function rankEval(hoverState, objectNumber) {
	
	if (objectNumber > 0) {
		
		for (i=1; i <= objectNumber; i++) {
			document.getElementById('voteObject'+i).className = 'votehover';
		}
		
		if (objectNumber+1 < 5) {
			for (i=objectNumber+1; i<=5; i++) {
				document.getElementById('voteObject'+i).className = 'voteclear';
			}
		}
		
		document.getElementById('voteInt').innerHTML = objectNumber + '/5';
		
	} else {
		for (i=1; i<=5; i++) {
			document.getElementById('voteObject'+i).className = 'voteclear';
		}
		document.getElementById('voteInt').innerHTML = '';
	}
}
	
/* BOOKMARK */
function bookmark(title, url) {
  if (document.all) window.external.AddFavorite(url, title);
  else if (window.sidebar) window.sidebar.addPanel(title, url, "");
}



/* TRITON */
var pin = Math.random();
var tritonProcState = false;

function launchTRITON() {
	if (!tritonProcState) {
		ajFetch('?L=chat.dac&chromeless=1&pin=' + pin, 'appendChatContent', true, 3000);
		document.getElementById('textInput').focus();
		tritonProcState = true;
	}
}

var usersInChat = new Array;
var stringBuffer = '';
var stringBufferActual = '';

function appendChatContent(dataContent) {
	/* Explode the data content at each carriage return */
	streamLines = dataContent.split('\n');
	
	/* Run through each lines */
	for (var n=0; n < streamLines.length; n++) {
		
		/* Don't act if the streamLine is blank */
		if (trim(streamLines[n]) != '') {
		
			/* Split the line into content chunks, divided by ":" */
			contentArray = streamLines[n].split(':');
			
			/* Data innput modes switching */
			switch(contentArray[0]) {
				
				/* CHATCONTENT MODE */
				case 'CHATCONTENT':
					var chatContainer = document.getElementById('chatContent');
					
					if (chatContainer.innerHTML.length > 5120) {
						chatContainer.removeChild(chatContainer.childNodes[0]);
					}
					
					chatContainer.innerHTML += urlDecode(contentArray[1]);
					scrollDown();
				break;
				
				case 'NICKLIST':
					document.getElementById('nickList').innerHTML = urlDecode(contentArray[1]);
				break;
				
				case 'NICKLISTPUSH':
					if (!document.getElementById('nickElement_'+contentArray[1])) {
						/* Push an element into the nicklist */
						var containerElement = document.getElementById('nickList');
						var newNickContainer = document.createElement('div');
						newNickContainer.setAttribute('id', 'nickElement_'+contentArray[1]);
						newNickContainer.innerHTML = urlDecode(contentArray[2]);
						containerElement.appendChild(newNickContainer);
						
						usersInChat.push(contentArray[1]);
					}
					
				break;
				
				case 'NICKLISTPOP':
					/* Pop an element off the nicklist */
					if (document.getElementById('nickElement_'+contentArray[1])) {
						var containerElement = document.getElementById('nickList');
						containerElement.removeChild('nickElement_'+contentArray[1]);
					}
					
					array_pop(usersInChat, contentArray[1]);
					
				break;
				
				case 'TOPIC':
					document.getElementById('topicHandle').innerHTML = urlDecode(contentArray[1]);
				break;

				case 'HEADER':
					document.getElementById('topicHeader').innerHTML = urlDecode(contentArray[1]);
				break;
				
				default:
					document.getElementById('debug').innerHTML += streamLines[n] + " ";
					
					/* 2b removed */
					var debuglen = document.getElementById('debugLink').innerHTML.length;
					document.getElementById('debugLink').innerHTML = '<a href="javascript:showDebug();">Debug (' + debuglen + ')</a>';
				break;
			}
		}
	}
}

/* KeyCodes handler */
function keyEventHandler(key) {
	
	/* This is called when a key has been pressed in the text area */
	switch (key) {
		case 9: /* Tab key */
			
			i=0;
			
			var textField = document.getElementById('textInput');
			if (textField.value != "") {
				
				words = textField.value.split(' ');
				var wordLen = words[words.length-1].length;
				var wholeLen = document.getElementById('textInput').value.length;
				
				if (trim(words[words.length-1]) != "") {
				
					while (key < usersInChat.length) {
						if (words[words.length-1].toLowerCase() == usersInChat[i].substr(0, wordLen).toLowerCase()) {
							textField.value += usersInChat[i].substr(wordLen, usersInChat[i].length-wordLen).toLowerCase() + " ";
							break;
						}
						i++;
					}
				}
		  	}
			void(0);
		break;

		case 13: /* Return key */
			sendData();
		break;
		
		case 37: /* Left Arrow */
			// 
		break;
		
		case 38: /* Up Arrow */
			stringBufferActual = document.getElementById('textInput').value;
			document.getElementById('textInput').value = stringBuffer;
		break;	
		
		case 39: /* Right Arrow */
			//
		break;
		
		case 40: /* Down Arrow */
			document.getElementById('textInput').value = stringBufferActual;
		break;
		
		default:
			data = document.getElementById('textInput').value;
			if (data.substr(0, 1) == "/") {
				ajFetch('?L=chat.comhelper&chromeless=1&str=' + urlEncode(data), 'commandHelper', false, 0);
				document.getElementById('textInput').focus();
			}
			
			else {
				
				var helper = document.getElementById('commandsHelper');
				helper.style.visibility = 'hidden';
				helper.innerHTML = '';
				
				document.getElementById('textInput').focus();
			}
		break;
	}
}

/* Send data from textInput element */
function sendData() {
	data = document.getElementById('textInput').value;

	/* Don't act if data is null */
	if (data != null && trim(data) != '') {

		stringBuffer = data;

		//data = data.replace('+', '&#43');
		
		/* encode and send the channel (ch), encode and send the text content (txt) */
		ajFetch('?L=chat.dac&chromeless=1&pin=' + pin + '&sendChatData=' + urlEncode(data), 'appendChatContent', false, 0);

		/* Clear the textInput value */
		document.getElementById('textInput').value = '';
		
		/* Hide the command helper */
		setTimeout("document.getElementById('commandsHelper').style.visibility = 'hidden';", 500);
		
	}
}

/* Scrolls the content div to its end */
function scrollDown() {
	content = document.getElementById('chatContent');
	content.scrollTop = content.scrollHeight;
}

function detachChat() {
	ajStop('appendChatContent');
	document.getElementById('detachedInfoDiv').style.visibility = 'visible';
	document.getElementById('chatBlockWrapper').style.visibility = 'hidden';	
	
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open('?L=chat.chatroom&channel=general&chromeless=1', '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=500,height=700');");
}

var selectedUser = "";

function pickUser(username) {

	var i=0;
	while (i < usersInChat.length) {
    	if (usersInChat[i] != username) {
			document.getElementById('nickEntityContainer_' + usersInChat[i]).className = 'chatNickEntity';
		}
		i++;
	}
	document.getElementById('nickEntityContainer_'+username).className = 'selectedChatNickEntity';
	selectedUser = username;
}

function actUser() {
	if (selectedUser != "") {
		var action = document.getElementById('userAction').value;
		document.getElementById('textInput').value = '/' + action + " " + selectedUser;
		sendData();
	}
	document.getElementById('userAction').selectedIndex = 0;
}

function commandHelper(dataContent) {

	var helper = document.getElementById('commandsHelper');

	if (trim(dataContent) != "") {
		
		/* Show the helper */
		helper.innerHTML = dataContent;
		
		helper.style.position = 'absolute';
		helper.style.top =  (findPosY(document.getElementById('textInput'))+3)+"px";
		helper.style.left = (findPosX(document.getElementById('textInput'))+2)+"px";
		helper.style.visibility = 'visible';
	}
	
	else {
		helper.style.visibility = 'hidden';
		helper.innerHTML = '';
	}
}
	
/* ---------------------- AJAX ------------------------- */

/* Ajax function class */
/* Declarations */
var arAjx = new Array(1);
var arStops = new Array;



/* ajFetch function */
function ajFetch(url, destination, cycle, delay, noloading) {
	
	/* Execution timer */
	var timerOne = new Date();
	floatInt = timerOne.getTime();
	//
	
	var curInstance;
	if (cycle == null) {
		cycle = false;	
	}
	if (noloading == null) {
		noloading = false;	
	}
	
	if (arAjx.length == 1) {
		curInstance = 1;
		arAjx[1] = new Ajax;
	} else {
		var found = false;
		for (i=1;i<arAjx.length;i++) {
			if (arAjx[i].Is_Free()) {
				curInstance = i;
				found = true;
			}
		}
		
		if (!found) {
			arAjx.push(new Ajax);
			curInstance = arAjx.length;
			arAjx[curInstance] = new Ajax;
		}
	}
	
	if (noloading) { arAjx[curInstance].Set_Loading(false); }
	
	if (paused) {
		arAjx[curInstance].HTTP_Get(url+"&pause=1", destination);
	} else {
		arAjx[curInstance].HTTP_Get(url, destination);
	}
	
	if (arStops[destination] != true) {
		if (cycle) {
			setTimeout("ajFetch('"+url+"','"+destination+"',true,"+delay+");",delay);
		}
	} else {
		arStops[destination] = null;
	}
}

/* Ajax functions, objects, classes and callback */
function Ajax() {
	/* Declarations */
	/* Public methods */
	this.HTTP_Get = HTTP_Get;
	this.Is_Free = Is_Free;
	this.Set_Loading = Set_Loading;
		
	/* Private variables */
	var ajobj = XMLHTTP_object();
	var http_destobj = null;
	var free = true;
	var show_loading = true;

	/* Methods */
	function HTTP_Get(url, destination) {
		if (free && (url != null) && (destination != null) && ((ajobj.readyState == 0) || (ajobj.readyState == 4))) {
			http_destobj = destination;
			
			ajobj.open("GET", url, true);
			ajobj.onreadystatechange = HTTP_Get_CallBack;
			ajobj.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
			ajobj.send(null);
			free = false;
		} else {
			return false;
		}
	}
	
	/* Get CallBack (Handle received data) */
	function HTTP_Get_CallBack() {
		if (ajobj.readyState == 4) {
			var results = ajobj.responseText;
			
			if (typeof(results)=='string' && results != null && results != '') {
				/* Function callback evaluator */
				if (eval("typeof(" + http_destobj + ") == 'function'")) { 
					/* Function detected, pass data to function */
					eval(http_destobj + "(results);");
				} else {
					/* Not a function, pass data to the html object */
					if (typeof document.getElementById(http_destobj).innerHTML != "undefined") {
						document.getElementById(http_destobj).innerHTML = results;
					}
				}
			}
			free = true;
		}
	}
	
	/* Helpers functions */
	function Is_Free() {
		return free;	
	}
	
	function Set_Loading(value) {
		show_loading = value;
	}
	
	/* AJAX OBJECT */
	function XMLHTTP_object() {
	  var xmlhttp;
	  /*@cc_on
	  @if (@_jscript_version >= 5)
		try {
		  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
		  try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		  } catch (E) {
			xmlhttp = false;
		  }
		}
	  @else
	  xmlhttp = false;
	  @end @*/
	  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		try {
		  xmlhttp = new XMLHttpRequest();
		} catch (e) {
		  xmlhttp = false;
		}
	  }
	  return xmlhttp;
	}
}

function ajStop(destination) {
	arStops[destination] = true;
}

/* --------------------- HELPERS ----------------------- */

/* Set Selection */
function setSelectionRange(input, selectionStart, selectionEnd) {
  if (input.setSelectionRange) {
    input.focus();
    input.setSelectionRange(selectionStart, selectionEnd);
  }
  else if (input.createTextRange) {
    var range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  }
}

/* Object position gizmo */
function findPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}
	else if (obj.x) curleft += obj.x;
	return curleft;
}

function findPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		curtop += obj.offsetHeight;
		while (obj.offsetParent) {
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	else if (obj.y) {
		curtop += obj.y;
		curtop += obj.height;
	}
	return curtop;
}
	
/* Array pop gizmo */
function array_pop(array, itemname) {
	var i = 0;
	while (i < array.length) {
		if (array[i] == itemname) array.splice(i, 1);
		i++;
  	}
	return array;
}

/* URLencode/decode helper */
function urlDecode(str){
    str=str.replace(new RegExp('\\+','g'), ' ');
   	return unescape(str);
}
	
function urlEncode(str){
	str = escape(str);
	str=str.replace(new RegExp('\\+','g'), 'PPP910918271');
	str=str.replace(new RegExp('%20','g'), '+');
	return str;
}

/* Base64 Helpers */
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
function encode64(input) {
	if (input != null && input != '' && input != ' ') {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;

		do {
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);

			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;

			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}

			output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + 
			keyStr.charAt(enc3) + keyStr.charAt(enc4);
		} while (i < input.length);
   		
		return output;
	}
}
function decode64(input) {
	var output = "";
	var chr1, chr2, chr3;
	var enc1, enc2, enc3, enc4;
	var i = 0;

	input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

	do {
		enc1 = keyStr.indexOf(input.charAt(i++));
		enc2 = keyStr.indexOf(input.charAt(i++));
		enc3 = keyStr.indexOf(input.charAt(i++));
		enc4 = keyStr.indexOf(input.charAt(i++));

		chr1 = (enc1 << 2) | (enc2 >> 4);
		chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
		chr3 = ((enc3 & 3) << 6) | enc4;

		output = output + String.fromCharCode(chr1);

		if (enc3 != 64) {
			output = output + String.fromCharCode(chr2);
		}
		if (enc4 != 64) {
			output = output + String.fromCharCode(chr3);
		}
	} while (i < input.length);
	
	return output;
}

/* trim helper */
function trim(str) {
	/* Removes white spaces on the beginning and on the end of a string */
	if (str != null && str != '') {
		while (str.charAt(0) == ' ')
			str = str.substring(1);
		while (str.charAt(str.length - 1) == ' ')
			str = str.substring(0, str.length - 1);
	}
	return str;
}
