var global_cg_ajax_count = 0;
var global_chat_pm_received_time = 0;
var global_chat_last_received_time = 0;
var global_chat_time_between_popups_min = 10;
var global_support_access = false;
if (typeof rootdir == "undefined")
{
var rootdir = "/"; // fail safe.
}



var global_window_focused = true;
function CGonBlur() {
global_window_focused = false;
};
function CGonFocus(){
global_window_focused = true;
handle_cg_events_on_focus();
};

if (/*@cc_on!@*/false) { // check for Internet Explorer...
	document.onfocusin = CGonFocus;
	document.onfocusout = CGonBlur;
} else {
	window.onfocus = CGonFocus;
	window.onblur = CGonBlur;
}


var global_popop_ajax_notifications_to_do = "";
function handle_cg_events_on_focus()
{
if(global_popop_ajax_notifications_to_do != "")
	{
cg_handle_ajax_popup_notification(global_popop_ajax_notifications_to_do);
global_popop_ajax_notifications_to_do = "";
	}

}





function popUp(id)
{
return false;
}
function InstantMessage(id, name)
{
if(userid <= 0)
	{
alert("Login to use the instant message feature");
return false;
	}
if(id == userid)
	{
alert("Cannot instant message yourself");
return false;
	}

if(isNaN(id) || id <= 0)
	{
return false;
	}
	if (typeof name == "undefined")
	{
return false;
	}


	if (typeof chatWindow != "undefined" && typeof chatroom_enabled != "undefined" && name.length > 0)
	{
			if(chatroom_enabled == false)
			{
			chatWindow.open();
setTimeout(function() {createChannel('PM', name, 'PM_' + id, 0, 0, 'user', 'active'); }, 650); // allow time for chatroom to open and initialize.
setTimeout(function() {make_channel_active('PM_' + id); }, 950); // allow time for chatroom to open and initialize.



			}
			else
			{
createChannel('PM', name, 'PM_' + id, 0, 0, 'user', 'active');
			}

	}
return false;
}

var global_update_CG = true; // change this to false at anytime to cancel recurring background updates.
var global_next_allowed = 0;


var global_update_cybergamer_last_done_time = 0;
var global_next_valid_update_time = 0;
function UpdateCyberGamer(do_update)
{

if(global_next_valid_update_time > timenow())
	{
if(global_update_CG == true && do_update == 1)
{
var up=setTimeout("UpdateCyberGamer(1)", global_updatetimermain);
}
return false;
	}


global_updatetimermain = global_updatetimermain + 500; // increase each query.
if(global_updatetimermain > 695000)
{
global_updatetimermain = 695000; // max.
}

if(global_update_CG == true && do_update == 1)
{
var up=setTimeout("UpdateCyberGamer(1)", global_updatetimermain);
}
var test_difference_global = timenow() - global_update_cybergamer_last_done_time;
if(test_difference_global < 4)
{
return false; // already updated in the last few seconds, do not do again regardless.
}
var check_cook = readCookie("CyberGamerOwns");
if(check_cook != '' && check_cook != null && check_cook != false && check_cook != 'undefined')
{
global_next_allowed = check_cook;
}
if(do_update == 1 && global_next_allowed > timenow()) // only cancel if it shouldnt be doing and it is a main timer one, but still schedule the next allowed one further into the future.
{
return false;
}
var next_t_p = (global_updatetimermain / 1000) - 2;
next_t_p = next_t_p + timenow();
createCookie("CyberGamerOwns",next_t_p,60);


var pug_plat_do = global_pug_platform;
var lfs_plat_do = global_lfs_platform;

var xmlHttp = new_connection();
if(xmlHttp)
{
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
var i=xmlHttp.responseText;
global_next_valid_update_time = 0;
if(i == '' || i == null || i == 'undefined' || i == false)
{
return;
}


	var json_content = i;
	if(json_content != "")
	{
		var json_arr = false;
		try
		{
		json_arr = JSON.parse(json_content);
		}
		catch (e)
		{

		}

		if(json_arr != false && isset(json_arr['ajax_notifications']))
		{
			if(global_window_focused == true)
			{
			cg_handle_ajax_popup_notification(json_arr['ajax_notifications']);
			}
			else
			{
			global_popop_ajax_notifications_to_do = global_popop_ajax_notifications_to_do + json_arr['ajax_notifications'];
			}
			cg_handle_load_time(json_arr['loadtime']);
		}
	}



}
}
var url=rootdir+"xml/global.php?platform="+platform+"&game="+global_game+"&pug_platform="+pug_plat_do+"&lfs_platform="+lfs_plat_do+"&c="+global_cg_ajax_count;
url=url+"&chk="+Math.random();
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
global_cg_ajax_count++;
global_update_cybergamer_last_done_time = timenow();
global_next_valid_update_time = timenow() + 240;
}
}
if(userid != 0 && userid != '' && userid > 0)
{
var update_time_cg = global_updatetimermain + 95000; // extra delay for first query.

if(userid == 1 || userid == 2 || userid == 1337)
	{
update_time_cg = 3500;
setTimeout("UpdateCyberGamer(1)",update_time_cg); // move down one to re-enable for all.
	}
}


function cg_update_sb_buddies(content)
{
if(document.getElementById('cg_buddies_online_list'))
{
document.getElementById('cg_buddies_online_list').innerHTML=content;
}

}




function cg_handle_load_time(content)
{
if(content == "" || userid != 1)
	{
return false;
	}



if (typeof debug_content != "undefined" && global_cg_ajax_count < 25)
{
debug_content = debug_content + '<br /><b>AJAX #'+global_cg_ajax_count+':</b> ' + content + 's';
}

}


var global_cg_allowed_login_attempt = true;
function cg_process_login()
{
//if anything goes wrong, return true so that normal POST login is handled, otherwise return false allowing AJAX to handle login.

if(!document.getElementById("cg_log_in") || !document.getElementById("cg_log_pw"))
	{
return true; // allow FORM to process normally.
	}

if(document.getElementById("cg_log_in").value.length == 0 || document.getElementById("cg_log_pw").value.length == 0)
	{
return false; // dont allow login form to be submitted if username or PW is blank.
	}
if(document.getElementById("cg_log_in").value == "Username" || document.getElementById("cg_log_in").value == "Username..." || document.getElementById("cg_log_in").value == "Username:")
	{
return false; // dont allow login form to be submitted if username is username..
	}

if(global_cg_allowed_login_attempt == false)
	{
return false;
	}
global_cg_allowed_login_attempt = false; // do not allow another login attempt for short period.
setTimeout(function() { global_cg_allowed_login_attempt = true }, 1000);

var id_req = "cg_login_attempt_" + rand(99999); // unique ID.

cg_alert(id_req, "Attempting to login: <b>" + htmlentities(document.getElementById("cg_log_in").value) + "</b>", "CYBERGAMER NETWORK LOGIN", 0);



var post_parameters = "username="+encodeURIComponent(document.getElementById("cg_log_in").value)+"&password="+encodeURIComponent(document.getElementById("cg_log_pw").value); 


var xmlHttp = new_connection();
xmlHttp.open('POST', rootdir+"xml/cg_process_login.php?handle_ajax_login=1&chk="+Math.random(), true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function()
{
	if (xmlHttp.readyState == 4)
	{
	var response = xmlHttp.responseText;

if(response == "login_ipauth")
		{
cg_alert(id_req, "Login Successful, but IP not authenticated.", "CYBERGAMER NETWORK LOGIN", 8);
alert("You are logging in from a new IP Address.\nPlease check your email account for an \"IP Authentication Request\" email and follow the link inside it.");
window.location=rootdir+"ipauth.php?login_attemped=1";
		}
	else if(response == "login_successful")
		{
cg_alert(id_req, "Login Successful", "CYBERGAMER NETWORK LOGIN", 0); // dont dissappear, so remains until logged in.
var pos = strpos(location.href, '#');
if(pos === false || isNaN(pos))
{
setTimeout(function() {window.location=window.location; }, 75); // reload page after very slight delay.
}
else
{
window.location=substr(location.href, 0, pos); // so browser reloads.
}
		}
		else
		{
cg_alert(id_req, "Login Failed...", "CYBERGAMER NETWORK LOGIN", 8);
		}
		return false;
	}

};
xmlHttp.send(post_parameters);






return false;
}



function cg_update_sb_pugbot(content, plat)
{

if(document.getElementById('cg_pugbot_active_list'))
{
document.getElementById('cg_pugbot_active_list').innerHTML=content;
pug_displaying_text(plat, "Displaying");
}

}





function CG_pugwindow_open(value)
{
var do_load = false;
if(document.getElementById("cg_pugbot_not_loaded"))
	{
do_load = true;
	}

if(do_load == false)
	{
return false;
	}

var pug_plat_do = global_pug_platform;
var xmlHttp = new_connection();
if(xmlHttp)
{
	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			var i=xmlHttp.responseText;
if(i != "")
			{
cg_update_sb_pugbot(i, pug_plat_do);
			}

			return false;
		}
	};

var url=rootdir+"xml/cg_pug_sb_content.php?pug_platform="+pug_plat_do;
url=url+"&chk="+Math.random();
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}

return false;
}





function CG_lfswindow_open(value)
{
var do_load = false;
if(document.getElementById("cg_lfs_not_loaded"))
	{
do_load = true;
	}

if(do_load == false)
	{
return false;
	}

var pug_plat_do = global_pug_platform;
var xmlHttp = new_connection();
if(xmlHttp)
{
	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			var i=xmlHttp.responseText;
if(i != "")
			{
if(document.getElementById('lfs_area_overall_content'))
{
document.getElementById('lfs_area_overall_content').innerHTML=i;
}
			}

			return false;
		}
	};

var url=rootdir+"xml/cg_lfs_sb_content.php?t=1";
url=url+"&chk="+Math.random();
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}

return false;
}












function cg_update_sb_lfs(content, plat)
{
cg_lfs_handle_content(content);
}








var last_ajax_popups_content = "";
function cg_handle_ajax_popup_notification(content)
{
content = trim(content);
if(content == "")
	{
return false;
	}

if(content == last_ajax_popups_content)
	{
return false;
	}
global_popop_ajax_notifications_to_do = ""; // ensure is empty.
last_ajax_popups_content = content;

var timer_delay = 25;
var timer_increase_by = 750;
var popup_type;
var popup_title;
var popup_text;
var temp_array;
var temp_data;

var cg_ajax_popups_array=content.split('|_|');
var previous_popup = "";
for (z=0; z < cg_ajax_popups_array.length; z++)
{

	var temp_data = cg_ajax_popups_array[z];
	if(trim(temp_data) != "" && temp_data != previous_popup)
	{
		previous_popup = temp_data;
		temp_array=temp_data.split('||');
		if(isset(temp_array[2])) // 0 = success/fail/normal - 1 = title, 2 = text.
		{

				popup_type = temp_array[0];
				popup_title = temp_array[1];
				popup_text = temp_array[2];
				
				if(popup_type == "NORMAL" && popup_title != "" && popup_text != "")
				{
	setTimeout("cg_alert('temp_' + rand(9999) + '_' + rand(9999), '"+addslashes(popup_text)+"', '"+addslashes(popup_title)+"', 11);", timer_delay);
				}
				else if( popup_type == "GOOD" && popup_title != "" && popup_text != "")
				{
	setTimeout("cg_alert('temp_' + rand(9999) + '_' + rand(9999), '"+addslashes(popup_text)+"', '"+addslashes(popup_title)+"', 7);", timer_delay);
				}
				else if(popup_type == "FAILED" && popup_title != "" && popup_text != "")
				{
	setTimeout("cg_alert('temp_' + rand(9999) + '_' + rand(9999), '"+addslashes(popup_text)+"', '"+addslashes(popup_title)+"', 9);", timer_delay);
				}
				timer_delay = timer_delay + timer_increase_by;

		}
	}

}





}



function cg_inbox_mark_all_read()
{
if(userid <= 0)
	{
return false;
	}

var xmlHttpch = new_connection();
if(xmlHttpch)
{
	xmlHttpch.onreadystatechange=function()
	{
		if(xmlHttpch.readyState==4)
		{
			var ret = xmlHttpch.responseText;
			if(ret == '' || ret == null || ret == 'undefined' || ret == false)
			{
			return false;
			}
				if(ret == 'success')
				{

				if(document.getElementById('cg_sb_mail_content'))
				{
					document.getElementById('cg_sb_mail_content').innerHTML='<div class="sb_block"><div class="noti mail">You have no new messages.<div>Go to your inbox to view old messages</div></div></div>';
					update_red_num_count(0, "cg_pm_alert_wrap", "cg_pm_alert_count");

					if(document.getElementById('cg_mark_all_read_href'))
					{
						document.getElementById('cg_mark_all_read_href').style.display="none";
					}

				}

				}
			return false;
		}
	};
var url=rootdir+"xml/mark_all_inbox_read.php?d=1";
url=url+"&chk="+Math.random();
xmlHttpch.open("GET",url,true);
xmlHttpch.send(null);
}
return false;


}


function cg_update_sb_mail(content)
{
if(content == "" || content == false)
	{
return false;
	}

var amount = trim(content.substr(0, 5));
amount = amount / 1;
var mail = content.substr(5);
if(mail == "")
	{
return false;
	}

if(document.getElementById('cg_sb_mail_content'))
{
document.getElementById('cg_sb_mail_content').innerHTML=mail;
}
update_red_num_count(amount, "cg_pm_alert_wrap", "cg_pm_alert_count");


}


function update_red_num_count(amount, wrapping_id, main_id)
{
//PM: wrap = cg_pm_alert_wrap and main = cg_pm_alert_count


amount = amount / 1;
if(!document.getElementById(main_id))
	{
return false;
	}
if(!document.getElementById(wrapping_id))
{
return false;
}
var current_count = 0;

current_count = trim(document.getElementById(main_id).innerHTML) / 1;
if(current_count == 0 && amount > 0 && wrapping_id == "cg_pm_alert_wrap")
{
do_title_flash("Private Message Arrived");
}

if(amount > 0 && document.getElementById('cg_mark_all_read_href'))
{
document.getElementById('cg_mark_all_read_href').style.display="";
}


//setTimeout(function() {slide_opacity(id, start, finish); }, 150);




if(amount == "" || amount == 0 || amount <= 0)
	{
document.getElementById(wrapping_id).style.display="none";
	}
else
	{
document.getElementById(wrapping_id).style.display="";
	}


if(current_count != amount)
	{

var cc = 100; // initital
var inc = 100; //increase by.
setTimeout(function() { document.getElementById(main_id).style.fontSize="12px"; document.getElementById(main_id).style.height="19px"; }, cc); cc = cc + inc;
setTimeout(function() { document.getElementById(main_id).style.fontSize="13px"; document.getElementById(main_id).style.height="21px"; }, cc); cc = cc + inc;
setTimeout(function() { document.getElementById(main_id).style.fontSize="14px"; document.getElementById(main_id).style.height="23px"; }, cc); cc = cc + inc;

setTimeout(function() { document.getElementById(main_id).innerHTML=" " + amount + " "; }, cc); cc = cc + inc; // number changes just before middle one.
setTimeout(function() { document.getElementById(main_id).style.fontSize="15px"; document.getElementById(main_id).style.height="25px"; }, cc); cc = cc + inc; // middle.

setTimeout(function() { document.getElementById(main_id).style.fontSize="14px"; document.getElementById(main_id).style.height="23px"; }, cc); cc = cc + inc;
setTimeout(function() { document.getElementById(main_id).style.fontSize="13px"; document.getElementById(main_id).style.height="21px"; }, cc); cc = cc + inc;
setTimeout(function() { document.getElementById(main_id).style.fontSize="12px"; document.getElementById(main_id).style.height="19px"; }, cc); cc = cc + inc;

setTimeout(function() { document.getElementById(main_id).style.fontSize="10px"; document.getElementById(main_id).style.height="17px"; }, cc); cc = cc + inc; // back to original.

	}

}



var global_next_time_load_offline_buddies = 0;
function cg_load_offline_buddies()
{

if(global_next_time_load_offline_buddies < timenow())
{
global_next_time_load_offline_buddies = timenow() + 45;
var url = rootdir + "xml/load_buddies_list.php?offline=1";
url=url+"&chk="+Math.random();
ajax_load_url_put_in_innerhtml(url, "buddies_offline_target");
}
}


function popupmessages(content)
{
if(trim(content) != "DO")
{
return false;
}
	if (typeof chatWindow != "undefined")
	{
		if (typeof chatroom_enabled != "undefined")
		{
			if(chatroom_enabled == false && difference(timenow(), global_chat_last_received_time, global_chat_time_between_popups_min) == false)
			{
			global_chat_pm_received_time = timenow();
			global_chat_last_received_time = timenow();
			chatWindow.open();
			global_chat_time_between_popups_min = global_chat_time_between_popups_min + 20;
			}
		}
	}
return false;
}

var anim_done = 0;
function AnimateNewAction(newPMmsg, max_display)
{

if(!document.getElementById('loginproblem'))
{
if(document.getElementById('loginprobspot'))
{
document.getElementById('loginprobspot').innerHTML='<div id="loginproblem"></div>';
}
}
if(document.getElementById('loginproblem'))
{
var length = newPMmsg.length;
var what = '';
var cur = 0;
var curtimer = 0;
var time_inbet = 100;
var whatnew = '';
while(cur < length)
{
whatnew = newPMmsg.substr(cur, 1);
if(whatnew == '>')
{
whatnew = '&gt;';
}
what = what + whatnew;
if(whatnew != '' && whatnew != ' ')
{
curtimer = curtimer + time_inbet;
setTimeout("AnimateNewPMSet('"+what+"')",curtimer);
}
cur++;
}
}
anim_done++;
curtimer = curtimer + 1000;
if(anim_done < max_display)
{
setTimeout("AnimateNewAction('"+newPMmsg+"', "+max_display+");",curtimer);
}
else
{
curtimer = curtimer + 3000;
setTimeout("AnimateNewPMSet('"+newPMmsg+"')",curtimer);
anim_done = 0;
}
}
function AnimateNewPMSet(what)
{
if(document.getElementById('loginproblem'))
{
document.getElementById('loginproblem').innerHTML=what;
}
}


function cg_update_numbers(ar)
{
if(ar == '' || ar == null || ar == false || ar == 'undefined')
{
return;
}
var nar=ar.split('|');
	if(document.getElementById('myinboxcount') && document.getElementById('myinboxcount').innerHTML != nar[0])
	{
		if(nar[0] >= 0)
		{
	document.getElementById('myinboxcount').innerHTML=nar[0];
			if(document.getElementById('loginprobspot'))
			{
			AnimateNewAction('New PM Received >>', 4);
			}
		}

	}


if(document.getElementById('wa_total_members') && document.getElementById('wa_total_members').innerHTML != nar[1] && nar[1] != '' && nar[1] > 0)
{
	document.getElementById('wa_total_members').innerHTML=nar[1];
}

if(document.getElementById('wa_online_now') && document.getElementById('wa_online_now').innerHTML != nar[2] && nar[2] != '' && nar[2] > 0)
{
document.getElementById('wa_online_now').innerHTML=nar[2];
}

if(document.getElementById('sb_online_buddies_a') && document.getElementById('sb_online_buddies_a').innerHTML != nar[3] && nar[3] != '')
{
document.getElementById('sb_online_buddies_a').innerHTML=nar[3];
}
if(document.getElementById('sb_online_buddies_b') && document.getElementById('sb_online_buddies_b').innerHTML != nar[3] && nar[3] != '')
{
document.getElementById('sb_online_buddies_b').innerHTML=nar[3];
}


}

function handlept(val)
{
if(val == '' || val == null || val == false || val == 'undefined')
{
return;
}
if(val != ' ')
{
var todo = val.split(' ');
var z = 0;
for (z=0; z < todo.length; z++)
{
if(todo[z] != '')
{
handleptoutput(todo[z]);
}
}
}
}

function handleptoutput(work)
{
var stuff = work.split('_');
var ida = stuff[0];
var idb = ida+'F';
if(document.getElementById(ida) && document.getElementById(ida).innerHTML!=stuff[1])
{
document.getElementById(ida).innerHTML=stuff[1];
}
if(document.getElementById(idb) && document.getElementById(idb).innerHTML!=stuff[1])
{
document.getElementById(idb).innerHTML=stuff[1];
}
}

function new_connection() {

var A;

try {
A=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
A=new ActiveXObject("Microsoft.XMLHTTP");
} catch (oc) {
A=null;
}
}
if(!A && typeof XMLHttpRequest != "undefined")
A = new XMLHttpRequest();

return A;
}


function mstimenow()
{
var d = new Date();
return d.getTime();
}

function timenow()
{
return globaltimenow;
}


function updateglobaltimer()
{
globaltimenow = globaltimenow + 1;
setTimeout("updateglobaltimer()",1000);
}
setTimeout("updateglobaltimer()",1000);

function increasetime()
{
globaltimeamountval = globaltimeamountval + 60;
var b=setTimeout("increasetime()",60000);
}
var c=setTimeout("increasetime()",60000);

function time()
{
if (servertimeOBJ != null){
var myscriptTime = servertimeOBJ;

}

else{
var myscriptTime = new Date();
}
	var Hours;
	var Mins;
	var Time;
	Hours = myscriptTime.getHours();
	if (Hours >= 12) {
	Time = "pm";
	}
	else {
	Time = "am";
	}

	if (Hours > 12) {
	Hours -= 12;
	}

	if (Hours == 0) {
	Hours = 12;
	}

	Mins = myscriptTime.getMinutes();

	if (Mins < 10) {
	Mins = "0" + Mins;
	}

	var thetime = Hours + ":" + Mins + Time;
return thetime;
	}

function trim(str)
{
if(str == "")
	{
return "";
	}
return str.replace(/^\s+|\s+$/g,'');
}
function clearme(val, text)
{
if(val.value == text)
{
val.value='';
val.focus();
}
}

