//EDITABLE

	var get_posts_timeout = 2000;
		//timeout in milli-seconds to wait before requesting new posts.
		//note: this timeout applies AFTER the server's get_posts response, so if you set this variable @ 500ms,
		//you should think of the request time of the server which will be added to the timeout.
		//example: if the server responsed in 200ms, the new posts will be requested after 200ms + get_posts_timeout, which will be 700ms.
		//so 500ms may result in 3 requests per 2 seconds. (3x 500ms timeout + 3x ~180ms request time)
	
	var ping_interval = 8000;
		//interval to ping to the server, used for the list-of-online-users.
	
	var get_posts_auto_timer_enabled = true;
		//auto-adjust get_posts_timeout based on chat activity.
		//strongly recommended! get_posts_timeout will be used as starting value.
	
	var get_posts_auto_timer_minimum = 500;
	var get_posts_auto_timer_maximum = 4000;
		//min and max milliseconds the get_posts_auto_timer can set.
		//The get_posts_timeout will never be lower than minimum and never be higher than maximum
    
    var no_login_timer_multiplier = 0.5;
        //the multiplier to increase the speed of the get_posts when not logged in.

	var interval_increasing_multiplier = 0.5;
		//the multiplier to INCREASE the speed of the get_posts. Will DECREASE the timeout faster if value is INCREASED.
		//increasing this variable will lower the timeout faster when chat is active.
		//note: multiplier cannot be negative. 0.5 = 50% of original speed, 2 = 200% of original speed.
	var interval_decreasing_multiplier = 0.1;
		//the multiplier to DECREASE the speed of the get_posts. Will INCREASE the timeout faster if value is INCREASED.
		//increasing this variable will raise the timeout faster when chat is inactive.
		//note: multiplier cannot be negative. 0.5 = 50% of original speed, 2 = 200% of original speed.
	
	var autoscroll_enabled = true;
		//auto scroll to bottom, like in Windows Live Messenger.
	
	var allow_multiple_send_post_threads = true;
		//allow users to send posts without having to wait for a "message send succesfully" response for the server,
		//since this response may take up to 60 seconds if the server doesn't respond.
	
	var scroll_to_bottom_on_post = true;
		//scroll to bottom when user send a message.
	
	var request_new_posts_on_send_post = true;
		//new posts will be requested right after the user has send a post. Used to show the user his own post directly in stead of the delay of X milliseconds.
	
	var temp_username = '???';
		//shown name from unknown usernames. The chat will request the username from the database and replace it.
	
	var system_name = 'System';
		//shown name of system messages.
	
	var root_element = 'page';
		//id of element to put al the chat elements in.
		//only edit if you know what you're doing.
		//SIZE OF CHAT-ELEMENTS CAN BE EDITED IN "./ajax/livechat.php"!
	
	var messages_history = 40;
		//max number of messages to show in the chat. 0 = no limit.
		
		//user statusses. Limit of 256 elements including the first blank one.
	var user_status_array = new Array(''
		,'online'
		,'away'
		,'brb'
	);
	
	
//NON EDITABLE

	var chat_last_message_id = 0;//INT containing the id of the last message.
	var chat_cache_storage_settings = '';//string containing the cache settings of the room.
	var get_posts_timer;//timer variable of get_posts function.
	var sending_post = false;//true: a message is being send. false: script is ready to send a new message.
	var shift_down = false;//true: user is holding shift key. false: user released the shift key.
	var chat_users = new Array();//array containing information of all users.
	var chat_last_poster_id;//INT containing the last poster id. Used to group messages
	var chat_message_list_fill_id = 0;//INT containting the <ul> tag's id to put the message in.
	var messages_count = 0;
	var no_messages = 0;
	var floating_get_posts_timeout = get_posts_timeout;
	var user_status = 1;
	var list_of_users = new Array();//array containing online users. (id,status,info)
	var room = -1;
	var USTAT_UNCHANGED = 0;
	var USTAT_NEW = 1;
	var USTAT_STATUS_CHANGED = 2;
	var USTAT_LEFT = 3;
	var loggedin = 0;
	var firstLOU = true;
	var no_msg_count = true;
	var popups = new Array();
	var chat_modding_allowed = false;
	var title_notify_active = false;

