var p=false, q=false;
var conv = new Array();
var sending=false;
var tID=null;
var tNoID=null;
var myWinFocus=true;

var m_nick, m_my_nick;

var tips_old_text;
var is_first_nick=true;




var emo=new Array('8-o', '%-)', ':-<', ':roll:', ':no:', '8-)', ':->', ';-(', ':-)', ';-p', ':-D', ':-p', ':hangover:', ':inlove:', ':annoyed:', ':asleep:', ':blush:', '=(', ':e', ':)', ';)', ':@', ':(', '8)', ':bow:');

var RootURL;


function CaretPosition() {
 var start = null;
 var end = null;
}
function getCaretPosition(oField) {
 var oCaretPos = new CaretPosition();
 // IE support
 if(document.selection)
 {
  oField.focus();
  var oSel = document.selection.createRange();
  var selectionLength = oSel.text.length;
  oSel.moveStart ('character', -oField.value.length);
  oCaretPos.start = oSel.text.length - selectionLength;
  oCaretPos.end = oSel.text.length;
 }
 // Firefox support
 else if(oField.selectionStart || oField.selectionStart == '0')
 {
  // This is a whole lot easier in Firefox
  oCaretPos.start = oField.selectionStart;
  oCaretPos.end = oField.selectionEnd;
 }
 return (oCaretPos);
}



function insert_emo(ei) {
	var txtarea = document.cf.txtChat;
	var caretPos = getCaretPosition(txtarea);
	
	txtarea.value = txtarea.value.substring(0, caretPos.start) + ' ' + emo[ei] + ' ' + txtarea.value.substring(caretPos.end);
	txtarea.focus();
}


function replaceAll(str, from, to) {
  if(from=='') return str;
  
    var idx = str.indexOf(from);
    while (idx > -1) {
        str = str.replace(from,to);
        idx = str.indexOf(from, 1);
    }
    return str;
}

function set_html(id, cont) {
  if(document.getElementById) {
    document.getElementById(id).innerHTML = cont;
  }
  else {
    if(document.layers) document.id.innerHTML = cont; else document.all.id.innerHTML = cont;
  }
}

function set_el(id, dstyle) {
  if(document.getElementById) {
    document.getElementById(id).style.display = dstyle;
  }
  else {
    if(document.layers) document.id.style.display = dstyle; else document.all.id.style.display = dstyle;
  }
}

function get_html(id) {
  if(document.getElementById) {
    return document.getElementById(id).innerHTML;
  }
  else {
    if(document.layers) return document.id.innerHTML; else return document.all.id.innerHTML;
  }
}

function clear_chat_status() {
  set_html('chat_msg', '&nbsp;');
}

function set_chat_status(stat,time_out) {
  set_html('chat_msg', stat);
  
  if(time_out>0) {
    clearTimeout(tNoID);
    tNoID = setTimeout("clear_chat_status()",time_out);
  }
}

function set_pseudo_textbox() {
  if(is_first_nick) {
    document.cf.txtPseudo.value = 'new nickname';
    setTimeout("clear_pseudo_textbox()",1000);
  }
}

function clear_pseudo_textbox() {
  if(document.cf.txtPseudo.value == 'new nickname') document.cf.txtPseudo.value = '';
}

function set_tip() {
  tips_old_text = get_html('pseudo_tip');
  set_html('pseudo_tip', '<b>Your temporary nickname for this chat</b> &mdash; a roleplaying game, anyone?<br>Real nickname is shown in <b style="color: #45C;">blue</b>, fake nickname in <b style="color: #333;">black</b>.');
}

function clear_tip() {
  set_html('pseudo_tip', tips_old_text);
}