function submitchange(value, urlpart)
{
var xmlHttpch = new_connection();
if(xmlHttpch)
{
    xmlHttpch.onreadystatechange=function()
      {
      if(xmlHttpch.readyState==4)
        {
var ret = xmlHttpch.responseText;
if(ret == '' || ret == null || ret == 'undefined' || ret == false)
{
return;
}
if(ret.substr(0,8) == 'display_')
{
AnimateNewAction(ret.substr(8), 1);
return;
}
document.getElementById('leftcolumn').innerHTML=ret;
        }
      }
var url=rootdir+"xml/c.php"+urlpart+value;
url=url+"&chk="+Math.random();
    xmlHttpch.open("GET",url,true);
    xmlHttpch.send(null);
}
    return false;
}
function onoffstatus(status)
{
offline = status;
if(status == 1)
{
document.getElementById('userlogged').setAttribute("id", "userloggedoffline");
if(document.getElementById('useremail'))
{
document.getElementById('useremail').setAttribute("id", "useremailoffline");
}
document.getElementById('options').setAttribute("id", "optionsoffline");
}
else
{
document.getElementById('userloggedoffline').setAttribute("id", "userlogged");
var emailtotal = document.getElementById('myinboxcount').innerHTML;
if(document.getElementById('useremailoffline'))
{
if(emailtotal == 0)
{
document.getElementById('useremailoffline').setAttribute("id", "useremail");
}
}
document.getElementById('optionsoffline').setAttribute("id", "options");
}
document.getElementById('optionsdropdown').style.visibility = "hidden";
document.getElementById('optionsimage').setAttribute('src', rootdir+'images/optionsarrow.jpg');
var xmlHttpch = new_connection();
if(xmlHttpch)
{
var url=rootdir+"xml/s.php?do="+status;
url=url+"&chk="+Math.random();
xmlHttpch.open("GET",url,true);
xmlHttpch.send(null);
}
return false;
}


var currently_voting = 0;
function vote(poll_id, answer_id)
{

if(currently_voting == poll_id)
	{
//alert("Please wait before voting again...");
return false;
	}
currently_voting = poll_id;

if(global_poll_timer != false)
{
clearTimeout(global_poll_timer); // clear timer so that current content isnt replaced between now and vote placed.
}

var xmlHttp = new_connection();
if(xmlHttp)
	{
	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			var response = xmlHttp.responseText;
			currently_voting = 0;
			if(response == '' || response == null)
			{
			return;
			}
			if(response == 'cannot')
			{
			alert('You cannot vote in this poll');
			return;
			}
			else if(response == 'error')
			{
			alert('An error has occurred.');
			return;
			}
			else
			{
			handle_vote_saved(poll_id, answer_id, response);
			}
		}
	};



var url=rootdir+"xml/vote.php?id="+poll_id+"&a="+answer_id+"&game="+global_game+"&platform="+platform;
url=url+"&chk="+Math.random();
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}


return false;
}


function slide_widths(id, new_percent, id2)
{

	if(document.getElementById(id) && new_percent >= 0 && new_percent <= 100 && !isNaN(new_percent))
	{
		new_percent = (Math.round(new_percent * 100) / 100);
		var current_width = document.getElementById(id).style.width;
		if(current_width.substr(1) == "%")
		{
		current_width = current_width.substr(0,1);
		}
		else if(current_width.substr(2) == "%")
		{
		current_width = current_width.substr(0,2);
		}
		else if(current_width.substr(3) == "%")
		{
		current_width = current_width.substr(0,3);
		}
		else if(current_width.substr(4) == "%")
		{
		current_width = current_width.substr(0,4);
		}
		else if(current_width.substr(5) == "%")
		{
		current_width = current_width.substr(0,5);
		}
		else if(current_width.substr(6) == "%")
		{
		current_width = current_width.substr(0,6);
		}


		if(current_width >= 0 && current_width <= 100 && !isNaN(current_width))
		{

			current_width = (Math.round(current_width * 100) / 100);
			if(current_width == new_percent)
			{
			return false;
			current_width++;
			}
			else if(current_width < new_percent)
			{
				
				var test = new_percent - current_width;
				if(test > 8)
				{
				current_width = current_width + 8;
				}
				else if(test > 5)
				{
				current_width = current_width + 5;
				}
				else if(test > 3)
				{
				current_width = current_width + 3;
				}
				else if(test > 2)
				{
				current_width = current_width + 2;
				}
				else if(test < 1)
				{
					current_width = new_percent;
				}
				else
				{
				current_width++;
				}

			}
			else
			{

				var test = current_width - new_percent;
				if(test > 8)
				{
				current_width = current_width - 8;
				}
				else if(test > 5)
				{
				current_width = current_width - 5;
				}
				else if(test > 3)
				{
				current_width = current_width - 3;
				}
				else if(test > 2)
				{
				current_width = current_width - 2;
				}
				else if(test < 1)
				{
					current_width = new_percent;
				}
				else
				{
				current_width--;
				}

			}


current_width = (Math.round(current_width * 100) / 100);
var what = current_width + "" + "%";
if(document.getElementById(id2))
{
	if(current_width < 2)
	{
var what2 = current_width = (Math.round(current_width * 10) / 10) + "" + "%";
	}
	else
	{
var what2 = Math.round(current_width) + "" + "%";
	}

document.getElementById(id2).innerHTML=what2;
}
document.getElementById(id).style.width=what;
setTimeout("slide_widths('"+id+"', "+new_percent+", '"+id2+"')",120);
		}

	}

}



var global_poll_timer = false;
function handle_vote_saved(poll_id, answer_id, response)
{

var answer_html = 'pa_' + poll_id + '_' + answer_id;
var answer_html_cur_votes = 'pac_' + poll_id + '_' + answer_id;
var answer_html_cur_votes_display = 'pad_' + poll_id + '_' + answer_id;
var answer_html_cur_votes_word = 'pa_word_' + poll_id + '_' + answer_id;

var tot_votes_id = 'poll_tot_' + poll_id;
var poll_q = 'poll_q_' + poll_id;
var polls_area_id = 'cg_polls_area';
if(!document.getElementById(answer_html))
{
return false;
}
if(!document.getElementById(answer_html_cur_votes))
{
return false;
}
if(!document.getElementById(answer_html_cur_votes_display))
{
return false;
}
if(!document.getElementById(answer_html_cur_votes_word))
{
return false;
}
if(!document.getElementById(tot_votes_id))
{
return false;
}
if(!document.getElementById(poll_q))
{
return false;
}
if(!document.getElementById(polls_area_id))
{
return false;
}

var total_votes = document.getElementById(tot_votes_id).innerHTML / 1;
var current_answer_votes = document.getElementById(answer_html_cur_votes).innerHTML / 1;
var my_a_id = 'poll_mya_' + poll_id;
var new_percent_for_old = 0;
var my_answer_num = 0;
if(document.getElementById(my_a_id))
{
	my_answer_num = document.getElementById(my_a_id).innerHTML / 1;
	if(my_answer_num > 0 && my_answer_num <= 24 && !isNaN(my_answer_num))
	{
		var old_answer_html_cur_votes = 'pac_' + poll_id + '_' + my_answer_num;
		if(document.getElementById(old_answer_html_cur_votes))
		{
			var new_percent_for_old_val = document.getElementById(old_answer_html_cur_votes).innerHTML / 1;
new_percent_for_old_val--; // minus your vote.
			if(total_votes > 0) // always true?
			{
			var new_percent_for_old = (new_percent_for_old_val / total_votes) * 100;
			new_percent_for_old = (Math.round(new_percent_for_old * 100) / 100);
			}
		}
	}
}
else // new vote.
{
total_votes++;
}
current_answer_votes++;
var new_percent = 0;
if(total_votes > 0) // always true?
	{
var new_percent = (current_answer_votes / total_votes) * 100;
new_percent = (Math.round(new_percent * 100) / 100);
	}



//alert(total_votes);

if(document.getElementById(answer_html) && new_percent >= 0 && new_percent <= 100 && !isNaN(new_percent))
{
slide_widths(answer_html, new_percent, answer_html_cur_votes_display);
if(document.getElementById(answer_html_cur_votes_word))
	{
document.getElementById(answer_html_cur_votes_word).style.fontWeight="bold";
	}
}

if(document.getElementById(my_a_id))
{
my_answer_num = document.getElementById(my_a_id).innerHTML / 1;
if(my_answer_num > 0 && my_answer_num <= 24 && !isNaN(my_answer_num))
	{
var old_answer_html = 'pa_' + poll_id + '_' + my_answer_num;
var old_answer_html_cur_votes_display = 'pad_' + poll_id + '_' + my_answer_num;
if(document.getElementById(old_answer_html) && document.getElementById(old_answer_html_cur_votes_display))
		{
slide_widths(old_answer_html, new_percent_for_old, old_answer_html_cur_votes_display);
if(document.getElementById('pa_word_' + poll_id + '_' + my_answer_num))
	{
document.getElementById('pa_word_' + poll_id + '_' + my_answer_num).style.fontWeight="";
	}
		}
	}
}



//reload all of the other widths
var answer_count = 0;
var old_answer_html2;
var old_answer_html_cur_votes_display2;
var old_answer_html_cur_votes2;
var answer_percent_new
while(answer_count < 24)
	{
answer_count++;
if(answer_count != my_answer_num && answer_count != answer_id && total_votes > 0)
		{
old_answer_html2 = 'pa_' + poll_id + '_' + answer_count;
old_answer_html_cur_votes_display2 = 'pad_' + poll_id + '_' + answer_count;
if(document.getElementById(old_answer_html2) && document.getElementById(old_answer_html_cur_votes_display2))
		{
		old_answer_html_cur_votes2 = 'pac_' + poll_id + '_' + answer_count;
		if(document.getElementById(old_answer_html_cur_votes2))
		{
			answer_percent_new = document.getElementById(old_answer_html_cur_votes2).innerHTML / 1;
			if(total_votes > 0) // always true?
			{
			answer_percent_new = (answer_percent_new / total_votes) * 100;
			answer_percent_new = (Math.round(answer_percent_new * 100) / 100);
			}
			slide_widths(old_answer_html2, answer_percent_new, old_answer_html_cur_votes_display2);
			}
		}
		}

	}







if(document.getElementById(poll_q))
{
//document.getElementById(poll_q).innerHTML="Answer Saved, reloading polls...";
}







if(document.getElementById(polls_area_id))
{
if(global_poll_timer != false)
{
clearTimeout(global_poll_timer);
}
global_poll_timer = setTimeout(function() {handle_new_polls_display(polls_area_id, response)},3500);
}




}


function handle_new_polls_display(polls_area_id, response)
{
if(document.getElementById(polls_area_id))
	{
setOpacity(polls_area_id, 20);
document.getElementById(polls_area_id).innerHTML=response;
slide_opacity(polls_area_id, 20, 100);
	}
}

function slide_opacity(id, start, finish)
{
if(document.getElementById(id) && start <= finish)
{
	setOpacity(id, start);
	if(start >= finish)
	{
		return false;
	}
	start = start + 20;
	if(start > finish)
	{
		start = finish;
	}
	setTimeout(function() {slide_opacity(id, start, finish); }, 150);
}
return false;
}



function ptexpand(what, id)
{
var c = 0;
var vid;
if(what.getAttribute('name') == 'b')
{
what.setAttribute('src', rootdir+'images/minimise.jpg');
what.setAttribute('name', 'a');
while(c < 65)
{
c++;
vid = 'h'+id+'pr'+c;
unhidept(vid);
}
}
else
{
what.setAttribute('src', rootdir+'images/maximise.jpg');
what.setAttribute('name', 'b');
while(c < 65)
{
c++;
vid = 'h'+id+'pr'+c;
hidept(vid);
}
}
}

function unhidept(id)
{

if(document.getElementById(id))
{
var variable = document.getElementById(id);
variable.setAttribute('class', 'nothidden');
variable.style.visibility = "visible";
variable.style.position = "relative";
if(navigator.appName == "Microsoft Internet Explorer")
{
variable.style.display = "block";
}
else
{
variable.style.display = "table-row";
}
}
}



function display_show(id)
{
	if(document.getElementById(id))
	{
		document.getElementById(id).style.display = "";
	}
}

function display_hide(id)
{
	if(document.getElementById(id))
	{
		document.getElementById(id).style.display = "none";
	}
}



function displayhideshow(id)
{
	if(document.getElementById(id))
	{
		if(document.getElementById(id).style.display == "none")
		{
			document.getElementById(id).style.display = "";
		}
		else
		{
			document.getElementById(id).style.display = "none";
		}
	}
}



function hidemain(id)
{
if(document.getElementById(id))
{
var variable = document.getElementById(id);
variable.style.visibility = "hidden";
variable.style.display = "none";
variable.style._visibility = "hidden";
variable.style._position = "absolute";
}
}


function unhidemain(id)
{

if(document.getElementById(id))
{
var variable = document.getElementById(id);
variable.style.visibility = "visible";
variable.style.position = "relative";
if(navigator.appName == "Microsoft Internet Explorer")
{
variable.style.display = "block";
}
else
{
variable.style.display = "table-row";
}
}
}




function hidept(id)
{
if(document.getElementById(id))
{
var variable = document.getElementById(id);
variable.setAttribute('class', 'hidden');
variable.style.visibility = "hidden";
variable.style.display = "none";
variable.style._visibility = "hidden";
variable.style._position = "absolute";
}
}





function makevisible(x) 
{
if(document.getElementById(x))
{
var variable = document.getElementById(x);

variable.style.visibility = "visible";
variable.style.position = "relative";
}
}


function makehidden(x) 
{
if(document.getElementById(x))
{
var variable = document.getElementById(x);

variable.style.visibility = "hidden";
variable.style.position = "absolute";
variable.style.top = "0px";
variable.style.left= "0px";
}
}

function update_id_with(id, what)
{
if(document.getElementById(id))
{
document.getElementById(id).innerHTML=what;
}
}





function handle_thread_unsubscribe(threadid, what, do_extra)
{

var xmlHttp = new_connection();
if(xmlHttp)
{
xmlHttp.onreadystatechange=function()
{
	if(xmlHttp.readyState==4)
	{
	var res=xmlHttp.responseText;
if(res == '' || res == null || res == 'undefined')
{
return;
}
	var say = '';
	if(res == 'unsubscribed')
	{
say = 'You have been Unsubscribed';
	}
	else if(res.substr(0, 4) == 'good')
	{
res = res.substr(4);
if(res == 1)
{
say = 'You will be emailed after a reply';
}
else
{
say = 'You will be emailed after '+res+' replies';
}
	}


if(say != '')
{

var oldhtml;
if(what == 1)
{
oldhtml = '<a href="#" onclick="handle_thread_unsubscribe('+threadid+', 0, 0);return false;"><div class="typical_toolbar_btn fl"><img src="'+cgmirrordir+'images/icons/simple_small20/_05.png" width="20" height="20" />UnSubscribe from Thread</div></a>';
}
else
{
oldhtml = '<a href="#" onclick="handle_thread_unsubscribe('+threadid+', 1, 0);return false;"><div class="typical_toolbar_btn fl"><img src="'+cgmirrordir+'images/icons/simple_small20/_05.png" width="20" height="20" />Subscribe to Thread</div></a>';
}
if(document.getElementById('subscribepart'))
	{
document.getElementById('subscribepart').innerHTML='<div class="typical_toolbar_btn fl"><img src="'+cgmirrordir+'images/icons/simple_small20/_05.png" width="20" height="20" />'+say+'</div>';
setTimeout("update_id_with('subscribepart', '"+oldhtml+"')",4000);
	}
if(document.getElementById('subscribepart2'))
	{
document.getElementById('subscribepart2').innerHTML='<div class="typical_toolbar_btn fl"><img src="'+cgmirrordir+'images/icons/simple_small20/_05.png" width="20" height="20" />'+say+'</div>';
setTimeout("update_id_with('subscribepart2', '"+oldhtml+"')",4000);
	}

}
	}
}
var url=rootdir+"xml/subscribeme.php?tid="+threadid+"&v="+what;
url=url+"&chk="+Math.random();
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}


}





function rand ( num )
{
return ( Math.floor ( Math.random ( ) * num + 1 ) );
}

function switchimage(x, y) {
	var wut = document.getElementById(y).style.visibility;
	if(wut == "hidden") {	
		x.setAttribute('src', rootdir+'images/maximiseforums.jpg');
	}
	else {
		x.setAttribute('src', rootdir+'images/minimiseforums.jpg');
	}
}


function preload(url)
{
var xmlHttp = new_connection();
if(xmlHttp)
{
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
}

function substr( f_string, f_start, f_length ) {
if(f_start < 0) {
f_start += f_string.length;
}

if(f_length == undefined) {
f_length = f_string.length;
} else if(f_length < 0){
f_length += f_string.length;
} else {
f_length += f_start;
}

if(f_length < f_start) {
f_length = f_start;
}

return f_string.substring(f_start, f_length);
}

function strpos( haystack, needle, offset){
if(haystack == null || haystack == "" || needle == null || needle == "")
{
if(userid == 1)
{
alert("HAYSTACK ERROR: " + haystack + " - needle: " + needle);
}
return false;
}
if(offset == null)
	{
offset = 0;
	}
    var i = haystack.indexOf( needle, offset ); // returns -1
    return i >= 0 ? i : false;
}
function addslashes(str) {
str=str.replace(/\'/g,'\\\'');
str=str.replace(/\"/g,'\\"');
//str=str.replace(/\\/g,'\\\\');
str=str.replace(/\0/g,'\\0');
return str;
}
function gethashhrefval()
	{
var cur = location.href;
if(cur == '')
		{
return false;
		}
var pos = strpos(cur, '#');
if(pos === false)
		{
return false;
		}
else
		{
pos++;
return substr(cur, pos);
		}
	}


function searchclearer(val, what, default_val)
{
if(typeof default_val == "undefined" || default_val == null || default_val == false)
	{
default_val = "Search:";
	}

if(val == 1)
{
if(what.value == default_val)
{
what.value='';
}
}
else
{
if(what.value == '')
{
what.value=default_val;
}
}
}

function search(id, link)
{
var search = document.getElementById(id).value;
if(search.length == 0)
{
alert('Enter something to search...');
}
else if(search.length < 3)
{
alert('Please enter atleast 3 letters for your search');
document.getElementById(id).focus();
}
else
{
searcg = trim(search);
search = urlencode(search);
search = search.replace(/%2f/gi, '%252F');
link=link.replace(/REP/g,search);
window.location=link;
}
return false;
}

function d_enter(e, id, link){
var unicode=e.charCode? e.charCode : e.keyCode
if (unicode == 13)
{
setTimeout("search('"+id+"','"+link+"');", 50);
return false;
}
return true;
}




function isset(  ) {
var a=arguments; var l=a.length; var i=0;
while ( i!=l ) {
if (typeof(a[i])=='undefined') { 
return false; 
} else { 
i++; 
}
}
return true;
}


function in_array (needle, haystack, argStrict) {

var key = '', strict = !!argStrict; 
if (strict) {
for (key in haystack) {
if (haystack[key] === needle) {
return true;            }
}
} else {
for (key in haystack) {
if (haystack[key] == needle) {                return true;
}
}
}
return false;
}



function str_replace (search, replace, subject, count) {
    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}



function htmlentities (string, quote_style)
{
var hash_map = {}, symbol = '', tmp_str = '', entity = '';
tmp_str = string.toString();

if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
return false;
}
hash_map["'"] = '&#039;';
for (symbol in hash_map) {
entity = hash_map[symbol];
tmp_str = tmp_str.split(symbol).join(entity);
}

return tmp_str;
}



function urldecode(str)
{
//id = id.replace(/ /gi, "");
//str = str.replace(/#/gi, "");
//str = str.replace(/%/gi, "");
//id = id.replace(/'/gi, "");
//id = id.replace(/"/gi, "");
//id = id.replace(/=/gi, "");
return decodeURIComponent(str).replace(/\+/g, ' ');
}


function urlencode (str) {
    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
                                                                    replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}

/*
function urlencode( str ) {
var ret = str;
ret = ret.toString();
ret = encodeURIComponent(ret);
ret = ret.replace(/%20/g, '+');
return ret;
}

*/


function get_html_translation_table (table, quote_style) {
   
    var entities = {}, hash_map = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';

    useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';

    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: "+useTable+' not supported');
        // return false;
    }

    entities['38'] = '&amp;';
    if (useTable === 'HTML_ENTITIES') {
        entities['160'] = '&nbsp;';
        entities['161'] = '&iexcl;';
        entities['162'] = '&cent;';
        entities['163'] = '&pound;';
        entities['164'] = '&curren;';
        entities['165'] = '&yen;';
        entities['166'] = '&brvbar;';
        entities['167'] = '&sect;';
        entities['168'] = '&uml;';
        entities['169'] = '&copy;';
        entities['170'] = '&ordf;';
        entities['171'] = '&laquo;';
        entities['172'] = '&not;';
        entities['173'] = '&shy;';
        entities['174'] = '&reg;';
        entities['175'] = '&macr;';
        entities['176'] = '&deg;';
        entities['177'] = '&plusmn;';
        entities['178'] = '&sup2;';
        entities['179'] = '&sup3;';
        entities['180'] = '&acute;';
        entities['181'] = '&micro;';
        entities['182'] = '&para;';
        entities['183'] = '&middot;';
        entities['184'] = '&cedil;';
        entities['185'] = '&sup1;';
        entities['186'] = '&ordm;';
        entities['187'] = '&raquo;';
        entities['188'] = '&frac14;';
        entities['189'] = '&frac12;';
        entities['190'] = '&frac34;';
        entities['191'] = '&iquest;';
        entities['192'] = '&Agrave;';
        entities['193'] = '&Aacute;';
        entities['194'] = '&Acirc;';
        entities['195'] = '&Atilde;';
        entities['196'] = '&Auml;';
        entities['197'] = '&Aring;';
        entities['198'] = '&AElig;';
        entities['199'] = '&Ccedil;';
        entities['200'] = '&Egrave;';
        entities['201'] = '&Eacute;';
        entities['202'] = '&Ecirc;';
        entities['203'] = '&Euml;';
        entities['204'] = '&Igrave;';
        entities['205'] = '&Iacute;';
        entities['206'] = '&Icirc;';
        entities['207'] = '&Iuml;';
        entities['208'] = '&ETH;';
        entities['209'] = '&Ntilde;';
        entities['210'] = '&Ograve;';
        entities['211'] = '&Oacute;';
        entities['212'] = '&Ocirc;';
        entities['213'] = '&Otilde;';
        entities['214'] = '&Ouml;';
        entities['215'] = '&times;';
        entities['216'] = '&Oslash;';
        entities['217'] = '&Ugrave;';
        entities['218'] = '&Uacute;';
        entities['219'] = '&Ucirc;';
        entities['220'] = '&Uuml;';
        entities['221'] = '&Yacute;';
        entities['222'] = '&THORN;';
        entities['223'] = '&szlig;';
        entities['224'] = '&agrave;';
        entities['225'] = '&aacute;';
        entities['226'] = '&acirc;';
        entities['227'] = '&atilde;';
        entities['228'] = '&auml;';
        entities['229'] = '&aring;';
        entities['230'] = '&aelig;';
        entities['231'] = '&ccedil;';
        entities['232'] = '&egrave;';
        entities['233'] = '&eacute;';
        entities['234'] = '&ecirc;';
        entities['235'] = '&euml;';
        entities['236'] = '&igrave;';
        entities['237'] = '&iacute;';
        entities['238'] = '&icirc;';
        entities['239'] = '&iuml;';
        entities['240'] = '&eth;';
        entities['241'] = '&ntilde;';
        entities['242'] = '&ograve;';
        entities['243'] = '&oacute;';
        entities['244'] = '&ocirc;';
        entities['245'] = '&otilde;';
        entities['246'] = '&ouml;';
        entities['247'] = '&divide;';
        entities['248'] = '&oslash;';
        entities['249'] = '&ugrave;';
        entities['250'] = '&uacute;';
        entities['251'] = '&ucirc;';
        entities['252'] = '&uuml;';
        entities['253'] = '&yacute;';
        entities['254'] = '&thorn;';
        entities['255'] = '&yuml;';
    }

    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
    if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#39;';
    }
    entities['60'] = '&lt;';
    entities['62'] = '&gt;';


    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        hash_map[symbol] = entities[decimal];
    }
    
    return hash_map;
}