function init() {
	elem(root_element).innerHTML = '<center><h1>Uw gegevens worden opgehaald...</h1><p>Het ophalen van de data hoort niet langer te duren dan 60 seconden</p></center>';
	add_user(-1,temp_username);//username voor users die nog niet geladen zijn.
	add_user(0,system_name);//username voor systeem berichten.
	ajax('livechat','init',null,null);
}

function ping() {
	ajax('livechat','ping&b=list_of_users','cache_storage='+chat_cache_storage_settings+'&loggedin='+loggedin+'&status='+user_status);
}

function get_posts(ms) {
	clearTimeout(get_posts_timer);
	if(ms) {
		get_posts_timer = setTimeout('get_posts(0)',ms);
	} else {
		ajax('livechat','posts','index='+chat_last_message_id+'&cache_storage='+chat_cache_storage_settings,'get_posts('+get_posts_timeout+');get_post_auto_timer();');
	}
}

function options() {
	var html = '';
	html += '<div style="vertical-align:middle;">';
	html += '<div>';
		html += '<input type="checkbox" checked="checked" id="window_close_on_ban'+room+'"/>';
		html += '<span style="font-size:10px;">auto-close window</span>';
	html += '</div>';
	if(chat_modding_allowed) {
		html += '<div>';
		html += '<button onclick="options_autoclose();ban_window();">(un)ban</button>';
		html += '</div>';
	}
	html += '</div>';
	popup_new('Options',html,'options');
}

function options_autoclose() {
	if(checkbox_checked('window_close_on_ban'+room)){
		remove(elem('popup'+room+'_options'));
	}
}

function ban_window() {
	var html = '';
	for(var a=3;a<chat_users.length;a++) {
		html += '<div>';
			html += '<button onclick="ajax(\'livechat\',\'ban\',\'user_id='+chat_users[a][0]+'\');">ban</button>';
			html += '<button onclick="ajax(\'livechat\',\'unban\',\'user_id='+chat_users[a][0]+'\');">unban</button>';
			html += chat_users[a][1];
		html += '</div>';
	}
	if(chat_users.length>3) {
		html += '<div>Or enter a username to (un)ban:</div>';
	}
	html += '<div>';
		html += '<input type="text" id="ban_username'+room+'"/>';
		html += '<button onclick="ajax(\'livechat\',\'ban\',\'username=\'+encodeURIComponent(elem(\'ban_username\'+room).value));">ban</button>';
		html += '<button onclick="ajax(\'livechat\',\'unban\',\'username=\'+encodeURIComponent(elem(\'ban_username\'+room).value));">unban</button>';
	html += '</div>';
	html += '<button onclick="remove(elem(\'popup'+room+'_banwindow\'));">sluiten</button>';
	popup_new('(un)ban user(s)',html,'banwindow');	
}

function popup_new(title,content,id,width,height) {
	var popupid = elem('popups'+room).childNodes.length;
	var newpopup = document.createElement('div');
	newpopup.style.position = 'absolute';
	newpopup.id = 'popup'+room+'_'+id;
	if(width) {
		newpopup.style.width = width + 'px';
	}
	if(height) {
		newpopup.style.height = height + 'px';
	}
	newpopup.style.zIndex = '1';
	newpopup.style.border = '1px solid #888';
	newpopup.style.background = '#000';
	newpopup.innerHTML = '<div style="height:16px;background:#000;color:#fff;margin:1px;"><div style="float:left;">'+title+'</div><img onclick="remove(elem(\'popup'+room+'_'+id+'\'));" style="float:right;" src="img/min.png"/></div>'+content;
	elem('popups'+room).appendChild(newpopup);
	newpopup.style.margin = ((elem(root_element).offsetHeight-newpopup.offsetHeight)/2)+'px 0px 0px '+((elem(root_element).offsetWidth-newpopup.offsetWidth)/2)+'px';
}

function register() {
	var html = '';
	html += '<form onsubmit="try{submit_register();}catch(e){alert(\'Error registering: \'+e);}return false;">';
		html += '<h2>Username:</h2><input type="text" id="r_username"/>';
		html += '<h2>Password:</h2><input type="password" id="r_password1"/>';
		html += '<h2>Password (again):</h2><input type="password" id="r_password2"/>';
		html += '<input type="submit" value="Register"/>';
	html += '</form>';
	popup_new('Registreren',html,'register',200);
}