function init_chat() {
  /*@cc_on @*/
  /*@if (@_jscript_version >= 5)
  try {
  	p = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
  	try {
  		p = new ActiveXObject("Microsoft.XMLHTTP");
  	} catch (E) {p = false;}
  }
  @end @*/
  if (!p) p = new XMLHttpRequest();
  
  /*@cc_on @*/
  /*@if (@_jscript_version >= 5)
  try {
  	q = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
  	try {
  		q = new ActiveXObject("Microsoft.XMLHTTP");
  	} catch (E) {q = false;}
  }
  @end @*/
  if (!q) q = new XMLHttpRequest();
  
  
  if(!p || !q) {
    set_html('chat_content', '<div style="color: #900;"><b>Sorry, your Internet browser does not support this chat feature.</b><br>Please tell us your browser specification and we will take a look.<br>We apologize for this inconvenience.</div>');
    return;
  }
  
  
  
  var temo='';
  for(var i=0;i<emo.length;i++) temo = temo + '<a href="javascript:" title="' + emo[i] + '" onclick="insert_emo(\'' + i + '\'); return false;"><img src="' + RootURL + 'images/emo/' + (i+1) + '.gif" border="0"></a> ';
  set_html('emo_list', temo);
  
  doFetch(true);
}


function handle_fetch() {
  if(q.readyState==4 && q.status==200) {
    if(q.responseText!='E' && q.responseText!='U' && q.responseText.length>3) {
  		var tmp = q.responseText.split('<br>');
  		
  		var ci=0, sc;
  		var t_forecolor, t_bgcolor;
  		var t_nick, t_content, t_nick_display, t_nick_title, t_nick_forecolor;
  		var res_join;
  		
  		while(ci<tmp.length) {
    		sc=tmp[ci].indexOf(':');
    		
    		if(tmp[ci].substr(0,sc)==m_nick) {t_forecolor='#222'; t_bgcolor='#F9F9F9';} else {t_forecolor='#45A'; t_bgcolor='#FFF';}
    		
    		t_nick=tmp[ci].substr(0,sc);
    		t_content=tmp[ci].substr(sc+1,tmp[ci].length-sc);
    		
    		t_nick_display = t_nick;
    		t_nick_title = '';
    		
    		if(t_content.substr(0,1)=='{') {
      		sc=t_content.indexOf('}',2);
      		if(sc>0) {
        		t_nick_display = t_content.substr(1,sc-1);
        		
        		if(t_nick_display.replace(/^\s*|\s*$/g,"")!='') {
        		  t_nick_title = t_nick;
        		  t_content = t_content.substr(sc+1,t_content.length-sc-1);
      		  }
      		  else t_nick_display = t_nick;
      		}
    		}
    		
    		if(t_content.substr(0,4).toLowerCase()=='/me ') {
      		t_content=t_content.substr(4,t_content.length-4);
      		t_forecolor='#F88';
      		t_nick_forecolor='#F88';
      		if(t_nick_title!='') t_nick_forecolor='#E66';
      		tmp[ci]='<div style="background-color: ' + t_bgcolor + ';"><b><a href="' + RootURL + t_nick + '" style="text-decoration: none; color: ' + t_nick_forecolor + ';" title="' + t_nick_title + '">' + t_nick_display + '</a> <span style="color: ' + t_forecolor +';">' + t_content + '</span></b></div>';
    		}
    		else {
      		t_nick_forecolor='#45C';
      		if(t_nick_title!='') t_nick_forecolor='#333';
    		  tmp[ci]='<div style="background-color: ' + t_bgcolor + ';"><b><a href="' + RootURL + t_nick + '" style="text-decoration: none; color: ' + t_nick_forecolor + ';" title="' + t_nick_title + '">' + t_nick_display + '</a>:</b> <span style="color: ' + t_forecolor +';">' + t_content + '</span></div>';
  		  }
  		  
    		ci+=1;
  		}
  		
  		conv = tmp.concat(conv);
  		if(conv.length>10) conv.splice(10,conv.length-10);
  		
  		res_join = conv.join('');
  		
  		for(var e=0;e<emo.length;e++) {
  		  res_join = replaceAll(res_join, emo[e].replace('<', '&lt;').replace('>', '&gt;'), '<img src="' + RootURL + 'images/emo/' + (e+1) + '.gif" border="0">');
		  }
  		
  		set_html('chat_content', res_join);
  	}
  	else {
  		if(conv.length==0) {
    		if(m_nick==m_my_nick)
  			  set_html('chat_content', '<div style="color: #333;">Here you can chat with your friends in real-time.<br>Type anything in the text field above and press <b>Enter</b>.<br><br><b>This chat can be accessed by all people who open your profile page.</b><br>--> Ask your friends to open your profile page and chat with them!</div>');
  			else
  			  set_html('chat_content', '<div style="color: #333;">Here you can chat with your friend in real-time.<br>Type anything in the text field above and press <b>Enter</b>.<br><br>This chatroom is owned by <b>' + m_nick + '</b>.</div>');
  		}
  	}
  	
  	clearTimeout(tID);
    tID = setTimeout("doFetch(false)",2000);
  }
}