function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";

var domain_part = "";
if (typeof global_cookie_domain != "undefined" && global_cookie_domain != "")
{
domain_part = "; domain="+global_cookie_domain;
}
document.cookie = name+"="+value+expires+"; path=/"+""+domain_part;
}


function readCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}
/*
function readCookie_old(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
*/
function eraseCookie(name) {
	createCookie(name,"",-1);
}

function setOpacity(obj, opacity) {
if(document.getElementById(obj))
{
obj = document.getElementById(obj);
opacity = (opacity >= 100)?99.999:opacity;
obj.style.filter="progid:DXImageTransform.Microsoft.Alpha(opacity=" + opacity + ");";
obj.style.KHTMLOpacity = opacity/100;
obj.style.MozOpacity = opacity/100;
obj.style.opacity = opacity/100;
}
}



//forum/PMing functions:
function forumhide(id)
{
if(document.getElementById(id))
{
var variable = document.getElementById(id);
variable.style.visibility = "hidden";
variable.style.display = "none";
variable.style._visibility = "hidden";
}
}
function forumunhide(id)
{
if(document.getElementById(id))
{
var variable = document.getElementById(id);
variable.style.visibility = "visible";
variable.style.display = "";
variable.style._visibility = "visible";
}
}

function post_unhide(post_id)
{
var a_id = 'a_' + post_id;
var b_id = 'b_' + post_id;
var c_id = 'c_' + post_id;
var d_id = 'd_' + post_id;
var e_id = 'e_' + post_id;
var f_id = 'f_' + post_id;
var g_id = 'g_' + post_id;
var h_id = 'h_' + post_id;
var i_id = 'i_' + post_id;

var bury_id = 'bury_' + post_id;
var bury_id2 = 'bury2_' + post_id;
forumhide(bury_id);
forumhide(bury_id2);

forumunhide(a_id);
forumunhide(b_id);
forumunhide(c_id);
forumunhide(d_id);
forumunhide(e_id);
forumunhide(f_id);
forumunhide(g_id);
forumunhide(h_id);
forumunhide(i_id);
}

function post_hide(post_id)
{
var a_id = 'a_' + post_id;
var b_id = 'b_' + post_id;
var c_id = 'c_' + post_id;
var d_id = 'd_' + post_id;
var e_id = 'e_' + post_id;
var f_id = 'f_' + post_id;
var g_id = 'g_' + post_id;
var h_id = 'h_' + post_id;
var i_id = 'i_' + post_id;
var bury_id = 'bury_' + post_id;
var bury_id2 = 'bury2_' + post_id;
forumunhide(bury_id);
forumunhide(bury_id2);

forumhide(a_id);
forumhide(b_id);
forumhide(c_id);
forumhide(d_id);
forumhide(e_id);
forumhide(f_id);
forumhide(g_id);
forumhide(h_id);
forumhide(i_id);
}

function expand(post_id)
{
post_unhide(post_id);
var und_id = "und"+post_id;
if(document.getElementById(und_id))
{
document.getElementById(und_id).style.display="";
}
var und_id = "rebury"+post_id;
if(document.getElementById(und_id))
{
document.getElementById(und_id).style.display="";
}

und_id = "unda"+post_id;
if(document.getElementById(und_id))
{
document.getElementById(und_id).style.display="none";
}
und_id = "undb"+post_id;
if(document.getElementById(und_id))
{
document.getElementById(und_id).style.display="none";
}
und_id = "undc"+post_id;
if(document.getElementById(und_id))
{
document.getElementById(und_id).style.display="none";
}
und_id = "undd"+post_id;
if(document.getElementById(und_id))
{
document.getElementById(und_id).style.display="none";
}
und_id = "unde"+post_id;
if(document.getElementById(und_id))
{
document.getElementById(und_id).style.display="none";
}
und_id = "undf"+post_id;
if(document.getElementById(und_id))
{
document.getElementById(und_id).style.display="none";
}
und_id = "undg"+post_id;
if(document.getElementById(und_id))
{
document.getElementById(und_id).style.display="none";
}


}

function doclick(idname)
{

var xmlHttp = new_connection();
if(xmlHttp)
{
var url=rootdir+"xml/click.php?id="+idname;
url=url+"&chk="+Math.random();
xmlHttp.open("GET",url,false);
xmlHttp.send(null);
var i = xmlHttp.responseText;
}

return true;
}

function difference(vala, valb, amount)
{
if(vala == valb)
{
return true;
}
var testone = vala - valb;
var testtwo = valb - vala;
if(testone < amount && testone > 0 || testtwo < amount && testtwo > 0)
{
return true;
}
else
{
return false;
}
}



var support_left_last_load_time = 0;

function support_left_col_load()
{

support_left_last_load_time = timenow();
if(!document.getElementById('support_left_col'))
{
return false;
}
var xmlHttp = new_connection();
if(xmlHttp)
{
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
var i=xmlHttp.responseText;
support_left_last_load_time = timenow();
document.getElementById('support_left_col').innerHTML = i;
//tooltipX();//fix up mouseover tooltip.
}
}

var url=rootdir+"xml/support_left_col.php?load=1";
url=url+"&chk="+Math.random();
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
return false;
}




function support_left_col_check_load()
{
if(difference(timenow(), support_left_last_load_time, 5) == false)
{
support_left_col_load();
}
setTimeout("support_left_col_check_load();", 90000);
}
setTimeout("support_left_col_check_load();", 90000);





function CGTip(id, teamid)
{
var amount = 1;
if(userid == '' || userid == 0)
{
alert('You must be logged in to place a Tip');
return;
}

var xmlHttpch = new_connection();
xmlHttpch.onreadystatechange=function()
{
if(xmlHttpch.readyState==4)
{
var ret = xmlHttpch.responseText;
if(ret == '' || ret == null || ret == 'undefined' || ret == false)
{
return;
}

if(ret.substr(0, 4) == 'good')
{
//alert('saved');
//tip_success_display(id);
var json_content = ret.substr(4);
if(json_content != "")
	{
var json_arr = false;
try
{
json_arr = JSON.parse(json_content);
}
catch (e)
{

}

if(json_arr != false && isset(json_arr['t1_tips']) && isset(json_arr['t2_tips']) && isset(json_arr['total_tips']) && !isNaN(json_arr['total_tips']) && json_arr['total_tips'] > 0)
		{
var tip_one_percent = (json_arr['t1_tips'] / json_arr['total_tips']) * 100;
var tip_two_percent = (json_arr['t2_tips'] / json_arr['total_tips']) * 100;
tip_one_percent = Math.round(tip_one_percent);
tip_two_percent = Math.round(tip_two_percent);



var arr = document.getElementsByTagName("b"); // could get child nodes of actual ladder table if this becomes problematic.
var doing = 0;
var team_one_check = "tip_pcnt_" + id + "_t1";
var team_two_check = "tip_pcnt_" + id + "_t2";
var team_one_radio = "tip_radio_" + id + "_t1";
var team_two_radio = "tip_radio_" + id + "_t2";

var tot_arr = arr.length;
	for(var i=0;i < tot_arr;i++)
	{
if(arr[i].className && arr[i].className == team_one_check)
		{
arr[i].innerHTML=tip_one_percent + "%";
		}
else if(arr[i].className && arr[i].className == team_two_check)
		{
arr[i].innerHTML=tip_two_percent + "%";
		}
else if(arr[i].className && arr[i].className == team_one_radio && isset(json_arr['team_one_id']) && json_arr['team_one_id'] == teamid)
		{
arr[i].checked=true;
		}
else if(arr[i].className && arr[i].className == team_two_radio && isset(json_arr['team_two_id']) && json_arr['team_two_id'] == teamid)
		{
arr[i].checked=true;
		}
	}
arr = document.getElementsByTagName("input"); // could get child nodes of actual ladder table if this becomes problematic.
tot_arr = arr.length;
	for(var i=0;i < tot_arr;i++)
	{
if(arr[i].className && arr[i].className == team_one_radio && isset(json_arr['team_one_id']) && json_arr['team_one_id'] == teamid)
		{
arr[i].checked=true;
		}
else if(arr[i].className && arr[i].className == team_two_radio && isset(json_arr['team_two_id']) && json_arr['team_two_id'] == teamid)
		{
arr[i].checked=true;
		}
	}


		}
	}

// class="tiprpcnt_' . $matchid . '_' . $team_one_id . '"

}
else if(ret == 'bad')
{
alert('Failed to place Tip');
}
else if(userid == 1)
{
alert('Failed, ERROR: ' + "\n" + ret);
}
else
{
alert('Failed to place tip, please retry');
}

}
}
var url=rootdir+"xml/tip.php?id="+id+"&teamid="+teamid+"&amount="+amount;
url=url+"&chk="+Math.random();
xmlHttpch.open("GET",url,true);
xmlHttpch.send(null);
}





function loadjscssfile(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
}







function DisplayAchievement(name)
{
temp_display_achiev(name);
}



function temp_display_achiev(name)
{
var id_req = "bot_hid_id_" + rand(9999);

cg_alert(id_req, name, "ACHIEVEMENT EARNT", 7); // 7 = instant success
return false;

var what = '<div id="'+idz+'" style="background-color:grey;border:5px solid black;width:45%;top:20px;padding: 20px 20px 20px 20px;right:26%; position:absolute;z-index:900000; text-align:center; font-size:18px; font-family:tahoma;"><b style="font-size:18px;">You have been awarded the following Achievement:</b><br /><br /><u style="font-size:24px;">'+name+'</u><br /><div style="float:right;"><b><u><a href="#Close" onclick="document.getElementById(\''+idz+'\').style.display=\'none\';return false;" style="color:white;font-size:12px;">Close</a></u></b></div>';
if(document.getElementById('vbottom_of_site'))
{
what = document.getElementById('vbottom_of_site').innerHTML + what;

document.getElementById('vbottom_of_site').innerHTML=what;
document.getElementById('vbottom_of_site').style.display="";


}
}




function AchievementSave(name)
{
if(userid == 0)
{
return false;
}


var xmlHttp = new_connection();
if(xmlHttp)
{
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
var i=xmlHttp.responseText;
}
}

var url=rootdir+"xml/achievementsave.php?name=" + name;
url=url+"&chk="+Math.random();
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}




return false;
}






function showlocaltime(timestamp)
{

var mmToMonth = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

if(!timestamp || timestamp == null || timestamp == "undefined" || timestamp == 0)
{
timestamp = Math.round(new Date().getTime() / 1000);
}
  var dt = new Date(timestamp * 1000);
//return dt.getDate() "-" mm "-" dt.getFullYear() " " dt.getHours() ":" dt.getMinutes();
var date_hours = dt.getHours();
var meridiem = 'am';
if(date_hours > 12)
{
date_hours = date_hours - 12;
meridiem = 'pm';
}
if(date_hours == 0)
{
date_hours = 12;
}
var date_mins = dt.getMinutes();
if(date_mins >= 0 && date_mins < 10)
{
date_mins = "0" + date_mins;
}


var dt_now = new Date(timenow() * 1000);

var full_date_part = dt.getDate() + "/" + mmToMonth[dt.getMonth()] + "/" + dt.getFullYear() + " - ";
var full_date_part2 = dt_now.getDate() + "/" + mmToMonth[dt_now.getMonth()] + "/" + dt_now.getFullYear() + " - ";
if(full_date_part == full_date_part2)
{
full_date_part = "";
}
else if(dt.getFullYear() == dt_now.getFullYear())
{
full_date_part = mmToMonth[dt.getMonth()] + "/" + dt.getDate() + " - ";
}



return full_date_part + date_hours + ":" + date_mins + meridiem;

}



function select_make_selected(id, toselect)
{

if(!document.getElementById(id))
	{
return false;
	}
var good = false;

if(document.getElementById(id).options)
	{
var array = document.getElementById(id).options;
for (x in array)
{

if(!isNaN(x))
	{
if(document.getElementById(id).options[x].value == toselect)
		{
document.getElementById(id).selectedIndex=x;
good = true;
break;
		}
	}
}

}


if(good == false)
{

	var selectvar = document.getElementById(id);
	for (var i=0; i<selectvar.length; i++)
	{

		if(selectvar.options[i].value == toselect)
		{
		document.getElementById(id).selectedIndex=i;
		good = true;
		break;
		}


	}

}





if(good == false && userid == 1)
{
	alert("Unable to locate select item["+toselect+"] for ID: " + id);
}


}










function show_hidden_ids(id, doval)
{
var c = 0;
var idcheck;
while(c < 150)
{
	idcheck = id + "" + c;
	if(document.getElementById(idcheck) && doval == 1)
	{
	document.getElementById(idcheck).style.display="none";
	}
	else if(document.getElementById(idcheck))
	{
	document.getElementById(idcheck).style.display="";
	}
c++;
}



return false;
}






var cg_ajaxalerts_array=new Array();