function get_post_auto_timer() {
	if(no_msg_count) {
		no_msg_count = false;
		return;
	}
	if(messages_count==0) {
		no_messages ++;
		floating_get_posts_timeout += (no_messages*50+(no_messages-1)*25)*interval_decreasing_multiplier;
	} else {
		no_messages = 0;
		floating_get_posts_timeout -= (messages_count*50+(messages_count-1)*25)*interval_increasing_multiplier;
	}
	
	if(floating_get_posts_timeout < get_posts_auto_timer_minimum) {
		floating_get_posts_timeout = get_posts_auto_timer_minimum;
	} else if(floating_get_posts_timeout > get_posts_auto_timer_maximum) {
		floating_get_posts_timeout = get_posts_auto_timer_maximum;
	}
	
	get_posts_timeout = parseInt(floating_get_posts_timeout*(loggedin?1:no_login_timer_multiplier));
	
	messages_count = 0;
}

function get_user_local_id(id) {
	for(var a=0;a<chat_users.length;a++) {
		if(chat_users[a]!=false && chat_users[a][0]==id) {
			return a;
		}
	}
	return 0;
}

function inputcheck(e,DorU) {
	var key;
	if(window.event) {
		key = e.keyCode;
	}
	else if(e.which) {
		key = e.which;
	}
	if(key==16 && DorU=='down') {
		shift_down = true;
	} 
	if(key==16 && DorU=='up') {
		shift_down = false;
	}
	if(shift_down==false && key==13 && DorU=='down') {
		send_post();
		return false;
	}
	if(shift_down==false && key==13 && DorU=='press') {
		send_post();
		return false;
	}
}

function send_post() {
	if(!allow_multiple_send_post_threads && sending_post){return false;}
	var message = elem('message').value.replace(/^\s*/,'').replace(/\s*$/,'');
	if(message.length > 0) {
		if(!allow_multiple_send_post_threads) {
			sending_post = true;
			elem('sendpostsubmit').value = 'wachten';
		}
		elem('message').value = '';
		var alt_request = '';
		if(request_new_posts_on_send_post) {
			alt_request = 'get_posts(0);';
		}
		ajax('livechat','post','message='+encodeURIComponent(message),'allow_send_post();'+alt_request);
	}
	if(scroll_to_bottom_on_post) {
		scroll_to_bottom();
	}
}

function allow_send_post() {
	if(allow_multiple_send_post_threads) {return false;}
	sending_post=false;
	elem('sendpostsubmit').value = 'Send';
}

function logout() {
	if(!confirm('Are you sure to logout?')) {return false;}
	ajax('livechat','logout');
}

function login() {
	if(elem('password') && elem('username')) {
		ajax('livechat','login','username='+encodeURIComponent(elem('username').value)+'&password='+encodeURIComponent(elem('password').value));
		elem('chatform1').innerHTML = 'Loggin in...';
	} else {
		alert('Element "password" and/or "username" is not available.');
		return false;
	}
}

function system_message(msg) {
	if(autoscroll_enabled) {
		var autoscroll = ((elem('chatmsg1').scrollTop+elem('chatmsg1').offsetHeight+40)>elem('chatmsg1').scrollHeight);
	}
	chat_last_poster_id = -2;
	poster = chat_users[get_user_local_id(0)];
	
	var element = document.createElement('div');
	element.className = 'system_message';
	element.innerHTML = '<span class="system_says"><span class="system_name"><span class="username'+poster[0]+'">'+poster[1]+'</span></span> message: </span>'+msg;
	elem('chatmsg1').appendChild(element);
	
	clear_history();
	
	if(autoscroll_enabled && autoscroll) {
		scroll_to_bottom();
	}
}

function clear_history() {
	if(!messages_history) {return;}
	
	var history_messages = document.getElementById('chatmsg1').getElementsByTagName('li');
	
	var deleted_messages = 0;
	while(history_messages.length > messages_history+deleted_messages) {
		remove(history_messages[deleted_messages]);//verwijder LI element.
		deleted_messages++;
	}
	if(deleted_messages) {
		var history_lists = document.getElementById('chatmsg1').getElementsByTagName('ul');
		
		for(var a=0;history_lists.length>a;a++) {
			if(history_lists[a].childNodes.length == 0) {
				remove(history_lists[a]);
			}
		}
		
	}
	
	var history_usersays = document.getElementById('chatmsg1').childNodes;
	
	var a=0;
	while(history_usersays[a+1]
	&& history_usersays[a+1].nodeName == 'DIV') {
		if(history_usersays[a+1].nodeName == 'DIV'
		&& history_usersays[a].nodeName == 'DIV') {
			remove(history_usersays[a]);
		}
		a++;
	}
}