function doFetch(isfirst) {
	if(sending) {
  	clearTimeout(tID);
  	
		if(isfirst)
		  tID = setTimeout("doFetch(true)",1500);
		else
		  tID = setTimeout("doFetch(false)",1500);
		  
		return;
	}
	
	/*
	if(!myWinFocus) {
  	clearTimeout(tID);
  	tID = setTimeout("doFetch(true)",500);
  	return;
	}
	*/
	
	if(isfirst) {
  	conv.splice(0,conv.length);
	  q.open('GET', RootURL + 'getchatroom.php?all=1&id='+m_nick, true);
  }
	else {
	  q.open('GET', RootURL + 'getchatroom.php?id='+m_nick, true);
  }
	
	q.onreadystatechange = handle_fetch;
	q.send(null);
}

function doRefresh() {
  clearTimeout(tID);
  doFetch(true);
}

function doSend() {
  if(!p || !q) return;
  
  
  if(m_my_nick=='') {
    alert('Please login to send chat.');
    return;
  }
  
  
  var cont = document.cf.txtChat.value;
	cont = cont.replace(/^\s*|\s*$/g,"");
	if(cont.length<1) {
	  document.cf.txtChat.focus();
	  return false;
  }
  
  if(sending) return;
  
  sending = true;
  
  set_chat_status('<b style="color: #9BF;">Sending...</b>',0);
  
  document.cf.txtChat.value='';
	document.cf.txtChat.focus();
	
	var pseu = document.cf.txtPseudo.value;
	pseu = pseu.replace(/^\s*|\s*$/g,"");
	
  if(pseu.length>0 && pseu.toLowerCase()!=m_my_nick.toLowerCase()) cont = '{' + pseu + '}' + cont;
	
	
	
	p.open('GET', RootURL + 'saychatroom.php?id='+m_nick+'&t='+encodeURIComponent(cont),false);
	p.send(null);
	
	clear_chat_status();
	
	if(p.responseText!='S') {
		if(p.responseText=='D') set_chat_status('<b style="color: #F00;">The chatroom has been disabled</b>',7500);
		if(p.responseText=='M') set_chat_status('<b style="color: #C33;">You have made too many consecutive posts.</b>',4000);
		if(p.responseText=='B') set_chat_status('<b style="color: #F00;">You have been blacklisted by the chatroom owner.</b>',10000);
		if(p.responseText=='F') set_chat_status('<b style="color: #C33;">You are not listed on the Friends List.</b>',5000);
	}
	
	sending = false;
}


//window.onfocus = new Function("myWinFocus=true;");
//window.onblur = new Function("myWinFocus=false;");





var recent_pc='';

var hug_text_length;

var theObj;

var fr_desc;

function getPosition(e) {   //Thank Beau Hartshorne for this snippet
  e=e || window.event;
  var cursor = {x:0,y:0};
  if (e.pageX || e.pageY) {
      cursor.x=e.pageX;
      cursor.y=e.pageY;
  }
  else {
      cursor.x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
      cursor.y = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop;
  }
  return cursor;
}

function oeTipHide() {
  document.getElementById('thOeTip').style.display="none";
}
function oeTip(text,me) {
  theObj=me;
  theObj.onmousemove=updatePos;
  document.getElementById('thOeTip').innerHTML=text;
  document.getElementById('thOeTip').style.display="block";
  me.title='';
  window.onscroll=updatePos;
}
function updatePos() {
  var ev=arguments[0]?arguments[0]:event;
  var cur=getPosition(ev);
  var x=cur.x;
  var y=cur.y
  diffX=-220;
  diffY=-2;
  document.getElementById('thOeTip').style.top  = y-2+diffY+ "px";
  document.getElementById('thOeTip').style.left = x-2+diffX+ "px";
}