function cg_alert(id, text, title, special)
{
//alert("TEMP AJAX TOP RIGHT POPUP:" + "\n" + title + "\n" + text);
//return true;
id = id.replace(/ /gi, "");
id = id.replace(/#/gi, "");
id = id.replace(/'/gi, "");
id = id.replace(/"/gi, "");
id = id.replace(/=/gi, "");
if(id == "")
	{
id = "temp_" + rand(9999);
if(userid == 1)
		{
alert("Using Temporary ID for AJAX alert");
		}
	}


var timer_amount = 900000; // 15 minutes popup will be closed by default
if(special != null && special > 0)
	{
timer_amount = 6000;
	}

if(special != null && special > 50)
	{
timer_amount = special;
	}



//0 = does not disappear, > 0 = disappear after 6 seconds IF not a failed one.  Special of 8/9 will disappear regardless whether it is failed or not for the completed/failed ones, for new ones they will move to failed upon creation.


var text_check = text.toLowerCase();
var title_check = title.toLowerCase();
var success_or_fail = "success";
if(text_check.match("error") != null || text_check.match("fail") != null || title_check.match("error") != null || title_check.match("fail") != null)
	{
success_or_fail = "fail";
timer_amount = 900000; // 15 minutes popup will be closed by default - so you must click close for ALL failures.
if(special != null && special == 8)//special of 9 will make failed ones disappear.
		{
timer_amount = 6000;
		}
	}

if(isset(cg_ajaxalerts_array[id]) && cg_ajaxalerts_array[id] != false && cg_ajaxalerts_array[id] != null)
	{

if(success_or_fail == "success")
		{
cg_ajaxalerts_array[id].completed(timer_amount);
		}
		else
		{
cg_ajaxalerts_array[id].failed(text, timer_amount);
		}

cg_ajaxalerts_array[id] = false;
	}
else
	{
cg_ajaxalerts_array[id] = new ajaxPopup(title, text); // If many are run at the same time, cannot assume that it has immediatlly been shown.


if(special != null && special == 9) // as special of 9 is a warning that will never have a follow up warning and is simply telling the user a message once off. so immediatly fail it and remove. // could add a 10 one that doesnt fail?
	{
setTimeout('if(isset(cg_ajaxalerts_array["'+id+'"])) { if(typeof cg_ajaxalerts_array["'+id+'"].wrapper != "undefined" && cg_ajaxalerts_array["'+id+'"].wrapper.style.visibility == "visible") { cg_ajaxalerts_array["'+id+'"].failed("'+addslashes(text)+'", 8000); cg_ajaxalerts_array["'+id+'"] = false; } }', 200);
setTimeout('if(isset(cg_ajaxalerts_array["'+id+'"])) { if(typeof cg_ajaxalerts_array["'+id+'"].wrapper != "undefined" && cg_ajaxalerts_array["'+id+'"].wrapper.style.visibility == "visible") { cg_ajaxalerts_array["'+id+'"].failed("'+addslashes(text)+'", 8000); cg_ajaxalerts_array["'+id+'"] = false; } }', 2000);
setTimeout('if(isset(cg_ajaxalerts_array["'+id+'"])) { if(typeof cg_ajaxalerts_array["'+id+'"].wrapper != "undefined" && cg_ajaxalerts_array["'+id+'"].wrapper.style.visibility == "visible") { cg_ajaxalerts_array["'+id+'"].failed("'+addslashes(text)+'", 8000); cg_ajaxalerts_array["'+id+'"] = false; } }', 5500);
setTimeout('if(isset(cg_ajaxalerts_array["'+id+'"])) { if(typeof cg_ajaxalerts_array["'+id+'"].wrapper != "undefined" && cg_ajaxalerts_array["'+id+'"].wrapper.style.visibility == "visible") { cg_ajaxalerts_array["'+id+'"].failed("'+addslashes(text)+'", 8000); cg_ajaxalerts_array["'+id+'"] = false; } }', 15000);
setTimeout('if(isset(cg_ajaxalerts_array["'+id+'"])) { if(typeof cg_ajaxalerts_array["'+id+'"].wrapper != "undefined" && cg_ajaxalerts_array["'+id+'"].wrapper.style.visibility == "visible") { cg_ajaxalerts_array["'+id+'"].failed("'+addslashes(text)+'", 8000); cg_ajaxalerts_array["'+id+'"] = false; } }', 25000);
setTimeout('if(isset(cg_ajaxalerts_array["'+id+'"])) { cg_ajaxalerts_array["'+id+'"].failed("'+addslashes(text)+'", 8000); cg_ajaxalerts_array["'+id+'"] = false; }', 40000);

	}
else if(special != null && special == 7) // as special of 9 is a warning that will never have a follow up warning and is simply telling the user a message once off. so immediatly fail it and remove. // could add a 10 one that doesnt fail?
	{
setTimeout('if(isset(cg_ajaxalerts_array["'+id+'"])) { if(typeof cg_ajaxalerts_array["'+id+'"].wrapper != "undefined" && cg_ajaxalerts_array["'+id+'"].wrapper.style.visibility == "visible") { cg_ajaxalerts_array["'+id+'"].completed(8000); cg_ajaxalerts_array["'+id+'"] = false; } }', 200);
setTimeout('if(isset(cg_ajaxalerts_array["'+id+'"])) { if(typeof cg_ajaxalerts_array["'+id+'"].wrapper != "undefined" && cg_ajaxalerts_array["'+id+'"].wrapper.style.visibility == "visible") { cg_ajaxalerts_array["'+id+'"].completed(8000); cg_ajaxalerts_array["'+id+'"] = false; } }', 2000);
setTimeout('if(isset(cg_ajaxalerts_array["'+id+'"])) { if(typeof cg_ajaxalerts_array["'+id+'"].wrapper != "undefined" && cg_ajaxalerts_array["'+id+'"].wrapper.style.visibility == "visible") { cg_ajaxalerts_array["'+id+'"].completed(8000); cg_ajaxalerts_array["'+id+'"] = false; } }', 5500);
setTimeout('if(isset(cg_ajaxalerts_array["'+id+'"])) { if(typeof cg_ajaxalerts_array["'+id+'"].wrapper != "undefined" && cg_ajaxalerts_array["'+id+'"].wrapper.style.visibility == "visible") { cg_ajaxalerts_array["'+id+'"].completed(8000); cg_ajaxalerts_array["'+id+'"] = false; } }', 15000);
setTimeout('if(isset(cg_ajaxalerts_array["'+id+'"])) { if(typeof cg_ajaxalerts_array["'+id+'"].wrapper != "undefined" && cg_ajaxalerts_array["'+id+'"].wrapper.style.visibility == "visible") { cg_ajaxalerts_array["'+id+'"].completed(8000); cg_ajaxalerts_array["'+id+'"] = false; } }', 25000);
setTimeout('if(isset(cg_ajaxalerts_array["'+id+'"])) { cg_ajaxalerts_array["'+id+'"].completed(8000); cg_ajaxalerts_array["'+id+'"] = false; }', 40000);

	}
else if(special != null && special == 11) // as special of 9 is a warning that will never have a follow up warning and is simply telling the user a message once off. so immediatly fail it and remove. // could add a 10 one that doesnt fail?
	{
setTimeout('if(isset(cg_ajaxalerts_array["'+id+'"])) { if(typeof cg_ajaxalerts_array["'+id+'"].wrapper != "undefined" && cg_ajaxalerts_array["'+id+'"].wrapper.style.visibility == "visible") { cg_ajaxalerts_array["'+id+'"].completed(500); cg_ajaxalerts_array["'+id+'"] = false; } }', 8000);
setTimeout('if(isset(cg_ajaxalerts_array["'+id+'"])) { if(typeof cg_ajaxalerts_array["'+id+'"].wrapper != "undefined" && cg_ajaxalerts_array["'+id+'"].wrapper.style.visibility == "visible") { cg_ajaxalerts_array["'+id+'"].completed(500); cg_ajaxalerts_array["'+id+'"] = false; } }', 15000);
setTimeout('if(isset(cg_ajaxalerts_array["'+id+'"])) { if(typeof cg_ajaxalerts_array["'+id+'"].wrapper != "undefined" && cg_ajaxalerts_array["'+id+'"].wrapper.style.visibility == "visible") { cg_ajaxalerts_array["'+id+'"].completed(500); cg_ajaxalerts_array["'+id+'"] = false; } }', 30000);
setTimeout('if(isset(cg_ajaxalerts_array["'+id+'"])) { cg_ajaxalerts_array["'+id+'"].completed(100); cg_ajaxalerts_array["'+id+'"] = false; }', 40000);
	}


	}




//timer_amount = 15000;
//setTimeout("kill_cg_alert('"+id+"', 1)", timer_amount);

}




var cg_alert_distance = 0;
var cg_alert_increase_by = 100;
var cg_alert_inv_timer = false;
var cg_alert_closing_allowed = false;

function cg_alert2(id, text, title, special, show_loading)
{

if(!document.getElementById("cg_alerts_area"))
{
return false;
}


if (typeof rootdir == "undefined")
{
show_loading = false;
}


if(show_loading == true)
	{
text = text + '<br /><div class="loading"></div>';
	}



id = id.replace(/ /gi, "");
id = id.replace(/#/gi, "");
id = id.replace(/'/gi, "");
id = id.replace(/"/gi, "");
id = id.replace(/=/gi, "");

var availHeight;
if(window.innerHeight) {
availHeight = window.innerHeight;
}
else {
availHeight = document.documentElement.clientHeight;
}

if(availHeight > 150)
{
}
else
{
return false;
}
var content_style = availHeight - 154 + "px";
content_style = ' style="height:'+content_style+'px;"';

var cg_alert_min_distance = Math.floor(availHeight / 8);
if(cg_alert_distance <= 0 || cg_alert_distance < cg_alert_min_distance)
{
cg_alert_distance = cg_alert_min_distance;
}

/*
text = text + '<br /><br />You have been permanently banned by <a href="">sn@p!!!!</a><form><fieldset><legend>General Information</legend><table padding="0" cellpadding="0" cellspacing="0"><col><col width="100%"><tr><th class="nw">CG Username:</th><td><div class="textinput"><input name="" type="text" value="sn@p!"></div></td></tr></table><div class="button_wrapper"><input type="image" src="'+cgmirrordir+'images/buttons/popup_save.png"></div></fieldset></form></div>';
*/


cg_alert_closing_allowed = false; // user cannot close.
var wrapped_content = ""; //  style="background:url(none);"
wrapped_content += '<div id="black_w2" style="height:0px;background:url(none);"><div style="margin-top: '+cg_alert_distance+'px;" class="cg_window_s"><div class="popup cg_window"><div class="title"><span id="'+id+'_title">'+title+'</span><a class="site_btn fr" onclick="kill_cg_alert(\''+id+'\', 0);">Close</a></div><div class="content" id="'+id+'_content" style="max-height:500px;overflow:auto;">'+text+'</div></div></div></div>';

if(document.getElementById(id))
{
	var idtitle = id + '_title';
	var idcontent = id + '_content';
	if(document.getElementById(idtitle) && document.getElementById(idcontent))
	{
	document.getElementById(idtitle).innerHTML=title;
	document.getElementById(idcontent).innerHTML=text;
	}
	else
	{
document.getElementById(id).innerHTML=wrapped_content;
cg_alert_distance = cg_alert_distance + cg_alert_increase_by;
	}
}
else
{
document.getElementById("cg_alerts_area").innerHTML=document.getElementById("cg_alerts_area").innerHTML + '<div id="'+id+'">'+wrapped_content+'</div>';
cg_alert_distance = cg_alert_distance + cg_alert_increase_by;
}

setTimeout(function() { cg_alert_closing_allowed = true; },400); // user can only close after it's been shown for this many ms.





var timer_amount = 600000; // 10 minutes popup will be closed by default
if(special == 1)
{
timer_amount = 1250; // quick
}
else if(special == 2)
{
timer_amount = 3000; // 
}
else if(special == 3)
{
timer_amount = 5000; // 
}
else if(special == 4)
{
timer_amount = 9991000; // forces user to close.
}
else if(special == 5)
{
timer_amount = 500;
}
//timer_amount = 15000;
setTimeout("kill_cg_alert('"+id+"', 1)", timer_amount);

}


function kill_cg_alert(id, doanyway)
{
if(cg_alert_closing_allowed == true && document.getElementById(id) || doanyway == 1 && document.getElementById(id))
{
document.getElementById(id).innerHTML="";
cg_alert_distance = cg_alert_distance - cg_alert_increase_by; // should loop through all viewable ones and resize, also make sure none can disappear whilst this is happening.
}
}


function strip_out_bad(text)
{
text = text.replace(/'/gi, "");
text = text.replace(/"/gi, "");


return htmlentities(text);
}



function ajax_load_url_return_content(url)
{

	var xmlHttp = new_connection();
	if(xmlHttp)
	{
		xmlHttp.open("GET",url,false);
		xmlHttp.send(null);
		if(xmlHttp.readyState==4)
		{
		return xmlHttp.responseText;
		}
	}
	return false;
}


function ajax_load_url_put_in_innerhtml(url, html_id)
{
if(!document.getElementById(html_id))
{
return false;
}

var xmlHttp = new_connection();
if(xmlHttp)
{
	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			var i=xmlHttp.responseText;
			document.getElementById(html_id).innerHTML = i;
			return false;
		}
	};

	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}
return false;

}


var global_dropdown_amount_queued = 0;
var global_dropdown_timer = false;
var global_dropdown_ajax_in_progress = false;
function handle_dropdown(id, type, specialval, optional_val)
{
if(!document.getElementById(id))
{
return false;
}
if(optional_val == null || optional_val == false)
	{
optional_val = 0;
	}
var id_results = id + "_results";
if(!document.getElementById(id_results))
{
return false;
}


var text = document.getElementById(id).value;
if(text == "" || text.length < 3)
{
global_dropdown_ajax_in_progress = false;
handle_dropdown_results(id_results, "");
return false;
}


//alert("Q")
queue_dropdown(id, type, specialval, optional_val, 0);
return false;
}


function queue_dropdown(id, type, specialval, optional_val, reset_queue)
{

if(reset_queue == 1)
{
global_dropdown_amount_queued = 0;
}
var id_results = id + "_results";

	if(global_dropdown_ajax_in_progress == false)
	{
global_dropdown_amount_queued = 0;
		global_dropdown_ajax_in_progress = true;
		do_dropdown_work(id, type, specialval, optional_val);

		if(global_dropdown_timer !== false)
		{
		clearTimeout(global_dropdown_timer);
		}
		global_dropdown_timer = setTimeout(function() { global_dropdown_ajax_in_progress = false; },1250); // disallow future ajax requests for this many ms.

	}
	else if(global_dropdown_amount_queued == 0)
	{
global_dropdown_amount_queued++;
		setTimeout("queue_dropdown('"+id+"', '"+type+"', '"+specialval+"', '"+optional_val+"', 1);", 250); // already running, re-check again in this amount of ms.
	}

}




var last_searched = "";
function do_dropdown_work(id, type, specialval, optional_val)
{

var id_results = id + "_results";
var text = document.getElementById(id).value;
if(text == "" || text.length < 3)
{
handle_dropdown_results(id_results, "");
return false;
}
if(text == last_searched)
{
return false;
}
last_searched = text;
//cgdebug("DDHANDLE", "WORKING["+text+"]");



var xmlHttp = new_connection();
if(xmlHttp)
{
	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			var i=xmlHttp.responseText;
//global_dropdown_ajax_in_progress = false;
//alert(i);
if(document.getElementById(id).value.substr(0,text.length) == text)
{
handle_dropdown_results(id_results, i);
}
else if(userid == 1)
			{
//alert("RESULT FOR NON NEEDED RESULT ["+text+"]");
			}
			return false;
		}
	};

var url=rootdir+"xml/load_dropdown.php?type="+type+"&text="+urlencode(text)+"&special="+specialval+"&optional="+optional_val;
url=url+"&chk="+Math.random();
//alert("searching: " + text);
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}



return false;
}





function handle_dropdown_results(id_results, content)
{

if(content == "")
{
document.getElementById(id_results).style.display="none";
document.getElementById(id_results).innerHTML=content;
}
else
{
document.getElementById(id_results).innerHTML=content;
document.getElementById(id_results).style.display="";
}



}




function dd_handle(type, val, title, special, optional)
{

if(type == "teaminvite")
{
dd_handle_teaminvite(type, val, title, special, optional);
}
else if(type == "team")
{
dd_handle_team(type, val, title, special, optional);
}
else if(type == "user" || type == "userteaminvite")
{
dd_handle_user(type, val, title, special, optional);
}
else if(type == "highschool" || type == "university")
{
dd_handle_highschool_university(type, val, title, special, optional);
}
else if(userid == 1)
{
alert("ERROR: No handle for result");
}

return false;
}


function dd_handle_highschool_university(type, val, title, special, optional)
{
if(!isNaN(special) && special > 0)
{
// do something different [not needed]
}
else if(special != "" && document.getElementById(special))
{
document.getElementById(special).value=title;
var id_results = special + "_results";
handle_dropdown_results(id_results, "");
}

return false;
}



function dd_handle_user(type, val, title, special, optional)
{

if(special == "admin_useraccess_select")
{
select_user(title, val);
var id_results = special + "_results";
handle_dropdown_results(id_results, "");
}
else if(special == "admin_supportnotify_select")
{
cg_support_ticket_notify(title, val, special);
document.getElementById(special).value="";
var id_results = special + "_results";
handle_dropdown_results(id_results, "");
}
else if(special == "admin_useraccess_select2")
{
select_user2(title, val);
var id_results = special + "_results";
handle_dropdown_results(id_results, "");
}
else if(special == "admin_pugadd_select")
{
cg_pug_select_user(title, val);
var id_results = special + "_results";
handle_dropdown_results(id_results, "");
}
else if(special == "cg_chat_priv")
{
CG_CHATROOM_give_user_access(title, val);
var id_results = special + "_results";
handle_dropdown_results(id_results, "");
}
else if(special == "memberlist_user_search")
{
window.location = rootdir+"profile/"+val+"/";
var id_results = special + "_results";
handle_dropdown_results(id_results, "");
}
else if(special == "inbox_user_search")
{
window.location = rootdir+"inbox/user/"+val+"/";
var id_results = special + "_results";
handle_dropdown_results(id_results, "");
}
else if(special.substr(0,14) == "cgtv_user_add_")
{
cgtv_user_add(val, title, optional);
var id_results = special + "_results";
handle_dropdown_results(id_results, "");
}
else if(special.substr(0,19) == "joblist_user_search")
{
cg_job_user_add(val, title, optional);
var id_results = special + "_results";
handle_dropdown_results(id_results, "");
}
else if(special.substr(0,21) == "grouplist_user_search")
{
cg_group_user_add(val, title, optional);
var id_results = special + "_results";
handle_dropdown_results(id_results, "");
}
else if(special.substr(0,22) == "grouplist2_user_search")
{
cg_group_user_add2(val, title, optional);
var id_results = special + "_results";
handle_dropdown_results(id_results, "");
}
else if(optional == "eventadmin")
{
if(confirm("Are you sure you want to add \""+title+"\" as an Event Admin?"))
	{
window.location = rootdir+"event.php?id="+special+"&add_event_admin_uid="+val;
	}
var id_results = "add_event_admin_results";
handle_dropdown_results(id_results, "");
}
else if(optional == "add_user_to_tourny")
{
add_user_to_tourny(val, title, special);
}
else if(special == "blocked_userlist")
{
if(confirm("Are you sure you want to block \""+title+"\" from contacting you?"))
	{
window.location = rootdir+"inbox/blocked.php?add_userid="+val;
	}
var id_results = special + "_results";
handle_dropdown_results(id_results, "");
}
else if(special == "premium_select_user")
{
var id_results = special + "_results";
handle_dropdown_results(id_results, "");
premium_get_userid = val;
premium_get_username = title;
setTimeout("premium_handle_recurring_option()", 150);
}
else if(type == "userteaminvite" && optional != "" && document.getElementById("invite_user_to_team_" + special) && special != null && !isNaN(special) && special > 0)
{
var main_id = "invite_user_to_team_" + special;
document.getElementById(main_id).value=title;
invite_cguser_to_team(special, global_ckey, optional, "", val); // must be after value is set so it can load it and then clear it.
var id_results = main_id + "_results";
handle_dropdown_results(id_results, "");
}
else if(special != "" && document.getElementById(special))
{
document.getElementById(special).value=title;
var id_results = special + "_results";
handle_dropdown_results(id_results, "");
}
else if(!isNaN(special) && special > 0 && confirm("Are you sure you want to invite '" + title + "' to be a manager of your organisation?"))
{
	var loc = rootdir+"organisation.php?id="+special+"&inv_manager_to_orgid="+val+"&ckey="+global_ckey;
	window.location=loc;
}
return false;
}


function cg_group_user_add2(u_id, name, group_id)
{
popup_close();
return groupadmin_action(group_id, 'useradd_group', u_id);
}
function cg_group_user_add(u_id, name, job_id)
{
cg_jobgroup_user_addedit('group', u_id, name, 1, job_id);
}

function cg_job_user_add(u_id, name, job_id)
{
cg_jobgroup_user_addedit('job', u_id, name, 1, job_id);
}

function cg_jobgroup_user_addedit(type, u_id, name, val, job_id)
{
if(job_id > 0)
	{
popup_close();
return jobadmin_action(job_id, 'add_'+type, u_id);
	}


var id = 'create_'+type+'_ids_part';
var id2 = type+'_'+u_id;

var remove_part = ' [<a href="#remove" onclick="cg_jobgroup_user_addedit(\''+type+'\', \''+u_id+'\', \''+name+'\', 0);return false;">REMOVE</a>]';
var new_content = '<div id="'+id2+'"><input type="hidden" name="'+id2+'" value="'+val+'"/><a href="'+rootdir+'profile/'+u_id+'/">'+htmlentities(name)+'</a>'+remove_part+'</div>';


if(document.getElementById(id2))
	{
if(val == 0)
		{
document.getElementById(id2).innerHTML="";
document.getElementById(id2).style.display="none";
		}
		else
		{
document.getElementById(id2).innerHTML=new_content;
document.getElementById(id2).style.display="";
		}
	}
else if(document.getElementById(id) && val == 1)
	{
document.getElementById(id).innerHTML=document.getElementById(id).innerHTML+new_content;
	}
return true;
}



function dd_handle_team(type, val, title, special, optional)
{

if(optional == "add_team_to_tourny")
{
add_team_to_tourny(val, title, special);
var id_results = "add_team_to_tourny_results";
handle_dropdown_results(id_results, "");
if(document.getElementById("add_team_to_tourny"))
	{
document.getElementById("add_team_to_tourny").value="";
document.getElementById("add_team_to_tourny").focus();
	}
}
else if(special == "admin_send_email_to_team")
{
addteam_email(title, val);
var id_results = special + "_results";
handle_dropdown_results(id_results, "");
}
else if(special != "" && document.getElementById(special))
{
document.getElementById(special).value=title;
var id_results = special + "_results";
handle_dropdown_results(id_results, "");
}
else if(!isNaN(special) && special > 0)
{
	if(userid == 1)
	{
alert("No handle for this");
	}
return false;
}

return false;
}






function dd_handle_teaminvite(type, val, title, special, optional)
{
if(special > 0)
{
}
else
{
return false;
}

if(confirm("Are you sure you want to invite '" + title + "' to your organisation?"))
{
var loc = rootdir+"team.php?id="+val+"&inv_to_orgid="+special+"&ckey="+global_ckey;
window.location=loc;
}


return false;
}


//LOGGED IN FUNCTIONS - INVITE USER TO TEAM:
//LOGGED IN FUNCTIONS - INVITE USER TO TEAM:
//LOGGED IN FUNCTIONS - INVITE USER TO TEAM:
//LOGGED IN FUNCTIONS - INVITE USER TO TEAM:


function handle_user_user_change(uid, tid)
{
if(!isset(teams_rank_array[tid][uid]))
{
return false;
}
var team_u_rank = "team_user_rank_" + tid;
select_make_selected(team_u_rank, teams_rank_array[tid][uid]);

if(isset(teams_core_array[tid][uid]))
{
var team_u_core = "team_user_core_" + tid;
select_make_selected(team_u_core, teams_core_array[tid][uid]);
}





}

function handle_user_rank_change(val, tid, uckey)
{
var team_user_id = "team_user_id_" + tid;
if(!document.getElementById(team_user_id))
{
return false;
}
var uid = document.getElementById(team_user_id).value;
if(isNaN(uid) || uid < 1)
{
alert("Error, no user selected.");
return false;
}
if(!isset(teams_rank_array[tid][uid]))
{
return false;
}

if(val >= 1 && val < 4)
{
var rank_name = "ERROR";
if(val == 1)
{
rank_name = "Captain";
}
else if(val == 2)
{
rank_name = "Lieutenant";
}
else if(val == 3)
{
rank_name = "Member";
}
var users_name = "user";

var w = document.getElementById(team_user_id).selectedIndex;
if(document.getElementById(team_user_id).options[w])
{
var selected_text = document.getElementById(team_user_id).options[w].text;
if(selected_text != "" && selected_text != null && selected_text != false && selected_text != "undefined")
{
users_name = selected_text;
}
}

var change_word = "demote";
if(val < teams_rank_array[tid][uid])
{
var change_word = "promote";
}



if(confirm("Are you sure you want to "+change_word+" "+users_name+" to a "+rank_name+"?"))
{
var loc = rootdir+"team.php?id="+tid+"&ckey="+uckey+"&rankuid="+uid+"&urank="+val;
window.location=loc;
}
else
{
var team_u_rank = "team_user_rank_" + tid;
select_make_selected(team_u_rank, teams_rank_array[tid][uid]); // revert.
}


}
return false;
}







function handle_user_core(val, tid, uckey, changes_left)
{
var team_user_id = "team_user_id_" + tid;
if(!document.getElementById(team_user_id))
{
return false;
}
var uid = document.getElementById(team_user_id).value;
if(isNaN(uid) || uid < 1)
{
alert("Error, no user selected.");
return false;
}
if(!isset(teams_rank_array[tid][uid]))
{
return false;
}

if(val >= 0 && val < 4)
{
var rank_name = "Non Core Member";
if(val == 1)
{
rank_name = "Core Member";
}
var users_name = "user";

var w = document.getElementById(team_user_id).selectedIndex;
if(document.getElementById(team_user_id).options[w])
{
var selected_text = document.getElementById(team_user_id).options[w].text;
if(selected_text != "" && selected_text != null && selected_text != false && selected_text != "undefined")
{
users_name = selected_text;
}
}



if(confirm("Are you sure you want to change "+users_name+" to a "+rank_name+"?\nYou have "+changes_left+" change(s) left."))
{
var loc = rootdir+"team.php?id="+tid+"&ckey="+uckey+"&coreuid="+uid+"&coreval="+val;
window.location=loc;
}
else
{
var team_u_rank = "team_user_core_" + tid;
select_make_selected(team_u_rank, teams_rank_array[tid][uid]); // revert.
}


}
return false;
}






function handle_acceptdecline_user(uid, tid, uckey, action, uname)
{

if(isNaN(uid) || uid < 1)
{
alert("Error, no user selected.");
return false;
}

if(isNaN(tid) || tid < 1)
{
alert("Error, no team selected.");
return false;
}


var confirm_text = "Are you sure you want to accept " + uname + " into the team?";
if(action == 0)
	{
confirm_text = "Are you sure you want to decline " + uname + " from joining the team?";
	}
else if(action == -1)
	{
confirm_text = "Are you sure you want to cancel the invitation for " + uname + " to join the team?";
	}



if(confirm(confirm_text))
{
var loc = rootdir+"team.php?id="+tid+"&ckey="+uckey+"&acceptdeclineuid="+uid+"&acceptval="+action;
window.location=loc;
}


return false;
}








function handle_removing_user(tid, uckey)
{

var team_user_id = "team_user_id_" + tid;
if(!document.getElementById(team_user_id))
{
return false;
}
var uid = document.getElementById(team_user_id).value;
if(isNaN(uid) || uid < 1)
{
alert("Error, no user selected.");
return false;
}

var users_name = "user";

var w = document.getElementById(team_user_id).selectedIndex;
if(document.getElementById(team_user_id).options[w])
{
var selected_text = document.getElementById(team_user_id).options[w].text;
if(selected_text != "" && selected_text != null && selected_text != false && selected_text != "undefined")
{
users_name = selected_text;
}
}


if(confirm("Are you sure you want to REMOVE " + users_name + " from the team?"))
{
var loc = rootdir+"team.php?id="+tid+"&ckey="+uckey+"&rankuid="+uid+"&urank=0";
window.location=loc;
}


return false;
}



function invite_info_update(val, id_name, game_name, team_name, do_loading)
{
var display_name = game_name + " - " + team_name;
if(team_name == "")
	{
display_name = game_name;
	}
else if(game_name == "")
	{
display_name = team_name;
	}

cg_alert(id_name, val, "INVITE: " + display_name, 0, do_loading);
}

var global_allow_team_invites = true;
var global_invite_users_to_team_count = 0;
function invite_cguser_to_team(tid, uckey, game_name, team_name, u_id)
	{
//alert(tid + " = " + uckey + " | " + game_name + " || " + team_name + " ---- " + u_id);

var inv_user_id = "invite_user_to_team_" + tid;
if(!document.getElementById(inv_user_id))
{
return false;
}

var uname_invite = trim(document.getElementById(inv_user_id).value);
if(uname_invite == "")
{
return false;
}


if(u_id == null || u_id == false || isNaN(u_id))
		{
u_id = 0;
		}


if(global_allow_team_invites == false)
		{
return false;
		}


if(global_invite_users_to_team_count > 7)
		{
global_allow_team_invites = false;
setTimeout(function() { global_allow_team_invites = true; }, 9000);
var id_req = "to_many_users_warning" + rand(9999);
cg_alert(id_req, "Please wait a moment before inviting any more users", "ERROR: USER DOES NOT EXIST", 9);
return false;
		}
global_invite_users_to_team_count++;
setTimeout(function() { global_invite_users_to_team_count--; }, 12000);



invite_actual_user(uname_invite, u_id, tid, uckey, game_name, team_name);
document.getElementById(inv_user_id).value="";
return false;
}


function invite_actual_user(val, u_id, tid, uckey, game_name, team_name)
{

var id_req = "cginv_" + tid + "_" + strip_out_bad(val) + rand(9999);

var xmlHttpch = new_connection();
if(xmlHttpch)
{
xmlHttpch.onreadystatechange=function()
{
	if(xmlHttpch.readyState==4)
	{
		var ret = xmlHttpch.responseText;
if(ret == "" || ret == null || ret == "undefined" || ret == false)
{
invite_info_update("REQUEST FAILED WHEN INVITING: " + val, id_req, game_name, team_name, false);
return;
}
else if(ret == "notfound")
{
cg_alert(id_req, "No user found named: " + htmlentities(val), "ERROR: USER DOES NOT EXIST", 3);
}
else if(ret == "error")
{
		invite_info_update("ERROR INVITING: " + htmlentities(val), id_req, game_name, team_name, game_name, team_name, false);
}
else if(ret == "noaccess")
{
		invite_info_update("ERROR INVITING: " + htmlentities(val) + ", you do not have access.", id_req, game_name, team_name, game_name, team_name, false);
}
else if(ret == "error_inviting_user")
{
		invite_info_update("ERROR inviting: " + htmlentities(val), id_req, game_name, team_name, game_name, team_name, false);
}
else if(ret == "user_is_match_banned")
{
		invite_info_update(htmlentities(val) + " is match banned, unable to invite", id_req, game_name, team_name, false);
}
else if(ret.substr(0,9) == "inv_error")
{
		invite_info_update("ERROR: " + ret.substr(9), id_req, game_name, team_name, false);
}
else if(ret == "invited")
{
cg_alert(id_req, htmlentities(val) + " has been invited to the team", "USER INVITED!", 2);
reload_team_members_table(tid);
}
else if(ret.substr(0,12) == "user_in_team")
{
		invite_info_update("ERROR: " + htmlentities(val) + ret.substr(12), id_req, game_name, team_name, false);
}
else if(userid == 1)
{
	invite_info_update("ERROR: " + ret + " -- " + val, id_req, game_name, team_name, false);
}
else
{
	invite_info_update("An Unknown Error has occurred", id_req, game_name, team_name, false);
}
	}
}
var url=rootdir+"xml/inv_user.php?tid="+tid+"&ckey="+uckey+"&u="+urlencode(val)+"&u_id="+u_id;

url=url+"&chk="+Math.random();
xmlHttpch.open("GET",url,true);
xmlHttpch.send(null);
invite_info_update("Attempting to invite CG user: <b>" + htmlentities(val) + "</b>&nbsp;", id_req, game_name, team_name, true);
}


}




function reload_team_members_table(tid)
{
	var id_a = "cg_team_table_" + tid;
	var id_b = "cg_team_table_" + tid + "_org";
	var url;
	if(document.getElementById(id_a))
	{
	url = rootdir + "xml/team_member_table.php?id="+tid+"&type=team";
	url=url+"&chk="+Math.random();
	ajax_load_url_put_in_innerhtml(url, id_a);
	}
	if(document.getElementById(id_b))
	{
	url = rootdir + "xml/team_member_table.php?id="+tid+"&type=organisation";
	url=url+"&chk="+Math.random();
	ajax_load_url_put_in_innerhtml(url, id_b);
	}
}


//LOGGED IN FUNCTIONS - END INVITE USER TO TEAM
//LOGGED IN FUNCTIONS - END INVITE USER TO TEAM
//LOGGED IN FUNCTIONS - END INVITE USER TO TEAM
//LOGGED IN FUNCTIONS - END INVITE USER TO TEAM
//LOGGED IN FUNCTIONS - END INVITE USER TO TEAM

function cgdebug(type, text)
{
if(userid != 1)
{
return false;
}
var debug_id = "cg_debug_area";
if(document.getElementById(debug_id))
{

document.getElementById(debug_id).innerHTML=document.getElementById(debug_id).innerHTML + "<br /><b>"+type+"</b>: "+text;
}

return false;
}




//TOOLBAR:
var toolbar_closed = 'CLOSED';
var toolbar_open = '<b>OPEN</b>';
function CG_init_ToolBar()
{
if(userid == '' || userid == 0)
{
return false;
}

CG_ToolBar_check_cookie();
return false;
}




var toolbar_previous_value = 0;
function CG_ToolBar_process(value)
{
createCookie("CyberGamer_ToolBar",value,160);
toolbar_previous_value = value; // should stop initiating window from dealing with twice.
return false;
}


function CG_ToolBar_process_actual(value)
{
return false; //disable this.
if(document.getElementById('sb_notWindow_close'))
{

}

if(toolbar_previous_value != value)
{
	if(value >= 0)
	{
		if (typeof notWindow != "undefined")
		{
		notWindow.open();
		}
	}
	else
	{
		if (typeof notWindow != "undefined")
		{
		notWindow.close();
		}
	}
}

toolbar_previous_value = value;
}





function CG_ToolBar_check_cookie()
{
CG_ToolBar_check_cookie_do();
setTimeout("CG_ToolBar_check_cookie();", 1000);
}



function CG_ToolBar_check_cookie_do()
{
var current_toolbar = readCookie("CyberGamer_ToolBar");
if(document.getElementById('toolbar_debug'))
{
document.getElementById('toolbar_debug').innerHTML='Cookie Value:'+current_toolbar;
}
if(current_toolbar != null && current_toolbar != 'undefined')
{
CG_ToolBar_process_actual(current_toolbar);
}
}
//END TOOLBAR













function tagmsg(post_id)
{
var xmlHttpch = new_connection();
if(xmlHttpch)
{
xmlHttpch.onreadystatechange=function()
{
	if(xmlHttpch.readyState==4)
	{
		var ret = xmlHttpch.responseText;
		if(ret == 1)
		{
		alert('Message has been tagged!');
		return;
		}
		else if(ret == 0)
		{
		alert('Message has been un tagged!');
		return;
		}
		else if(ret == '' || ret == null || ret == 'undefined' || ret == false)
		{
		alert('Error - message has not been tagged.');
		return;
		}
	}
};
var url=rootdir+"xml/tag.php?id="+post_id;
url=url+"&chk="+Math.random();
xmlHttpch.open("GET",url,true);
xmlHttpch.send(null);
}
return false;
}



function decrease_inbox_read()
{
var val;
if(document.getElementById("cg_pm_unread_count_a"))
{
val = document.getElementById("cg_pm_unread_count_a").innerHTML / 1;
if(val > 0)
	{
val--;
document.getElementById("cg_pm_unread_count_a").innerHTML=val;
	}
}

if(document.getElementById("cg_pm_unread_count_b"))
{
val = document.getElementById("cg_pm_unread_count_b").innerHTML / 1;
if(val > 0)
	{
val--;
document.getElementById("cg_pm_unread_count_b").innerHTML=val;
	}
}



}


function cg_mark_msg_read(id, deletemsg)
{
if(id > 0)
	{
	}
	else
	{
return false;
	}
var extra_request = "";
var text_use = '<img src="'+cgmirrordir+'images/icons/fuge/icons/mail.png" alt="" width="16" height="16" class="icon" /><a href="'+rootdir+'inbox/">Message has been marked as read</a><p>Go to your inbox to re-read it.</p>';
if(isset(deletemsg) && deletemsg == true)
	{
extra_request = "&remove_msg=1";
var text_use = '<img src="'+cgmirrordir+'images/icons/fuge/icons/mail.png" alt="" width="16" height="16" class="icon" /><a href="'+rootdir+'inbox/trash/">Message has been removed</a><p>Go to your trash to un-delete it.</p>';
	}


var html_id = "cgpm_" + id;
if(document.getElementById(html_id))
{
document.getElementById(html_id).innerHTML=text_use;
}
var xmlHttpch = new_connection();
if(xmlHttpch)
{
	xmlHttpch.onreadystatechange=function()
	{
		if(xmlHttpch.readyState==4)
		{
		var ret = xmlHttpch.responseText;
		if(ret == "marked")
			{
			}
		else if(ret == "alreadymarked")
			{
			}
		else if(ret == "deleted")
			{
			}
			else
			{
				//some kind of error has occurred.
				cgdebug("MARK READ FAILED", ret);
			}
		}
	}
	var url=rootdir+"xml/inbox_message_send.php?id="+id+"&mark_as_read=1" + extra_request;
	url=url+"&chk="+Math.random();
	xmlHttpch.open("GET",url,true);
	xmlHttpch.send(null);
}
return false;




}



function mailcgwindow(id, title)
{
 // not ideal workaround.
var showhideid = "title_" + id;


var id_check2 = id + "_extra";
var id_ta = id + "_ta";
var id_ta2 = id + "_ta_extra";
var id_ph = id + "_ph";
var id_ph2 = id + "_ph_extra";
var showhideid2 = "title_" + id + "_extra";
if(document.getElementById(id_check2) && document.getElementById(showhideid2))
{

if(document.getElementById(id))
{
//remove temp div
document.getElementById(id_check2).innerHTML="";
}
else
{
//turn temp div into perm.
document.getElementById(id_check2).setAttribute("id", id);
document.getElementById(showhideid2).setAttribute("id", showhideid);
if(document.getElementById(id_ta2) && document.getElementById(id_ph2)) // post reply area is optional.
	{
document.getElementById(id_ta2).setAttribute("id", id_ta);
document.getElementById(id_ph2).setAttribute("id", id_ph);
	}
}

}





if(!document.getElementById(id))
{
if(userid == 1)
	{
alert("HTML ID not found for MAIL("+title+"): " + id);
	}
return false;
}

cgwindow(id, title);
if(document.getElementById(showhideid))
{
document.getElementById(showhideid).style.display="none";
}

}

/*
function handle_send_message(id)
{
if(id > 0)
	{
	}
	else
	{
return false;
	}
var html_id = "cgpm_" + id + "_ta";
var html_popup = "cgpm_msg_" + id;
var html_popup_bot = "cgpm_bot_" + id;
if(!document.getElementById(html_id))
{
return false;
}


var post_text = document.getElementById(html_id).value;
if(post_text.length <= 2)
	{
alert("Text entered is to short");
return false;
	}


document.getElementById(html_id).value="Posting...";

var get_vars = "";
var post_parameters = "post_text="+encodeURIComponent(post_text); 


var xmlHttp = new_connection();
xmlHttp.open('POST', rootdir+"xml/inbox_message_send.php?id="+id+"&chk="+Math.random() + "" + get_vars, true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function()
{
	if (xmlHttp.readyState == 4)
	{
	var response = xmlHttp.responseText;
			if(response == "failed" || response == "error" || response == "cannot_reply_to_system_messages")
			{
			document.getElementById(html_id).value=post_text;
			alert("ERROR: " + response);
			}
			else if(response == "messageblocked")
			{
			document.getElementById(html_id).value=post_text;
			alert("ERROR: You have been added to users block list, as such your message was not sent.");
			}
			else if(response == "to_many_pms")
			{
			document.getElementById(html_id).value=post_text;
			alert("You have sent to many PMs in the last few minutes, please wait before trying again...");
			}
			else if(response == "text_to_short")
			{
			document.getElementById(html_id).value=post_text;
			alert("Text entered to short...");
			}
			else if(response == "no_access")
			{
			document.getElementById(html_id).value=post_text;
			alert("Error Saving Message");
			}
			else if(response == "not_logged_in")
			{
			document.getElementById(html_id).value=post_text;
			alert("Error: you are not logged in.");
			}
			else if(response == "saved") // message saved but didnt return messages.
			{
			document.getElementById(html_id).value="";
			}
			else // All good, update popup with content
			{ // GOOD PM
			//load_ticket(ticket_id, true); //need to reload content.
			document.getElementById(html_id).value="";
			if(document.getElementById(html_popup))
				{
					document.getElementById(html_popup).innerHTML=response;
						if(document.getElementById(html_popup_bot))
						{
						popup_gobottom(document.getElementById(html_popup_bot));
						}
				}
		if(document.getElementById("fast_pm_achievement_complete"))
				{
					DisplayAchievement('Fast PM Reply!');
				}


			} // GOOD PM
	}

};
xmlHttp.send(post_parameters);

return false;
}
*/



function edit_d_enter(e){
var unicode=e.charCode? e.charCode : e.keyCode
if (unicode == 13)
{
return false;
}
return true;
}







function CG_submit_rating_lesser(real_id, type) // used just to get the overall rating.
{
if(userid <= 0 || userid == "")
	{
alert("Login to rate an item");
return false;
	}


var id = 'cg_rating_area_' + type + '_' + real_id;
var saved_id = id + "_saved";



if(!document.getElementById(id) || !document.getElementById(saved_id))
{
if(userid == 1)
	{
alert("ID's not found");
	}
return false;
}

var main_rating = document.getElementById(id).innerHTML;

if(isNaN(main_rating))
	{
alert("You must select a rating first!");
return false;
	}


var xmlHttp = new_connection();
if(xmlHttp)
{
	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
		var i=xmlHttp.responseText;

if(i == "success")
			{
var cur_content = document.getElementById(saved_id).innerHTML;
document.getElementById(saved_id).innerHTML='<b class="highlight">Saved!</b>';
setTimeout(function() {document.getElementById(saved_id).innerHTML=cur_content;}, 4500);
			}
			else
			{
document.getElementById(saved_id).innerHTML="<b>Error</b>";
 if(userid == 1)
				{
alert("Error: " + i);
				}
			}

		}
	};
var url=rootdir+"xml/rate.php?id="+real_id+"&type="+type+"&r="+main_rating;
url=url+"&chk="+Math.random();
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
return false;





return false;
}



function CG_submit_rating(real_id, type)
{
if(userid <= 0 || userid == "")
	{
alert("Login to rate an item");
return false;
	}


var id = 'cg_rating_area_' + type + '_' + real_id;
var saved_id = id + "_saved";



if(!document.getElementById(id) || !document.getElementById(saved_id))
{
if(userid == 1)
	{
alert("ID's not found");
	}
return false;
}

var id_content = id + "_content";
var id_editing = id + "_editing";
var id_music = id + "_music";
var id_presentation = id + "_presentation";
if(!document.getElementById(id_content) || !document.getElementById(id_editing) || !document.getElementById(id_music) || !document.getElementById(id_presentation))
{
if(userid == 1)
	{
alert("Secondary ID's not found");
	}
return false;
}

var content_rating = document.getElementById(id_content).innerHTML;
var editing_rating = document.getElementById(id_editing).innerHTML;
var music_rating = document.getElementById(id_music).innerHTML;
var presentation_rating = document.getElementById(id_presentation).innerHTML;
var main_rating = document.getElementById(id).innerHTML;

if(isNaN(main_rating) || isNaN(content_rating) || isNaN(editing_rating) || isNaN(music_rating) || isNaN(presentation_rating))
	{
alert("You must rate all 4 sections: Content, Editing, Music and Presentation");
return false;
	}


var xmlHttp = new_connection();
if(xmlHttp)
{
	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
		var i=xmlHttp.responseText;
if(i == "success")
			{
var cur_content = document.getElementById(saved_id).innerHTML;
document.getElementById(saved_id).innerHTML='<b class="highlight">Saved!</b>';
setTimeout(function() {document.getElementById(saved_id).innerHTML=cur_content;}, 4500);
			}
			else
			{
document.getElementById(saved_id).innerHTML="<b>Error</b>";
 if(userid == 1)
				{
alert("Error: " + i);
				}
			}

		}
	};
var url=rootdir+"xml/rate.php?id="+real_id+"&type="+type+"&r="+main_rating+"&content="+content_rating+"&editing="+editing_rating+"&music="+music_rating+"&presentation="+presentation_rating;
url=url+"&chk="+Math.random();
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
return false;





return false;
}


function cg_load_page(id, type, page, op_uid)
{
var pages_id = 'cg_discussion_pages_' + type +'_' + id;
var content_id = 'cg_discussion_' + type +'_' + id;
if(!document.getElementById(pages_id) || !document.getElementById(content_id))
{
if(userid == 1)
	{
alert("ID's not found: " + type + " - " + id);
	}
return false;
}

var page_word_id = 'page_word_' + type + '_' + id;
if(document.getElementById(page_word_id))
{
//document.getElementById(page_word_id).innerHTML="Loading";
}


var url=rootxmldir+"commentspage.php?id="+id+"&type="+type+"&page="+page+"&op="+op_uid;
url=url+"&chk="+Math.random();
cg_json_call(url);
return false;
}

var global_dicussion_check_between_updates = 2000;
var global_dicussion_check_between_updates_max = 3000;
var global_final_check_timer = false;
var global_last_final_check_time=new Array();

function cg_discussion_box_load(id, type)
{
do_check_final_page(id, type);
}


function cg_post_handle_response(id, type, json_arr)
{
var pages_id = 'cg_discussion_pages_' + type +'_' + id;
var content_id = 'cg_discussion_' + type +'_' + id;
if(!document.getElementById(pages_id) || !document.getElementById(content_id))
{
if(userid == 1)
	{
alert("HTML ID's not found: " + type + " - " + id);
	}
return false;
}


if(!isset(json_arr['pages']) || !isset(json_arr['content']))
	{
return false;
	}

var pages_part = json_arr['pages'];
var content_part = json_arr['content'];

document.getElementById(pages_id).innerHTML=pages_part;

document.getElementById(content_id).innerHTML=content_part;
var page_word_id = 'page_word_' + type + '_' + id;
if(document.getElementById(page_word_id))
{
document.getElementById(page_word_id).innerHTML="Page:";
}

var check_final_id = 'on_final_page_' + type + '_' + id;
if(document.getElementById(check_final_id))
	{
if(global_final_check_timer != false)
		{
clearTimeout(global_final_check_timer);
		}
global_dicussion_check_between_updates = global_dicussion_check_between_updates + 500;
if(global_dicussion_check_between_updates > global_dicussion_check_between_updates_max)
		{
global_dicussion_check_between_updates = global_dicussion_check_between_updates_max;
		}
global_final_check_timer = setTimeout(function() {do_check_final_page(id, type);}, global_dicussion_check_between_updates);
	}



}



function do_check_final_page(id, type)
{
var allowed_to_do = true;
var check_visible = 'discussion_' + type + '_' + id;
if(document.getElementById(check_visible))
{
if(document.getElementById(check_visible).style.display == "none")
{
allowed_to_do = false;
}
}

if(allowed_to_do == false)
{
setTimeout("do_check_final_page("+id+", '"+type+"')",5000); // not visible, re-check every X seconds.
return false;
}


if(isset(global_last_final_check_time[id+"_"+type]) && difference(timenow(), global_last_final_check_time[id+"_"+type], 2) == true)
{
if(userid == 1)
	{
	alert("cancelling page ajax update.");
	}
return false;
}
var check_final_id = 'on_final_page_' + type + '_' + id;
if(document.getElementById(check_final_id))
	{
global_last_final_check_time[id+"_"+type] = timenow();
cg_load_page(id, type, 99999);
	}
}


function cg_page_post(htmlid, id, type, op_uid)
{
if(!document.getElementById(htmlid))
{
return false;
}
var text = document.getElementById(htmlid).value;
if(text == "")
	{
	alert("No Text entered");
return false;
	}
else if(text.length < 2)
	{
	alert("Must enter atleast two characters");
return false;
	}
else if(text == "Posting...")
	{
	alert("Please wait before attempting to post again...");
return false;
	}

var page_word_id = 'page_word_' + type + '_' + id;
if(document.getElementById(page_word_id))
{
document.getElementById(page_word_id).innerHTML="Posting";
}

document.getElementById(htmlid).value="Posting...";

var post_form_name = "comment_" + type + '_' + id;
var post_parameters = post_form_name+"="+encodeURIComponent(text); 




var xmlHttp = new_connection();
xmlHttp.open('POST', rootdir+"xml/comments_post.php?id="+id+"&type="+type+"&op="+op_uid+"&chk="+Math.random(), true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
var response = xmlHttp.responseText;

//convert response to proper json arr

var json_arr = false;
try
{
json_arr = JSON.parse(response);
}
catch (e)
{

}
cg_post_handle_response(id, type, json_arr);
document.getElementById(htmlid).value="";
return false;
}

};
xmlHttp.send(post_parameters);






return false;
}


function cg_page_remove_post(html_post_area_id, id, type, msg_id)
{
if(!document.getElementById(html_post_area_id))
	{
	alert("Failed to remove post");
return false;
	}
if(confirm("Are you sure?") == false)
	{
return false;
	}



var xmlHttp = new_connection();
if(xmlHttp)
{
	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
		var i=xmlHttp.responseText;
		if(i == "remove_success")
			{
document.getElementById(html_post_area_id).style.display="none";
			}
		}
	};
var url=rootdir+"xml/comments_post.php?id="+id+"&type="+type+"&remove_id="+msg_id;
url=url+"&chk="+Math.random();
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
return false;

}