function add_message(id,poster,time,msg) {
	if(chat_last_message_id>=id) {
		return;
	}
	if(autoscroll_enabled) {
		var autoscroll = ((elem('chatmsg1').scrollTop+elem('chatmsg1').offsetHeight+40)>elem('chatmsg1').scrollHeight);
	}
	var input_poster = poster;
	if(!no_msg_count) {
		messages_count++;
	}
	if(chat_last_poster_id!=poster) {
		if(get_user_local_id(poster)==0) {
			request_user(poster);
		}
		
		chat_last_poster_id = poster;		
		poster = chat_users[get_user_local_id(poster)];
		chat_message_list_fill_id++;
		
		var element = document.createElement('div');
		element.className = 'user_says';
        
        time = time.replace(/^\S+\s+/i, "");
        time = time.replace(/\:\d+$/i, "");
        
		element.innerHTML = '<span class="user_name"><span class="username'+chat_last_poster_id+'">'+poster[1]+'</span></span> says: <span class="post_time">('+time+')</span>';
		elem('chatmsg1').appendChild(element);
		
		var element = document.createElement('ul');
		element.style.margin = '0px';
		element.className = 'user_message_list';
		element.style.padding = '0px 0px 0px 20px';
		element.id = 'list'+room+'_'+chat_message_list_fill_id;
		elem('chatmsg1').appendChild(element);
	}
	
	var element = document.createElement('li');	
	element.id='msg'+room+'_'+id;
	element.innerHTML = msg;
	element.className="user_message"
	document.getElementById('list'+room+'_'+chat_message_list_fill_id).appendChild(element);
	
	chat_last_message_id = id;
	
	clear_history();
	
	if(autoscroll_enabled && autoscroll) {
		scroll_to_bottom();
	}
}

function submit_register() {
	var error = '';
	if(!elem('r_username').value.match(/^[a-z0-9_-]{3,20}$/i)) {
		error += '\n    -Username invalid:\n      Username should contain 3 up to 20 alpha-numeric characters.';
	}
	if(elem('r_password1').value != elem('r_password2').value) {
		error += '\n    -Passwords do not match.';
	}
	if(!elem('r_password1').value.match(/^.{4,32}$/)) {
		error += '\n    -Passwords should contain at least 4 characters.';		
	}
	if(error.length > 0) {
		alert('ERROR:\n'+error);
		return false;
	}
	ajax('livechat','register','username='+encodeURIComponent(elem('r_username').value)+'&password='+encodeURIComponent(elem('r_password1').value));
}

function userstatus_select_fill(elementid) {
	for(var a=1;a<user_status_array.length;a++) {
		
		var option=document.createElement('option');
		option.text = user_status_array[a];
		option.value = a;
		option.style.fontSize = '10px';
		
		try {
			elem(elementid).add(option,null);
		} catch(e) {
			elem(elementid).add(option);
		}
		
	}
}

function set_title(titleString) {
	try{document.title = titleString;}catch(e){}
	try{window.title = titleString;}catch(e){}
	try{document.getElementsByTagName('title')[0].innerHTML = titleString;}catch(e){}
}

function scroll_to_bottom() {
	if(elem('chatmsg1').scrollTop != elem('chatmsg1').scrollHeight) {
		if(!title_notify_active) {
			title_notify_active = true;
			set_title('\u203E\u203EEyeMJR Hardcore\u203E\u203E');
			setTimeout("set_title('__EyeMJR Hardcore__');",500);
			setTimeout("set_title('\u203E\u203EEyeMJR Hardcore\u203E\u203E');",1000);
			setTimeout("set_title('__EyeMJR Hardcore__');",1500);
			setTimeout("set_title('\u203E\u203EEyeMJR Hardcore\u203E\u203E');",2000);
			setTimeout("set_title('__EyeMJR Hardcore__');",2500);
			setTimeout("set_title('\u203E\u203EEyeMJR Hardcore\u203E\u203E');",3000);
			setTimeout("set_title('EyeMJR Hardcore');title_notify_active = false;",3500);
		}
		elem('chatmsg1').scrollTop = elem('chatmsg1').scrollHeight;
	}
}

function clear_LOU() {
	for(var a=0;a<list_of_users.length;a++) {
		if(list_of_users[a]!=null) {
			list_of_users[a][2] = USTAT_LEFT;
		}
	}
}