function hif() {
  document.getElementById('thFriendInfo').style.display="none";
}
function shf(nick,desc,f_info,login,ldays,me) {
  theObj=me;
  theObj.onmousemove=updatePosFriend;
  
  if(desc!='') desc = desc + '<br>'; else desc='&nbsp;';
  
  document.getElementById('fri_nick').innerHTML='<b style="font-size: 120%; color: #000;">'+nick+'</b> <sup style="color: #C00;">' + f_info + '</sup>';
  document.getElementById('fri_desc').innerHTML=desc;
  if(login!='') document.getElementById('fri_login').innerHTML='<br>Last login: <b style="color: #36A;">' + login + '</b>';
  
  if(ldays<4) document.getElementById('thFriendInfo').style.backgroundColor='#FFE'; else document.getElementById('thFriendInfo').style.backgroundColor='#F9F9F9';
  
  fr_desc = desc;
  
  document.getElementById('thFriendInfo').style.display="block";
  
  me.title='';
  window.onscroll=updatePosFriend;
}
function updatePosFriend() {
  var ev=arguments[0]?arguments[0]:event;
  var cur=getPosition(ev);
  var x=cur.x;
  var y=cur.y
  if(x>500) diffX=-300; else diffX=-10;
  if(fr_desc=='&nbsp;') diffY =- 85; else diffY =- (72+24*Math.ceil(fr_desc.length/85));
  document.getElementById('thFriendInfo').style.top  = y-2+diffY+ "px";
  document.getElementById('thFriendInfo').style.left = x-2+diffX+ "px";
}

function updatePosHug() {
  var ev=arguments[0]?arguments[0]:event;
  var cur=getPosition(ev);
  var x=cur.x;
  var y=cur.y
  
  if(x<250) {
    diffX=-15;
    
    if(hug_text_length>100) {
      if(x>100) diffX=-70;
      if(x>150) diffX=-120;
      if(x>200) diffX=-150;
    }
  }
  else if(x<450) {
    if(hug_text_length<50) diffX=-100;
    else if(hug_text_length<100) diffX=-120;
    else if(hug_text_length<150) diffX=-150;
    else if(hug_text_length<200) diffX=-200;
    else diffX=-230;
  }
  else if(x<650) {
    if(hug_text_length<50) diffX=-100;
    else if(hug_text_length<100) diffX=-150;
    else if(hug_text_length<150) diffX=-220;
    else if(hug_text_length<200) diffX=-300;
    else diffX=-450;
  }
  else {
    if(hug_text_length<50) diffX=-100;
    else if(hug_text_length<100) diffX=-200;
    else if(hug_text_length<150) diffX=-350;
    else if(hug_text_length<200) diffX=-450;
    else diffX=-670;
  }
  
  diffY=-95;
  document.getElementById('thHugTip').style.top  = y-2+diffY+ "px";
  document.getElementById('thHugTip').style.left = x-2+diffX+ "px";
}
function hugTipHide() {
  document.getElementById('thHugTip').style.display="none";
}
function hugTip(text,hugtextlength,me) {
  theObj=me;
  theObj.onmousemove=updatePosHug;
  
  hug_text_length = hugtextlength;
  
  var tdisp = '<table cellpadding"0" cellspacing="0" border="0"><tr><td valign="top"><img src="' + theObj.src + '" style="width:50px;height:50px;" border="0"></td><td width="8">&nbsp;</td><td valign="top">' + text + '</td></tr></table>';
  
  document.getElementById('thHugTip').innerHTML=tdisp;
  document.getElementById('thHugTip').style.display="block";
  me.title='';
  window.onscroll=updatePosHug;
}



var qatips=true;
function hintqa() {
  if(document.getElementById('ask')!=null) {
    if(document.getElementById('ask').value!='') {qatips=false; return;}
    document.getElementById('ask').value=' questions / comments / testimonials';
  }
}