var previous_edited_text=new Array();
function cg_page_edit(html_post_area_id, html_editpost_area_id, id, type, msg_id)
{
var html_post_area_id_text = html_post_area_id + "_text";
if(!document.getElementById(html_editpost_area_id))
	{
	alert("Failed to edit post");
return false;
	}
if(!document.getElementById(html_post_area_id_text))
	{
	alert("Failed to edit post.");
return false;
	}

var text = document.getElementById(html_editpost_area_id).value;
var post_form_name = "edit_" + type + '_' + id;
var post_parameters = post_form_name+"="+encodeURIComponent(text); 

var xmlHttp = new_connection();
xmlHttp.open('POST', rootdir+"xml/comments_post.php?id="+id+"&type="+type+"&edit_id="+msg_id+"&chk="+Math.random(), true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
var response = xmlHttp.responseText;
if(response != "" && response != "error" && response != false && response != "undefined")
	{
document.getElementById(html_post_area_id_text).innerHTML=response;
popup_close(); // close edit popup.
previous_edited_text[html_editpost_area_id]=text; // add text of post to array, to be replace textarea value upon next area, due to continuous destroying of IDs during popup creation.

	}

return false;
}

};
xmlHttp.send(post_parameters);






return false;
}


function cg_page_edit_fix_tarea(id)
{
	if(document.getElementById(id))
	{
		if(isset(previous_edited_text[id]))
		{
		document.getElementById(id).value=previous_edited_text[id];
		}
	}
}