function online_user(user_id,user_status) {
	var changed = false;
	for(var a=0;a<list_of_users.length;a++) { //verander huidige status
		if(list_of_users[a]!=null) {
			if(list_of_users[a][0]==user_id) {
				if(!changed && list_of_users[a][1]!=user_status) {
					list_of_users[a][1]=user_status;
					list_of_users[a][2]=USTAT_STATUS_CHANGED;
					changed = true;
				} else if(!changed && list_of_users[a][1]==user_status) {
					list_of_users[a][2]=USTAT_UNCHANGED;
					changed = true;
				} else {
					list_of_users[a]=null;//double user
				}
			}
		}
	}
	if(!changed) { //voeg users toe
		changed = false;
		for(var a=0;a<list_of_users.length;a++) {
			if(!changed && list_of_users[a]==null) {
				list_of_users[a] = new Array(user_id,user_status,USTAT_NEW);
				changed = true;
			}
		}
		if(!changed) {
			list_of_users[list_of_users.length] = new Array(user_id,user_status,USTAT_NEW);
			changed = true;
		}
	}
}

function update_LOU() {
	for(var a=0;a<list_of_users.length;a++) {
		if(list_of_users[a]!=null) {
			if(list_of_users[a][2]==USTAT_NEW) {
				if(!elem('userelement'+room+'_'+list_of_users[a][0])) {
					var element = document.createElement('div');
					element.className = 'user_LOU';
					element.id = 'userelement'+room+'_'+list_of_users[a][0];
					elem('chatlou1').appendChild(element);
				}
				elem('userelement'+room+'_'+list_of_users[a][0]).innerHTML = '<span class="username'+list_of_users[a][0]+'">'+get_username(list_of_users[a][0])+'</span> <span class="user_status_all" id="userstatus'+room+'_'+list_of_users[a][0]+'"><span class="user_status'+list_of_users[a][1]+'">'+user_status_array[list_of_users[a][1]]+'</span></span>';
				
				if(!firstLOU) {
					system_message('<span class="username'+list_of_users[a][0]+'">'+get_username(list_of_users[a][0])+'</span> ontrack.');
				}
				
			} else if(list_of_users[a][2]==USTAT_LEFT) {
				elem('userelement'+room+'_'+list_of_users[a][0]).innerHTML = '';
				
				if(!firstLOU) {
					system_message('<span class="username'+list_of_users[a][0]+'">'+get_username(list_of_users[a][0])+'</span> offtrack.');
				}
				
				list_of_users[a] = null;
			} else if(list_of_users[a][2]==USTAT_STATUS_CHANGED) {
				elem('userstatus'+room+'_'+list_of_users[a][0]).innerHTML = '<span class="user_status'+list_of_users[a][1]+'">'+user_status_array[list_of_users[a][1]]+'</span>';
			}
		}
	}
	firstLOU = false;
}

function get_username(userId) {
	if(!get_user_local_id(userId)) {
		request_user(userId);
	}
	return chat_users[get_user_local_id(userId)][1];
}

function update_username(userId) {
	if(!get_user_local_id(userId)) {
		request_user(userId);
		return false;
	}
	var elements = document.getElementById(root_element).getElementsByTagName('div');
	for(var a=0;a<elements.length;a++) {
		if(elements[a].className.substr(0,8)=='username' && elements[a].className.substr(8)==userId) {
			elements[a].innerHTML = chat_users[get_user_local_id(userId)][1];
		}
	}
	var elements = document.getElementById(root_element).getElementsByTagName('span');
	for(var a=0;a<elements.length;a++) {
		if(elements[a].className.substr(0,8)=='username' && elements[a].className.substr(8)==userId) {
			elements[a].innerHTML = chat_users[get_user_local_id(userId)][1];
		}
	}
}

var requested_users = new Array();
function request_user(id) {
	var ignore;
	for(var a=0;a<requested_users.length;a++) {
		if(requested_users[a]==id) {
			ignore = true;
		}
	}
	if(!ignore) {
		requested_users[requested_users.length] = id;
		ajax('livechat','userinfo','id='+id);
	}
}

function add_user(userId,username) {
	if(get_user_local_id(userId)) {return;}
	var a = 0;
	while(a < chat_users.length && chat_users[a]!=false) {
		a++;
	}
	chat_users[a] = new Array(userId,username);
	update_username(userId);
}