function sort_out_edit_content(html_editpost_area_id, text)
{
document.getElementById(html_editpost_area_id).value=text;

}



function cg_style_hide(id)
{
//if(document.getElementById(id))
//{
//setTimeout(function() {document.getElementById(id).style.visibility="hidden";},1500);
//}
}


function buddy(bid, status, id)
{
if(userid <= 0)
{
alert('Login to add buddy.');
return;
}
var xmlHttpch = new_connection();
if(xmlHttpch)
{
var url=rootdir+"xml/buddy.php?id="+bid+"&s="+status;
url=url+"&chk="+Math.random();
xmlHttpch.open("GET",url,true);
xmlHttpch.send(null);
	if(status == 1)
	{
if(document.getElementById("cg_buddy_addremove"))
{
document.getElementById("cg_buddy_addremove").innerHTML='<a href="#AddBuddy" onclick="buddy('+id+', 0);return false;"><div class="site_btn fl"><img src="'+cgmirrordir+'images/icons/simple_small20/_408.png" alt="" />Waiting for Buddy to Accept</div></a>';
}

	}
	else
	{
if(document.getElementById("cg_buddy_addremove"))
{
document.getElementById("cg_buddy_addremove").innerHTML='<a href="#AddBuddy" onclick="buddy('+id+', 1);return false;"><div class="site_btn fl"><img src="'+cgmirrordir+'images/icons/simple_small20/_408.png" alt="" />Add Buddy</div></a>';
}
	}
}



return;
}







//BEGIN HOMEPAGE WORK




function homepage_previous()
{
if(homepage_buttons_disabled == true)
{
return false;
}
if(homepage_current_page > 1)
{
homepage_current_page--;
homepage_table(homepage_currently_displaying, homepage_currently_displaying_info, homepage_current_page);
}
}

function homepage_next()
{
if(homepage_buttons_disabled == true)
{
return false;
}
//alert("nxt");
homepage_current_page++;
homepage_table(homepage_currently_displaying, homepage_currently_displaying_info, homepage_current_page);
}

function homepage_change(to) // if to is null will reload current (content will change if filter cookie has changed)
{
if(homepage_buttons_disabled == true)
	{
setTimeout(function() {	homepage_buttons_disabled = false; },100); // failsafe.
return false;
}
if(to != "" && to != null)
{
homepage_currently_displaying = to;
createCookie(homepage_platform_used + "_default_tab_" + userid,to,120);
}
homepage_current_page = 1;
homepage_table(homepage_currently_displaying, homepage_currently_displaying_info, homepage_current_page);
}


function homepage_working_display(what)
	{
//0 = about to do something, 1 = completed, all good.
var next_num = homepage_current_page + 1;
var prev_num = homepage_current_page - 1;

var prev_name_part = "Back to Page: " + prev_num;
if(prev_num <= 0)
{
prev_name_part = "No Previous Page";
}
global_hpage_prev_name = prev_name_part;
global_hpage_next_name = "Next Page: " + next_num;


if(what == 0)
	{

homepage_buttons_disabled = true;
if(document.getElementById("homepage_prev_button"))
{
setOpacity("homepage_prev_button", 60);
//document.getElementById("homepage_prev_button").src=cgmirrordir+"images/buttons/prevarrow_disabled.png";
}
if(document.getElementById("homepage_next_button"))
{
setOpacity("homepage_next_button", 60);
//document.getElementById("homepage_next_button").src=cgmirrordir+"images/buttons/nextarrow_disabled.png";
}

}
else if(what >= 1)
{
homepage_buttons_disabled = false;
if(document.getElementById("homepage_prev_button") && homepage_current_page > 1)
{
setOpacity("homepage_prev_button", 100);
//document.getElementById("homepage_prev_button").src=cgmirrordir+"images/buttons/prevarrow.png";
}
if(document.getElementById("homepage_next_button"))
{
	if(what == 2)
	{
setOpacity("homepage_next_button", 60);
	//document.getElementById("homepage_next_button").src=cgmirrordir+"images/buttons/nextarrow_disabled.png";
	}
	else
	{
setOpacity("homepage_next_button", 100);
	//document.getElementById("homepage_next_button").src=cgmirrordir+"images/buttons/nextarrow.png";
	}
}
}

}


var global_home_queued_already = false
var global_home_last_query_time = 0;
function homepage_table(page_name, page_info, page)
{
if(global_home_queued_already == true)
{
return false;
}
	var time_between_requests = 1000;
	homepage_working_display(0);

	var time_since_last_request =  mstimenow() - global_home_last_query_time;
	if(time_since_last_request < time_between_requests)
	{
		global_home_queued_already = true;
		var run_in_x_seconds = time_between_requests - time_since_last_request;
		setTimeout(function() {	global_home_queued_already = false; homepage_table(page_name, page_info, page); },run_in_x_seconds);
	}
	else
	{
		global_home_last_query_time =  mstimenow();
		homepage_table2(page_name, page_info, page);
	}
return false;
}












function homepage_table2(page_name, page_info, page)
{
if(!document.getElementById("homepage_table_display"))
{
return false;
}
if(document.getElementById("cghpg_la_title"))
{
document.getElementById("cghpg_la_title").innerHTML = "Loading: " + ucfirst(page_name);
}
homepage_change_display(page_name);
var urlpart = "?platform="+homepage_platform_used+"&page_name="+page_name+"&info="+page_info+"&page="+page;
var url=rootxmldir+"homepage_table.php"+urlpart;
url=url+"&chk="+Math.random();
cg_json_call(url);
return false;
}


function cg_homepage_handle_result(ret_arr)
{
var ret = "";
if(isset(ret_arr['result']))
	{
ret = ret_arr['result'];
	}
if(ret == "" || ret == null || ret == "undefined" || ret == false)
{
return false;
}
var goodvalue = 1;
if(ret == "empty")
{
ret = '<table class="fp_table" id="forumactivity"><col /><thead><tr><th><b>&nbsp;</b></th></tr></thead><tbody><tr><td align="center">No Entries Found</td></tr></tbody></table>';
goodvalue = 2;
}

if(ret != "")
{
document.getElementById("homepage_table_display").innerHTML=ret;
homepage_working_display(goodvalue);
}
return false;
}


function homepage_highlight(id, what)
{
if(!document.getElementById(id))
{
return false;
}
if(what == 1)
{
//document.getElementById(id).style.fontWeight="bold";
document.getElementById(id).className="active";
}
else
{
//document.getElementById(id).style.fontWeight="normal";
document.getElementById(id).className="";
}

}

function homepage_change_display(page_name)
{

homepage_highlight("menu_" + page_name, 1);
for (x in homepage_menu_items)
{
if(homepage_menu_items[x] != page_name)
{
homepage_highlight("menu_" + homepage_menu_items[x], 0);
}
}

}





function check_filters_cookie(do_init)
{
var CGFilters_Cookie = readCookie(homepage_cookie_name);

var cookie_content = "";
	var listsArray = document.getElementsByTagName("input");
	var listsNo = listsArray.length;
	for(i = 0;i < listsNo; i++) {
if(do_init == false && listsArray[i].className == "filter_checkbox" && listsArray[i].checked == true)
{
if(cookie_content == "")
{
cookie_content = "_";
}
cookie_content = cookie_content + listsArray[i].value + "_";
}

if(do_init == true && listsArray[i].className == "filter_checkbox")
{
if(CGFilters_Cookie != "" && CGFilters_Cookie != null && strpos(CGFilters_Cookie, "_" + listsArray[i].value + "_") !== false)
{
listsArray[i].checked=true;
}
}

	}

if(do_init == false && cookie_content != CGFilters_Cookie)
{
createCookie(homepage_cookie_name,cookie_content,120);
homepage_change("");
}



}


function cg_filter_change()
{
check_filters_cookie(false);
}



//END HOMEPAGE






/**
*
*  AJAX IFRAME METHOD (AIM)
*  http://www.webtoolkit.info/
*
**/

AIM = {

frame : function(c) {

var n = 'f' + Math.floor(Math.random() * 99999);
var d = document.createElement('DIV');
d.innerHTML = '<iframe style="display:none" src="about:blank" id="'+n+'" name="'+n+'" onload="AIM.loaded(\''+n+'\')"></iframe>';
document.body.appendChild(d);

var i = document.getElementById(n);
if (c && typeof(c.onComplete) == 'function') {
i.onComplete = c.onComplete;
}

return n;
},

form : function(f, name) {
f.setAttribute('target', name);
},

submit : function(f, c) {
AIM.form(f, AIM.frame(c));
if (c && typeof(c.onStart) == 'function') {
return c.onStart();
} else {
return true;
}
},

loaded : function(id) {
var i = document.getElementById(id);
if (i.contentDocument) {
var d = i.contentDocument;
} else if (i.contentWindow) {
var d = i.contentWindow.document;
} else {
var d = window.frames[id].document;
}
if (d.location.href == "about:blank") {
return;
}

if (typeof(i.onComplete) == 'function') {
i.onComplete(d.body.innerHTML);
}
}

}


function remove_cgwindow(id)
{
if(document.getElementById('black_w') && document.getElementById('cgwindow_content'))
{
if(document.getElementById(id))
{
document.getElementById(id).innerHTML=document.getElementById('cgwindow_content').innerHTML;
}
document.body.removeChild(document.getElementById('black_w'));
}
}



function startCallback()
{
setTimeout("remove_cgwindow('cg_upload_options');", 75);
setTimeout(function() {	cg_alert("cg_file_upload_id", "Uploading file to CG...", "FILE UPLOAD", 0); },75);
return true;
}

function completeCallback(response)
{
if(response.substr(0,7) == "success")
	{
var content = response.substr(7);
setTimeout(function() {	cg_alert("cg_file_upload_id", "Upload Successful!", "FILE UPLOAD", 1500); },75);
cg_alert2("cg_file_uploaded", content, "FILE UPLOADED", 4);
	}
	else
	{
setTimeout(function() {	cg_alert("cg_file_upload_id", "Error: Upload Failed!", "FILE UPLOAD", 8); },75);
if(userid == 1)
		{
alert(response);
		}
	}
}


function cg_check_file_upload()
{
if(document.getElementById("cg_upload_title") && document.getElementById("cg_upload_title").value.length >= 2)
{
return true;
}
alert("Must enter a title for the file");
document.getElementById("cg_upload_title").focus();
return false;

}


function cg_view_previous_user_uploads(u_id, remove_id)
{
if(u_id <= 0)
	{
	return false;
	}
if(!isset(remove_id) || remove_id == null)
	{
remove_id = 0;
	}


remove_cgwindow('cg_upload_options'); //remove upload window if it is open.
if(remove_id <= 0)
	{
cg_alert2("cg_files_uploaded", "<b>Loading files list...</b>", "FILES UPLOADED", 4);
	}

var xmlHttpch = new_connection();
if(xmlHttpch)
{
	xmlHttpch.onreadystatechange=function()
	{
		if(xmlHttpch.readyState==4)
		{
			var ret = xmlHttpch.responseText;
			if(ret == '' || ret == null || ret == 'undefined' || ret == false)
			{
			return false;
			}

cg_alert2("cg_files_uploaded", ret, "FILES UPLOADED", 4);

			return false;
		}
	};

var url=rootdir+"xml/view_uploaded_user_files.php?id=" + u_id + "&remove="+remove_id;
url=url+"&chk="+Math.random();
xmlHttpch.open("GET",url,true);
xmlHttpch.send(null);
}
return false;
}


function dump(arr,level) {
var dumped_text = "";
if(!level) level = 0;

//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += "    ";

if(typeof(arr) == 'object') { //Array/Hashes/Objects
 for(var item in arr) {
  var value = arr[item];
 
  if(typeof(value) == 'object') { //If it is an array,
   dumped_text += level_padding + "'" + item + "' ...\n";
   dumped_text += dump(value,level+1);
  } else {
   dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
  }
 }
} else { //Stings/Chars/Numbers etc.
 dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
} 




function init_konami_code()
{
var kn_arr = new Array("fzMhh8zhTiY", "Tg4u7ko333U", "KoQb8vb4blA", "VkmncrAPILw", "HoUgZmo_Kdo", "THNPmhBl-8I", "k-wFI9vTqto", "5pidokakU4I", "zlfKdbWwruY", "Vo0Cazxj_yc", "ByPtY_spGWw", "xLjphhzDDrY");
var yt_id = kn_arr[(rand((kn_arr.length)) - 1)];
var what = '<h1>Konami Master</h1><div class="page_summary">Congratulations on completing the <a href="http://en.wikipedia.org/wiki/Konami_Code" class="highlight"><b>Konami Code</b></a>. Enjoy this random video:<br /></div>';
var what2 = '<div align="center"><object width="860" height="600"><param name="movie" value="http://www.youtube.com/v/'+yt_id+'&hl=en&fs=1&rel=0&autoplay=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'+yt_id+'&hl=en&fs=1&rel=0&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="860" height="600" wmode="opaque"></embed></object></div>';
if(document.getElementById('content_of_site'))
{
document.getElementById('content_of_site').innerHTML=what+what2;
}
else
{
document.body.innerHTML='<br /><br /><br />' + what2;
}
document.title='Konami Master!';
DisplayAchievement('Konami Master!');
AchievementSave('konami_master');
}


/*
* Konami-JS ~ Now with iPhone support!
* Code: http://konami-js.googlecode.com/
* Examples: http://www.snaptortoise.com/konami-js
* Copyright (c) 2009 George Mandis (georgemandis.com)
* Version: 1.0.8 (05/08/2009)
* Licensed under the Artistic License/GPL
* http://dev.perl.org/licenses/
* Tested in: Safari 4, Firefox 3, IE7 and Mobile Safari 2.2.1
*/

var konami = {
input:"",
pattern:"38384040373937396665",
clear:setTimeout('konami.clear_input()',2000),
load: function(link) {
window.document.onkeydown = function(e) {
konami.input+= e ? e.keyCode : event.keyCode;
if (konami.input == konami.pattern) {
konami.code(link);
clearTimeout(konami.clear);
return;
}
clearTimeout(konami.clear);
konami.clear = setTimeout("konami.clear_input()",2000);
}
this.iphone.load(link)
},
code: function(link) { window.location=link},
clear_input: function() {
konami.input="";
clearTimeout(konami.clear);
},
iphone:{
start_x:0,
start_y:0,
stop_x:0,
stop_y:0,
tap:false,
capture:false,
keys:["UP","UP","DOWN","DOWN","LEFT","RIGHT","LEFT","RIGHT","TAP","TAP","TAP"],
code: function(link) { window.location=link},
load: function(link){
document.ontouchmove = function(e){
if(e.touches.length == 1 && konami.iphone.capture==true){ // Only deal with one finger
var touch = e.touches[0]; // Get info for finger #1
konami.iphone.stop_x = touch.pageX;
konami.iphone.stop_y = touch.pageY;
konami.iphone.tap = false; 
konami.iphone.capture=false;
konami.iphone.check_direction();
}
}		
document.ontouchend = function(evt){
if (konami.iphone.tap==true) konami.iphone.check_direction();		
}
document.ontouchstart = function(evt){
konami.iphone.start_x = evt.changedTouches[0].pageX
konami.iphone.start_y = evt.changedTouches[0].pageY
konami.iphone.tap = true
konami.iphone.capture = true
}		
},
check_direction: function(){
x_magnitude = Math.abs(this.start_x-this.stop_x)
y_magnitude = Math.abs(this.start_y-this.stop_y)
x = ((this.start_x-this.stop_x) < 0) ? "RIGHT" : "LEFT";
y = ((this.start_y-this.stop_y) < 0) ? "DOWN" : "UP";
result = (x_magnitude > y_magnitude) ? x : y;
result = (this.tap==true) ? "TAP" : result;			
if (result==this.keys[0]) this.keys = this.keys.slice(1,this.keys.length)
if (this.keys.length==0) this.code(this.link)
}
}
}



konami.iphone.code = function() {
//Nothing.
}

konami.code = function() {
if(isset(navigator.platform) && navigator.platform.toLowerCase() == "win32" && isset(navigator.appName) && navigator.appName.toLowerCase() == "netscape" && isset(navigator.appCodeName) && navigator.appCodeName.toLowerCase() == "mozilla" && isset(navigator.userAgent) && navigator.userAgent != "")
{
var pos_konami = strpos(navigator.userAgent, 'Windows NT');
if(pos_konami === false || isNaN(pos_konami))
{
}
else
{
init_konami_code();
}
}
}

if(isset(navigator.platform) && navigator.platform.toLowerCase() == "win32" && isset(navigator.appName) && navigator.appName.toLowerCase() == "netscape" && isset(navigator.appCodeName) && navigator.appCodeName.toLowerCase() == "mozilla" && isset(navigator.userAgent) && navigator.userAgent != "")
{
var pos_konami = strpos(navigator.userAgent, 'Windows NT');
if(pos_konami === false || isNaN(pos_konami))
{
}
else
{
konami.load();
}
}



function userprofile_more(area, u_id, htmlid, htmlidremove)
{

if(!document.getElementById(htmlid))
{
return false;
}


if(htmlidremove != null && htmlidremove != false && document.getElementById(htmlidremove))
{
document.getElementById(htmlidremove).style.display="none";
}




var xmlHttpch = new_connection();
if(xmlHttpch)
{
	xmlHttpch.onreadystatechange=function()
	{
		if(xmlHttpch.readyState==4)
		{
var ret = xmlHttpch.responseText;
if(ret == '' || ret == null || ret == 'undefined' || ret == false)
{
return false;
}
else if(ret == "error")
{
alert("Nothing found");
return false;
}

if(document.getElementById(htmlid))
{
document.getElementById(htmlid).innerHTML=ret;
}
if(area == "recentactivity")
			{
document.getElementById('user_profile_recent').style.height='850px';
			}

return false;
		}
	};

var url=rootdir+"xml/profile_more.php?id=" + u_id + "&area="+area;
url=url+"&chk="+Math.random();
xmlHttpch.open("GET",url,true);
xmlHttpch.send(null);
}
return false;

}




function handle_code_select(what)
{
var id = what.parentNode.nextSibling; // 
if(id)
	{
id.focus();
id.select();
	}
return false;
}



function handle_spoiler(what)
{
if(!what)
	{
return false;
	}
var arr = what.parentNode.getElementsByTagName("span");
var doing = 0;
if(arr.length <= 0)
	{
return false; // didnt find spoiler properly..
	}

	for(var i=0;i < arr.length;i++)
	{
if(arr[i].className && arr[i].className == "spoilertext" && arr[i].style.display == "none")
		{
doing = 1;
		}
	}
//Clicking only on the "spoiler" text part opens/hides, otherwise if you click on the actual content (ie to play a a youtube video) it'll hide.
var spoiler = "";
var spoilertext = "";
if(doing == 0)
	{
spoiler = "bold";
spoilertext = "none";
	}



	for(var i=0;i < arr.length;i++)
	{
if(arr[i].className && arr[i].className == "spoiler")
		{
arr[i].style.fontWeight=spoiler;
		}
else if(arr[i].className && arr[i].className == "spoilertext")
		{
arr[i].style.display=spoilertext;
		}
	}

}



function user_save_setting(setting, value)
{

var xmlHttpch = new_connection();
if(xmlHttpch)
{
	xmlHttpch.onreadystatechange=function()
	{
		if(xmlHttpch.readyState==4)
		{
var ret = xmlHttpch.responseText;
if(ret == '' || ret == null || ret == 'undefined' || ret == false)
{
return false;
}
else if(ret == "error")
{
			alert('An error has occurred.');
return false;
}

return false;
		}
	};

var url=rootdir+"xml/user_save_setting.php?setting="+setting+"&value="+value;
url=url+"&chk="+Math.random();
xmlHttpch.open("GET",url,true);
xmlHttpch.send(null);
}
return false;



}



function load_recent_posts(time_period, unread, words, sectionid)
{
var main_id = "recent_posts_area";
if(!document.getElementById(main_id))
{
return false;
}
document.getElementById(main_id).innerHTML='<div align="center"><b>Loading Posts: '+words+'...</b></div><br />';
document.getElementById(main_id).style.display="";


var xmlHttp = new_connection();
if(xmlHttp)
{
xmlHttp.onreadystatechange=function()
{
	if(xmlHttp.readyState==4)
	{
		var i=xmlHttp.responseText;
document.getElementById(main_id).innerHTML=i;

if(document.getElementById("select_pfiltera"))
{
customSelect("select_pfiltera","select_pfiltera_text",true);
}
if(document.getElementById("select_pfilterb"))
{
customSelect("select_pfilterb","select_pfilterb_text",true);
}



	}
}
var url=rootdir+"xml/forum_recent_posts.php?period="+time_period+"&unread="+unread+"&sectionid="+sectionid;
url=url+"&chk="+Math.random();
xmlHttp.open("GET",url,true);
xmlHttp.send(null);

}

return false;
}

function cg_post_preview(text_id, preview_area_id)
{
if(!document.getElementById(text_id))
{
return false;
}
if(!document.getElementById(preview_area_id))
{
return false;
}

if(document.getElementById(preview_area_id).style.display == "none") // display full loading msg only the first time.
	{
document.getElementById(preview_area_id).innerHTML='<div align="center"><br /><b>Loading Preview...</b><br /><br /></div>';
document.getElementById(preview_area_id).style.display="";
	}
else if(document.getElementById("post_preview_note_area")) // display "loading" inside the already loaded preview.
	{
document.getElementById("post_preview_note_area").innerHTML=' &nbsp;<b>Loading Preview...</b>';
document.getElementById("post_preview_note_area").style.display="";
	}


var post_text = document.getElementById(text_id).value;
if(post_text == "")
	{
return false;
	}



var post_parameters = "text="+encodeURIComponent(post_text); 




var xmlHttp = new_connection();
xmlHttp.open('POST', rootdir+"xml/preview_post.php?type="+preview_area_id+"&chk="+Math.random(), true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
var response = xmlHttp.responseText;

document.getElementById(preview_area_id).innerHTML=response;
document.getElementById(preview_area_id).style.display="";


return false;
}

};
xmlHttp.send(post_parameters);



return false;
}

function cg_hide_preview(preview_area_id)
{
	if(document.getElementById(preview_area_id))
	{
	document.getElementById(preview_area_id).style.display="none";
	}
return false;
}


function do_title_flash(new_title)
{
if(new_title == "" || new_title == false)
	{
return false;
	}

var current_title = document.title;


document.title = new_title;
setTimeout(function() { document.title = "*" + new_title + "*"; }, 500);
setTimeout(function() { document.title = "**" + new_title + "**"; }, 1000);
setTimeout(function() { document.title = "***" + new_title + "***"; }, 1500);
setTimeout(function() { document.title = "" + new_title + ""; }, 2000);
setTimeout(function() { document.title = "*" + new_title + "*"; }, 2500);
setTimeout(function() { document.title = "**" + new_title + "**"; }, 3000);
setTimeout(function() { document.title = "***" + new_title + "***"; }, 3500);
setTimeout(function() { document.title = "" + new_title + ""; }, 4000);
setTimeout(function() { document.title = "*" + new_title + "*"; }, 4500);
setTimeout(function() { document.title = "**" + new_title + "**"; }, 5000);
setTimeout(function() { document.title = "***" + new_title + "***"; }, 5500);
setTimeout(function() { document.title = "" + new_title + ""; }, 6000);

setTimeout(function() { document.title = current_title; }, 25000);

}



function cg_update_smartbar()
{
if (typeof smartbar == "undefined")
{
	return false;
}
smartbar.ajaxObj_update.update();
/*
if(smartbar.currOpen != null)
{
	smartbar.currOpen.ajax.update();
}
*/
}


function show_this_reason(reason, id)
{
if(!document.getElementById(id))
	{
return false;
	}
if(reason == -1)
	{
document.getElementById(id).innerHTML="";
document.getElementById(id).style.display="none";
	}
	else
	{
document.getElementById(id).innerHTML='<div class="dottedbox">'+reason + ' [<a href="#Close" onclick="show_this_reason(-1, \''+id+'\');return false">Close</a>]</div>';
document.getElementById(id).style.display="";
	}
}

function cgteam_lfs(teamid, val)
{
if(teamid == 0 || teamid <= 0)
	{
return false;
	}

var map_prompt = "";
if(val == 1)
	{
map_prompt = prompt("Enter Map:", "Any Map");
if(map_prompt == null)
		{
return false;
		}
	}

var have_server = 0;
if(document.getElementById("cg_lfs_has_svr") && document.getElementById("cg_lfs_has_svr").checked == true)
	{
have_server = 1;
	}


var id_req = "cg_lfs_enter_team_"+teamid + rand(9999);

cg_alert(id_req, "Processing Request", "LOOKING FOR SCRIM", 0, true);



var xmlHttp = new_connection();
if(xmlHttp)
{
xmlHttp.onreadystatechange=function()
{
	if(xmlHttp.readyState==4)
	{
var r=xmlHttp.responseText;
if(r == "good")
		{
cg_alert(id_req, "Processing Request", "LOOKING FOR SCRIM", 0, true);
cg_update_smartbar();
		}
		else
		{
cg_alert(id_req, "An error has occurred:"+r, "LOOKING FOR SCRIM", 0, true);
		}
	}
}
var url=rootdir+"xml/lfs.php?teamid="+teamid+"&value="+val+"&platform="+global_lfs_platform+"&map="+urlencode(map_prompt)+"&server="+have_server;
url=url+"&chk="+Math.random();
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}



return false;
}




function cg_radio_input_checked_value(radio_name)
	{
arr = document.getElementsByTagName("input"); // could get child nodes of actual ladder table if this becomes problematic.
var ret = "";
tot_arr = arr.length;
	for(var i=0;i < tot_arr;i++)
	{
if(arr[i].name && arr[i].name == radio_name && arr[i].name.checked && arr[i].name.checked == true)
		{
ret = arr[i].value;
break;
		}
	}

return ret;
} 

function cg_lfs_enter_custom_team()
{
if(!document.getElementById("cg_customlfs_team_name"))
	{
alert("Cannot find HTML Team Name Text Box");
return false;
	}
var team_name_use = trim(document.getElementById("cg_customlfs_team_name").value);
if(team_name_use == "")
	{
alert("No Team Name Entered");
document.getElementById("cg_customlfs_team_name").focus();
return false;
	}

if(!document.getElementById("cg_customlfs_game_name"))
	{
alert("Cannot find HTML Game Name Text Box");
return false;
	}
var game_name_use = document.getElementById("cg_customlfs_game_name").value;
if(game_name_use == "")
	{
alert("No Game Selected");
return false;
	}


if(!document.getElementById("cg_customlfs_platform_name"))
	{
return false;
	}
var platform_name_use = document.getElementById("cg_customlfs_platform_name").value;




if(!document.getElementById("cg_customlfs_map_name"))
	{
alert("Cannot find HTML Map Name Text Box");
document.getElementById("cg_customlfs_map_name").focus();
return false;
	}
var map_name_use = trim(document.getElementById("cg_customlfs_map_name").value);

var level = cg_radio_input_checked_value("cg_customlfs_radio");


var server_provided = 0;
if(document.getElementById("cg_customlfs_server_provided") && document.getElementById("cg_customlfs_server_provided").checked == true)
	{
var server_provided = 1;
	}


var id_req = "cg_lfs_enter_team_custom" + rand(9999);

cg_alert(id_req, "Processing Request", "LOOKING FOR SCRIM", 0, true);



var xmlHttp = new_connection();
if(xmlHttp)
{
xmlHttp.onreadystatechange=function()
{
	if(xmlHttp.readyState==4)
	{
var r=xmlHttp.responseText;
if(r == "good")
		{
cg_alert(id_req, "Successfully added team", "LOOKING FOR SCRIM", 0, true);
cg_update_smartbar();
		}
		else if(r == "tomany")
		{
cg_alert(id_req, "ERROR, already LFS with too many teams", "LOOKING FOR SCRIM", 0, true);
		}
		else
		{
cg_alert(id_req, "An error has occurred:"+r, "LOOKING FOR SCRIM", 0, true);
		}

	}
}

var url=rootdir+"xml/lfscustom.php?teamname="+urlencode(team_name_use)+"&map="+urlencode(map_name_use)+"&server="+server_provided+"&platform="+platform_name_use+"&game="+game_name_use;
url=url+"&chk="+Math.random();
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}






}



function cg_lfs_handle_content(ret)
{
if(!document.getElementById("cg_lfs_active_list"))
	{
return false;
	}
var lfs_arr=ret.split('|||');
if(isset(lfs_arr[1]))
	{
document.getElementById("cg_lfs_active_list").innerHTML=lfs_arr[0];
if(document.getElementById("sb_lfs_total_a"))
	{
document.getElementById("sb_lfs_total_a").innerHTML=lfs_arr[1];
	}
if(document.getElementById("sb_lfs_total_b"))
	{
document.getElementById("sb_lfs_total_b").innerHTML=lfs_arr[1];
	}
	}
}

function FormatPrice(amount)
{
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}

function cg_who_quoted_me(u_id, sectionid)
{
var id = "who_quoted_me_area";
if(!document.getElementById(id))
	{
return false;
	}
if(u_id <= 0)
	{
return false;
	}


document.getElementById(id).innerHTML='<div align="center"><b>Loading...</b><br /><br /></div>';
document.getElementById(id).style.display="";


var xmlHttpch = new_connection();
xmlHttpch.onreadystatechange=function()
{
if(xmlHttpch.readyState==4)
{
var ret = xmlHttpch.responseText;
if(ret == '' || ret == null || ret == 'undefined')
{
return;
}
if(ret == "noresults")
	{
ret = '<div align="center"><b>No results found</b><br /></div>';
	}

document.getElementById(id).innerHTML=ret;
document.getElementById(id).style.display="";

}
}


var page_part = '';
var page = get_page();
if(page != '')
	{
page_part = '&page='+page;
	}

var url=rootdir+"xml/search.php?area=forums&who_quoted_uid="+u_id+"&sectionid="+sectionid + page_part;
url=url+"&chk="+Math.random();
xmlHttpch.open("GET",url,true);
xmlHttpch.send(null);




}


function get_page()
	{
var page = gethashhrefval();
if(page != false && page != '' && substr(page, 0, 5) == 'page-')
	{
return substr(page, 5);
	}
return '';
	}


function update_page_check_forums(u_id, search_section)
{


if(document.getElementById("who_quoted_me_area"))
	{
var id = "who_quoted_me_area";
	}
else if(document.getElementById('search_results_area'))
	{
var id = "search_results_area";
	}
else
	{
return false;
	}
setTimeout(function() {	document.getElementById(id).innerHTML='<div align="center"><b>Loading Page: '+get_page()+'...</b><br /></div>'; },10);
if(document.getElementById('search_results_area'))
	{
setTimeout("search_exec('"+search_section+"')",25);
	}
else if(document.getElementById('who_quoted_me_area'))
	{
setTimeout("cg_who_quoted_me("+u_id+", "+search_section+")",25);
	}
	else if(userid == 1)
	{
alert("err");
	}
}


function cg_browser_width()
{
var W = screen.width;
if (parseInt(navigator.appVersion)>3) {
 if (navigator.appName=="Netscape") {
  W = window.innerWidth;
 }
 if (navigator.appName.indexOf("Microsoft")!=-1) {
  W = document.body.offsetWidth;
 }
}
return W;
}


function cg_browser_height()
{
var H = screen.height;
if (parseInt(navigator.appVersion)>3) {
 if (navigator.appName=="Netscape") {
  H = window.innerHeight;
 }
 if (navigator.appName.indexOf("Microsoft")!=-1) {
  H = document.body.offsetHeight;
 }
}
return H;
}

function cg_adupdate()
{
if (typeof global_ads_blocked == "undefined")
{
return false;
}

	if(global_ads_blocked == true)
	{

		var xmlHttp = new_connection();
		if(xmlHttp)
		{
			xmlHttp.onreadystatechange=function()
			{
				if(xmlHttp.readyState==4)
				{
				var i=xmlHttp.responseText;
				
				return false;
				}
			};
		var url=rootdir+"xml/cg_adstat.php?chk="+Math.random();
		xmlHttp.open("GET",url,true);
		xmlHttp.send(null);
		}
	}
}
setTimeout("cg_adupdate()", 1500);


function CGForumAddFav(secid, val)
{
var val_opposite = 0;
var val_words = "Remove from Favorites";
if(val == 0)
		{
val_opposite = 1;
val_words = "Add to Favorites";
		}
var xmlHttp = new_connection();
if(xmlHttp)
{
	xmlHttp.onreadystatechange=function()
	{
	if(xmlHttp.readyState==4)
	{
	var i=xmlHttp.responseText;
	if(i == "success")
		{
if(document.getElementById('addfavpart'))
{
document.getElementById('addfavpart').innerHTML='<img src="'+cgmirrordir+'images/icons/simple_small20/_05.png" width="20" height="20" /><a href="#" onclick="CGForumAddFav('+secid+', '+val_opposite+');return false;">'+val_words+'</a>';
}
		}
else if(userid == 1)
			{
alert(i);
			}

	return false;
	}
	};
var url=rootdir+"xml/cg_forumfav.php?id="+secid+"&val="+val+"&chk="+Math.random();
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
return false;
}



function cg_homepageload(area)
{
var hpage_arr = new Array("shoutcasts", "events", "all");


var tot_arr = hpage_arr.length;
for(var i=0;i < tot_arr;i++)
{
	if(hpage_arr[i] == area)
	{
display_show("cghpage_" + hpage_arr[i]);
display_show("cghpagemore_" + hpage_arr[i]);
if(document.getElementById("cghpagemenu_"+hpage_arr[i]))
		{
document.getElementById("cghpagemenu_"+hpage_arr[i]).className="active";
		}
	}
	else
	{
display_hide("cghpage_" + hpage_arr[i]);
display_hide("cghpagemore_" + hpage_arr[i]);
if(document.getElementById("cghpagemenu_"+hpage_arr[i]))
		{
document.getElementById("cghpagemenu_"+hpage_arr[i]).className="";
		}
	}
}



}


function cgstack_showhide(whatid)
{
var save_me = false;
var buttonid = whatid + "button";
if(document.getElementById(whatid) && document.getElementById(buttonid))
{
}
else
{
return false;
}

if(document.getElementById(whatid).style.display == "none")
	{
document.getElementById(whatid).style.display="";
document.getElementById(buttonid).innerHTML="-";
display_show(whatid + "_a");
display_show(whatid + "_b");
display_show(whatid + "_c");
display_show(whatid + "_menu");

	}
else
	{
document.getElementById(whatid).style.display="none";
document.getElementById(buttonid).innerHTML="+";
display_hide(whatid + "_a");
display_hide(whatid + "_b");
display_hide(whatid + "_c");
display_hide(whatid + "_menu");
save_me = true;
	}


var cook_key = "cgplusminus_" + userid;
var check_cook = readCookie(cook_key);
var current_cook = "";
if(check_cook != '' && check_cook != null && check_cook != false && check_cook != 'undefined')
{
current_cook = check_cook;
}


var what_check = "-" + whatid + "-";

var pos = false;
if(current_cook != "")
{
var pos = strpos(current_cook, what_check);
}
if(pos === false || isNaN(pos))
{
if(save_me == true)
	{
	if(current_cook == "")
	{
		current_cook = "-";
	}
	current_cook = current_cook + whatid + "-";
	}
}
else if(save_me == false) //exists and done want to save.
	{
if(current_cook != "") // always true..
		{
current_cook=str_replace(what_check, "", current_cook);
		}
	}

createCookie(cook_key,current_cook,180); // must always save even if empty, could/should remove cookie if empty instead however.
}




/*
    http://www.JSON.org/json2.js
    2010-08-25

    Public Domain.

    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

    See http://www.JSON.org/js.html


    This code should be minified before deployment.
    See http://javascript.crockford.com/jsmin.html

    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.


    This file creates a global JSON object containing two methods: stringify
    and parse.

        JSON.stringify(value, replacer, space)
            value       any JavaScript value, usually an object or array.

            replacer    an optional parameter that determines how object
                        values are stringified for objects. It can be a
                        function or an array of strings.

            space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as '\t' or '&nbsp;'),
                        it contains the characters used to indent at each level.

            This method produces a JSON text from a JavaScript value.

            When an object value is found, if the object contains a toJSON
            method, its toJSON method will be called and the result will be
            stringified. A toJSON method does not serialize: it returns the
            value represented by the name/value pair that should be serialized,
            or undefined if nothing should be serialized. The toJSON method
            will be passed the key associated with the value, and this will be
            bound to the value

            For example, this would serialize Dates as ISO strings.

                Date.prototype.toJSON = function (key) {
                    function f(n) {
                        // Format integers to have at least two digits.
                        return n < 10 ? '0' + n : n;
                    }

                    return this.getUTCFullYear()   + '-' +
                         f(this.getUTCMonth() + 1) + '-' +
                         f(this.getUTCDate())      + 'T' +
                         f(this.getUTCHours())     + ':' +
                         f(this.getUTCMinutes())   + ':' +
                         f(this.getUTCSeconds())   + 'Z';
                };

            You can provide an optional replacer method. It will be passed the
            key and value of each member, with this bound to the containing
            object. The value that is returned from your method will be
            serialized. If your method returns undefined, then the member will
            be excluded from the serialization.

            If the replacer parameter is an array of strings, then it will be
            used to select the members to be serialized. It filters the results
            such that only members with keys listed in the replacer array are
            stringified.

            Values that do not have JSON representations, such as undefined or
            functions, will not be serialized. Such values in objects will be
            dropped; in arrays they will be replaced with null. You can use
            a replacer function to replace those with JSON values.
            JSON.stringify(undefined) returns undefined.

            The optional space parameter produces a stringification of the
            value that is filled with line breaks and indentation to make it
            easier to read.

            If the space parameter is a non-empty string, then that string will
            be used for indentation. If the space parameter is a number, then
            the indentation will be that many spaces.

            Example:

            text = JSON.stringify(['e', {pluribus: 'unum'}]);
            // text is '["e",{"pluribus":"unum"}]'


            text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
            // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

            text = JSON.stringify([new Date()], function (key, value) {
                return this[key] instanceof Date ?
                    'Date(' + this[key] + ')' : value;
            });
            // text is '["Date(---current time---)"]'


        JSON.parse(text, reviver)
            This method parses a JSON text to produce an object or array.
            It can throw a SyntaxError exception.

            The optional reviver parameter is a function that can filter and
            transform the results. It receives each of the keys and values,
            and its return value is used instead of the original value.
            If it returns what it received, then the structure is not modified.
            If it returns undefined then the member is deleted.

            Example:

            // Parse the text. Values that look like ISO date strings will
            // be converted to Date objects.

            myData = JSON.parse(text, function (key, value) {
                var a;
                if (typeof value === 'string') {
                    a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
                    if (a) {
                        return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
                            +a[5], +a[6]));
                    }
                }
                return value;
            });

            myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
                var d;
                if (typeof value === 'string' &&
                        value.slice(0, 5) === 'Date(' &&
                        value.slice(-1) === ')') {
                    d = new Date(value.slice(5, -1));
                    if (d) {
                        return d;
                    }
                }
                return value;
            });


    This is a reference implementation. You are free to copy, modify, or
    redistribute.
*/

/*jslint evil: true, strict: false */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
    call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
    getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
    lastIndex, length, parse, prototype, push, replace, slice, stringify,
    test, toJSON, toString, valueOf
*/


// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

if (!this.JSON) {
    this.JSON = {};
}

(function () {

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function (key) {

            return isFinite(this.valueOf()) ?
                   this.getUTCFullYear()   + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate())      + 'T' +
                 f(this.getUTCHours())     + ':' +
                 f(this.getUTCMinutes())   + ':' +
                 f(this.getUTCSeconds())   + 'Z' : null;
        };

        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function (key) {
            return this.valueOf();
        };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string) {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.

        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' + string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
    }


    function str(key, holder) {

// Produce a string from holder[key].

        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

// If the value has a toJSON method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

// What happens next depends on the value's type.

        switch (typeof value) {
        case 'string':
            return quote(value);

        case 'number':

// JSON numbers must be finite. Encode non-finite numbers as null.

            return isFinite(value) ? String(value) : 'null';

        case 'boolean':
        case 'null':

// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.

            return String(value);

// If the type is 'object', we might be dealing with an object or an array or
// null.

        case 'object':

// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.

            if (!value) {
                return 'null';
            }

// Make an array to hold the partial results of stringifying this object value.

            gap += indent;
            partial = [];

// Is the value an array?

            if (Object.prototype.toString.apply(value) === '[object Array]') {

// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.

                length = value.length;
                for (i = 0; i < length; i += 1) {
                    partial[i] = str(i, value) || 'null';
                }

// Join all of the elements together, separated with commas, and wrap them in
// brackets.

                v = partial.length === 0 ? '[]' :
                    gap ? '[\n' + gap +
                            partial.join(',\n' + gap) + '\n' +
                                mind + ']' :
                          '[' + partial.join(',') + ']';
                gap = mind;
                return v;
            }

// If the replacer is an array, use it to select the members to be stringified.

            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i += 1) {
                    k = rep[i];
                    if (typeof k === 'string') {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            } else {

// Otherwise, iterate through all of the keys in the object.

                for (k in value) {
                    if (Object.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            }

// Join all of the member texts together, separated with commas,
// and wrap them in braces.

            v = partial.length === 0 ? '{}' :
                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                        mind + '}' : '{' + partial.join(',') + '}';
            gap = mind;
            return v;
        }
    }

// If the JSON object does not yet have a stringify method, give it one.

    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {

// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.

            var i;
            gap = '';
            indent = '';

// If the space parameter is a number, make an indent string containing that
// many spaces.

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

// If the space parameter is a string, it will be used as the indent string.

            } else if (typeof space === 'string') {
                indent = space;
            }

// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                     typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }

// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.

            return str('', {'': value});
        };
    }


// If the JSON object does not yet have a parse method, give it one.

    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {

// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.

            var j;

            function walk(holder, key) {

// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.

            text = String(text);
            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.

// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

            if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                j = eval('(' + text + ')');

// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.

                return typeof reviver === 'function' ?
                    walk({'': j}, '') : j;
            }

// If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('JSON.parse');
        };
    }
}());





function handle_cg_jumptopage(element, id, before, after)
{
var pg_value = -1;
if(document.getElementById(id))
{
pg_value = document.getElementById(id).value;
}

if(pg_value == -1)
{
alert("Error changing page");
}
else if(isNaN(pg_value))
{
alert("Must enter a Number");
}
else if(pg_value <= 0)
{
alert("Must enter a Number greater than 0");
}
else if(pg_value > 0)
{
var link = before + pg_value + after;
window.location=link;
}
else
{
alert("Error changing page...");
}

}

function cg_load_summary(area, id, page, type)
{
var html_id = 'top_summary_' + area + '_' + id;


var xmlHttp = new_connection();
if(xmlHttp)
{
	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			var i=xmlHttp.responseText;
if(i != "" && i != "error" && i != "NOACCESS")
{
	if(document.getElementById(html_id))
	{
		document.getElementById(html_id).innerHTML=i;
	}
}

			return false;
		}
	};

var url=rootdir+"xml/top_summary.php?id="+id+"&area="+area+"&page="+page+"&type="+type;
url=url+"&chk="+Math.random();
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}

return false;
}



function cg_load_right_col_threads(html_id, platform, game, page, type_view)
{

if(html_id == "cgrightthreadslist" && type_view != "")
	{
createCookie("latest_right",type_view,160);
	}

var xmlHttp = new_connection();
if(xmlHttp)
{
	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			var i=xmlHttp.responseText;
if(i != "" && i != "error" && i != "NOACCESS")
{
	if(document.getElementById(html_id))
	{
		document.getElementById(html_id).innerHTML=i;
	}
}

			return false;
		}
	};

var url=rootdir+"xml/right_column_threads.php?platform="+platform+"&section="+game+"&page="+page+"&t="+html_id+"&typeview="+type_view;
url=url+"&chk="+Math.random();
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}


return false;
}


//CHAT FUNCTIONS START


function d_enterchat(e, id, chatroom_type, chatroom_id){
var unicode=e.charCode? e.charCode : e.keyCode
if (unicode == 13)
{
CG_CHAT_submit_text(id, chatroom_type, chatroom_id);
return false;
}
return true;
}

function CG_CHAT_submit_text(id, chatroom_type, chatroom_id)
{
if(!document.getElementById(id))
{
alert("Could not find Chat textbox");
return false;
}
var text_value = document.getElementById(id).value;
if(text_value == "")
	{
alert("Must enter some text");
return false;
	}
if(trim(text_value) == "Submitting...")
	{
document.getElementById(id).value="";
return false;
	}

//document.getElementById(id).value="Submitting...";
document.getElementById(id).value="";



var post_parameters = "post_text="+encodeURIComponent(text_value); 


var xmlHttp = new_connection();
xmlHttp.open('POST', rootdir+"xml/cg_chat_post.php?type="+chatroom_type+"&roomid="+chatroom_id+"&chk="+Math.random(), true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
var response = xmlHttp.responseText;
if(response == "post_saved")
{
if(trim(document.getElementById(id).value) == "Submitting...")
	{
document.getElementById(id).value="";
	}
//CG_CHATROOM_update_textarea_value("");
}
else if(response == "banned_from_channel")
{
alert("You have been banned from this channel, your post was not saved.");
document.getElementById(id).value=text_value; // put users text back into textbox so they can try again.
}
else if(response == "posting_to_fast")
{
alert("You are posting to fast, your post was not saved, please wait before trying again.");
document.getElementById(id).value=text_value; // put users text back into textbox so they can try again.
}
else
{
alert("Your Post Failed to Save, please retry");
if(userid == 1)
{
alert("Error: " + response);
}
CG_CHATROOM_update_textarea_value(text); // put users text back into textbox so they can try again.
}
}

};
xmlHttp.send(post_parameters);


return false;





}


function CG_CHAT_send_action(action, warning, room_id, u_id)
{

if (typeof room_id == "undefined")
{
return false;
}
else if (typeof u_id == "undefined")
{
return false;
}
else if(isset(room_id) && room_id != "" && room_id != null && room_id != "undefined" && room_id != false && isset(action) && action != "" && action != null && action != false && isset(u_id) && u_id != "" && u_id != null && u_id != false)
{
//assume room_id is fine.
}
else
{
return false;
}

var id_req = "room_" + room_id + "_" + u_id + "_" + rand(9999);

if(warning == "" || confirm(warning))
	{
	}
else
	{
return false;
	}
if(action == "loadbans")
{
}
else
{
cg_alert(id_req, "Processing Request", "CHATROOM ADMINISTRATION", 0, true);
}
//make CH load proper..

var xmlHttp = new_connection();
if(xmlHttp)
{
	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			var response=xmlHttp.responseText;
if(action == "loadbans" || action.substr(0, 8) == "loadbans")
			{
var html_id = "cg_chanbans_" + room_id;
if(document.getElementById(html_id))
{
document.getElementById(html_id).innerHTML=response;
}
else if(userid == 1)
				{
alert("not found");
				}




			}

if(action != "loadbans")
			{
cg_alert(id_req, '<b>' + response + '</b>', "CHATROOM ADMINISTRATION: ACTION COMPLETE", 3);
			}
if(action == "removeban")
			{
CG_CHAT_admin_loadbans(room_id); // reload ban list.
			}

			return false;
		}
	};

var url=rootdir+"xml/cg_chatroom_admin.php?type=CH&do_uid="+u_id+"&roomid="+room_id+"&"+action;
url=url+"&chk="+Math.random();
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}


return false;
}



function CG_CHAT_admin_loadbans(room_id)
{
CG_CHAT_send_action("loadbans", "", room_id, -9);
}






//CHAT FUNCTIONS END.



function cg_thread_poll_submit(thread_poll_id, answer_number, votechangeable)
{
var html_id = 'cgthreadpoll_area_' + thread_poll_id;
if(userid <= 0 && answer_number > 0)
	{
	alert("Must login to vote");
	return false;
	}
if(votechangeable == 1)
	{
if(confirm("Vote cannot be changed once submitted for this poll, proceed?") == false)
{
return false;
}
	}


var xmlHttp = new_connection();
if(xmlHttp)
{
	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			var response=xmlHttp.responseText;
if(response == "")
{
//happens when refreshing page etc whilst request happens.
}
else if(response == "error")
{
alert("An error has occured while voting in a thread poll.");
}
else if(response == "invalid")
{
alert("An error has occured while voting in a thread poll: INVALID.");
}
else if(response == "alreadyvoted")
{
alert("You have already voted in this poll and are not allowed to change your vote.");
}
else if(response == "votingclosed")
{
alert("Voting has been closed for this poll.");
}
else if(document.getElementById(html_id))
{
document.getElementById(html_id).innerHTML=response;
}
			return false;
		}
	};

var url=rootdir+"xml/cg_threadpoll_vote.php?id="+thread_poll_id+"&a="+answer_number;
url=url+"&chk="+Math.random();
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}




return false;
}


function ucfirst(text)
{
return text.substr(0, 1).toUpperCase() + text.substr(1);
}

function number_format(number, decimals, dec_point, thousands_sep)
	{
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

function utf8_encode ( argString ) {
    var string = (argString+''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");

    var utftext = "";
    var start, end;
    var stringl = 0;

    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;

        if (c1 < 128) {
            end++;
        } else if (c1 > 127 && c1 < 2048) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc !== null) {
            if (end > start) {
                utftext += string.substring(start, end);
            }
            utftext += enc;
            start = end = n+1;
        }
    }

    if (end > start) {
        utftext += string.substring(start, string.length);
    }

    return utftext;
}


function md5 (str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // + namespaced by: Michael White (http://getsprink.com)
    // +    tweaked by: Jack
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_encode
    // *     example 1: md5('Kevin van Zonneveld');
    // *     returns 1: '6e658d4bfcb59cc13f96c14450ac40b9'

    var xl;

    var rotateLeft = function (lValue, iShiftBits) {
        return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
    };

    var addUnsigned = function (lX,lY) {
        var lX4,lY4,lX8,lY8,lResult;
        lX8 = (lX & 0x80000000);
        lY8 = (lY & 0x80000000);
        lX4 = (lX & 0x40000000);
        lY4 = (lY & 0x40000000);
        lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
        if (lX4 & lY4) {
            return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
        }
        if (lX4 | lY4) {
            if (lResult & 0x40000000) {
                return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
            } else {
                return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
            }
        } else {
            return (lResult ^ lX8 ^ lY8);
        }
    };

    var _F = function (x,y,z) { return (x & y) | ((~x) & z); };
    var _G = function (x,y,z) { return (x & z) | (y & (~z)); };
    var _H = function (x,y,z) { return (x ^ y ^ z); };
    var _I = function (x,y,z) { return (y ^ (x | (~z))); };

    var _FF = function (a,b,c,d,x,s,ac) {
        a = addUnsigned(a, addUnsigned(addUnsigned(_F(b, c, d), x), ac));
        return addUnsigned(rotateLeft(a, s), b);
    };

    var _GG = function (a,b,c,d,x,s,ac) {
        a = addUnsigned(a, addUnsigned(addUnsigned(_G(b, c, d), x), ac));
        return addUnsigned(rotateLeft(a, s), b);
    };

    var _HH = function (a,b,c,d,x,s,ac) {
        a = addUnsigned(a, addUnsigned(addUnsigned(_H(b, c, d), x), ac));
        return addUnsigned(rotateLeft(a, s), b);
    };

    var _II = function (a,b,c,d,x,s,ac) {
        a = addUnsigned(a, addUnsigned(addUnsigned(_I(b, c, d), x), ac));
        return addUnsigned(rotateLeft(a, s), b);
    };

    var convertToWordArray = function (str) {
        var lWordCount;
        var lMessageLength = str.length;
        var lNumberOfWords_temp1=lMessageLength + 8;
        var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
        var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
        var lWordArray=new Array(lNumberOfWords-1);
        var lBytePosition = 0;
        var lByteCount = 0;
        while ( lByteCount < lMessageLength ) {
            lWordCount = (lByteCount-(lByteCount % 4))/4;
            lBytePosition = (lByteCount % 4)*8;
            lWordArray[lWordCount] = (lWordArray[lWordCount] | (str.charCodeAt(lByteCount)<<lBytePosition));
            lByteCount++;
        }
        lWordCount = (lByteCount-(lByteCount % 4))/4;
        lBytePosition = (lByteCount % 4)*8;
        lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
        lWordArray[lNumberOfWords-2] = lMessageLength<<3;
        lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
        return lWordArray;
    };

    var wordToHex = function (lValue) {
        var wordToHexValue="",wordToHexValue_temp="",lByte,lCount;
        for (lCount = 0;lCount<=3;lCount++) {
            lByte = (lValue>>>(lCount*8)) & 255;
            wordToHexValue_temp = "0" + lByte.toString(16);
            wordToHexValue = wordToHexValue + wordToHexValue_temp.substr(wordToHexValue_temp.length-2,2);
        }
        return wordToHexValue;
    };

    var x=[],
        k,AA,BB,CC,DD,a,b,c,d,
        S11=7, S12=12, S13=17, S14=22,
        S21=5, S22=9 , S23=14, S24=20,
        S31=4, S32=11, S33=16, S34=23,
        S41=6, S42=10, S43=15, S44=21;

    str = this.utf8_encode(str);
    x = convertToWordArray(str);
    a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
    
    xl = x.length;
    for (k=0;k<xl;k+=16) {
        AA=a; BB=b; CC=c; DD=d;
        a=_FF(a,b,c,d,x[k+0], S11,0xD76AA478);
        d=_FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
        c=_FF(c,d,a,b,x[k+2], S13,0x242070DB);
        b=_FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
        a=_FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
        d=_FF(d,a,b,c,x[k+5], S12,0x4787C62A);
        c=_FF(c,d,a,b,x[k+6], S13,0xA8304613);
        b=_FF(b,c,d,a,x[k+7], S14,0xFD469501);
        a=_FF(a,b,c,d,x[k+8], S11,0x698098D8);
        d=_FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
        c=_FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
        b=_FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
        a=_FF(a,b,c,d,x[k+12],S11,0x6B901122);
        d=_FF(d,a,b,c,x[k+13],S12,0xFD987193);
        c=_FF(c,d,a,b,x[k+14],S13,0xA679438E);
        b=_FF(b,c,d,a,x[k+15],S14,0x49B40821);
        a=_GG(a,b,c,d,x[k+1], S21,0xF61E2562);
        d=_GG(d,a,b,c,x[k+6], S22,0xC040B340);
        c=_GG(c,d,a,b,x[k+11],S23,0x265E5A51);
        b=_GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
        a=_GG(a,b,c,d,x[k+5], S21,0xD62F105D);
        d=_GG(d,a,b,c,x[k+10],S22,0x2441453);
        c=_GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
        b=_GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
        a=_GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
        d=_GG(d,a,b,c,x[k+14],S22,0xC33707D6);
        c=_GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
        b=_GG(b,c,d,a,x[k+8], S24,0x455A14ED);
        a=_GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
        d=_GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
        c=_GG(c,d,a,b,x[k+7], S23,0x676F02D9);
        b=_GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
        a=_HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
        d=_HH(d,a,b,c,x[k+8], S32,0x8771F681);
        c=_HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
        b=_HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
        a=_HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
        d=_HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
        c=_HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
        b=_HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
        a=_HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
        d=_HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
        c=_HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
        b=_HH(b,c,d,a,x[k+6], S34,0x4881D05);
        a=_HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
        d=_HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
        c=_HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
        b=_HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
        a=_II(a,b,c,d,x[k+0], S41,0xF4292244);
        d=_II(d,a,b,c,x[k+7], S42,0x432AFF97);
        c=_II(c,d,a,b,x[k+14],S43,0xAB9423A7);
        b=_II(b,c,d,a,x[k+5], S44,0xFC93A039);
        a=_II(a,b,c,d,x[k+12],S41,0x655B59C3);
        d=_II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
        c=_II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
        b=_II(b,c,d,a,x[k+1], S44,0x85845DD1);
        a=_II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
        d=_II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
        c=_II(c,d,a,b,x[k+6], S43,0xA3014314);
        b=_II(b,c,d,a,x[k+13],S44,0x4E0811A1);
        a=_II(a,b,c,d,x[k+4], S41,0xF7537E82);
        d=_II(d,a,b,c,x[k+11],S42,0xBD3AF235);
        c=_II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
        b=_II(b,c,d,a,x[k+9], S44,0xEB86D391);
        a=addUnsigned(a,AA);
        b=addUnsigned(b,BB);
        c=addUnsigned(c,CC);
        d=addUnsigned(d,DD);
    }

    var temp = wordToHex(a)+wordToHex(b)+wordToHex(c)+wordToHex(d);

    return temp.toLowerCase();
}



	
function CG_stream_start(file_id)
{
if(isNaN(file_id))
	{
if(file_id.substr(0, 12) == "audioplayer_")
		{
file_id = file_id.substr(12);
		}
	}


var xmlHttp = new_connection();
if(xmlHttp)
{
xmlHttp.onreadystatechange=function()
{
	if(xmlHttp.readyState==4)
	{
		var i=xmlHttp.responseText;
		if(i == "" || i == null || i == "undefined" || i == false)
		{
		return;
		}

		if(!isNaN(i) && i > 0)
		{
if(document.getElementById("streamed_today_amount"))
	{
document.getElementById("streamed_today_amount").innerHTML=i;
}
		return true;
		}
		else if(userid == 1)
		{
		alert("Error: " + i);
		}
		return false;
	}
}
var url=rootdir+"xml/streamhit.php?id="+file_id;
url=url+"&chk="+Math.random();
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}

}


function cg_buddy_acceptdeny(u_id, val, htmlid)
{


if(document.getElementById(htmlid) && val == 1)
{
document.getElementById(htmlid).innerHTML="Accepting...";
}
else if(document.getElementById(htmlid) && val == 0)
{
document.getElementById(htmlid).innerHTML="Declining...";
}


var xmlHttp = new_connection();
if(xmlHttp)
{
xmlHttp.onreadystatechange=function()
{
	if(xmlHttp.readyState==4)
	{
		var i=xmlHttp.responseText;
if(i == "" || i == null || i == "undefined" || i == false)
{
return;
}
if(i == "success" && document.getElementById(htmlid))
{
document.getElementById(htmlid).parentNode.style.display="none";
}
else if(i == "notfound")
{
alert("An error has occurred whilst accepting/declining the buddy invitation");
}
else if(userid == 1)
		{
alert(i);
		}
		return false;
	}
}
var url=rootdir+"xml/buddyacceptdecline.php?id="+u_id+"&accept="+val;
url=url+"&chk="+Math.random();
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}

return false;

}


function extractIFrameBody(iFrameEl) {
 
var iframeid =  document.getElementById(iFrameEl);
return iframeid.contentWindow.document.body.innerHTML;


  var doc = null;
  if (iFrameEl.contentDocument) { // For NS6
    doc = iFrameEl.contentDocument; 
  } else if (iFrameEl.contentWindow) { // For IE5.5 and IE6
    doc = iFrameEl.contentWindow.document;
  } else if (iFrameEl.document) { // For IE5
    doc = iFrameEl.document;
  } else {
    alert("Error: could not find iFrame document");
    return null;
  }
  return doc.body;
 
}


var json_overall_count = 0;
function cg_json_call(url)
{
json_overall_count++;
var html_id = "cgjsondemand" + json_overall_count;
if(json_overall_count > 5)
	{
var old_number = json_overall_count - 5;
var old_html_id = "cgjsondemand" + old_number;
var oldscript = document.getElementById(old_html_id);
oldscript.parentNode.removeChild(oldscript);
delete oldscript;
	}
var head = document.getElementsByTagName("head")[0];
script = document.createElement('script');
script.id = html_id;
script.type = 'text/javascript';
script.src = url;
head.appendChild(script);
}








function ajaxObjectJK(url, callbackFunction) { // callbackFunction must be a string of the function to send data.
  var that=this;
if (typeof callbackFunction == "undefined")
{
var callbackFunction = ""; // fail safe.
}
  this.callbackfunc = callbackFunction;
  this.url = url;
  this.abort = function() {
//Does nothing.
  }



this.update = function(passData,postMethod)
{

if (typeof(passData) == 'undefined' || passData == null) {
passData = "";
}
	if (typeof(globalsite) == 'undefined') {
	var uri=that.url+'?'+passData+'&retfunc='+urlencode(that.callbackfunc);
	}
	else
	{
	var uri=that.url+'&chk='+Math.random()+passData+'&retfunc='+urlencode(that.callbackfunc); // Live Site.
	}
	cg_json_call(uri);
}

return true;                                             
}


function cg_default_game_load(plat, game)
{
if(userid <= 0)
	{
return false;
	}
if(global_user_default_platform == plat && global_user_default_game == game && document.getElementById('cg_make_this_default_game'))
{
document.getElementById('cg_make_this_default_game').innerHTML="This is my default game";
}
return true;
}

function cg_set_default_game(plat, game)
{
if(userid <= 0)
	{
alert("You must register/login first");
return false;
	}


var xmlHttp = new_connection();
if(xmlHttp)
{
	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			var i=xmlHttp.responseText;
			if(i == "success")
			{
				if(document.getElementById('cg_make_this_default_game'))
				{
				document.getElementById('cg_make_this_default_game').innerHTML="This is now my default game";
				}
			}
			else
			{
				if(document.getElementById('cg_make_this_default_game'))
				{
				document.getElementById('cg_make_this_default_game').innerHTML="Failed to save";
				}
			}

			return false;
		}
	};

var url=rootdir+"xml/cg_set_default_game.php?platform="+plat+"&game="+game;
url=url+"&chk="+Math.random();
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}



}


function cg_pug_size_change(htmlid, make_bigger)
{

var id_a = "pug_chatwindow";
var id_b = "pug_chatusers_wrapper";
var id_c = htmlid + "_cg_chat";

var chatwindow_height = 330;

				if(document.getElementById(id_a))
				{
var cur_temp = trim(document.getElementById(id_a).style.height); // default is 330
if(cur_temp != "")
					{
cur_temp = cur_temp.replace(/px/g,'');
chatwindow_height = cur_temp / 1;
					}

				}


if(make_bigger == true)
	{
if(chatwindow_height < 700)
	{
chatwindow_height = chatwindow_height + 40;
	}
	}
	else
	{
if(chatwindow_height > 190)
		{
chatwindow_height = chatwindow_height - 40;
		}
	}



var users_height = chatwindow_height - 20;
var pug_chattext_height = chatwindow_height - 80;






				if(document.getElementById(id_a))
				{
				document.getElementById(id_a).style.height=chatwindow_height + "px";
				}
				if(document.getElementById(id_b))
				{
				document.getElementById(id_b).style.height=users_height + "px";
				}
				if(document.getElementById(id_c))
				{
				document.getElementById(id_c).style.height=pug_chattext_height + "px";
				}





}


function CG_PUG_play_sound()
{

	if (typeof smartbar != "undefined")
	{
		if(smartbar) {smartbar.playSound("pugstart");}
	}
do_title_flash("READY UP");
}

cg_global_js_loaded = true; // must be at end.
