minChatHeight  = 100;
minRightWidth  = 100;
maxRightWidth  = 400;

maxChatHistory = 10;

id=0;

var chatList = new Array();
var chatListCRC = 0;

var reqLoad = new Subsys_JsHttpRequest_Js();

var SelColor = null;
currentUser  = null;

tLoad =null;
tGarbage = null;

refresh = 0;
autohide = 0;

var lastPrivate = 0;
privat = false;
firstLoad=true;

var call_popup_loaded = 0;

function ChatUser(_id, _name, _state, _color, _moder) {

	this.id 	= _id;
	this.name 	= _name;
	this.state	= _state;
	this.color	= _color;
	this.moder	= _moder;

	this.setColor = function(_c) {
		this.color = _c;
	}

	this.setStatus = function(_m) {
		this.moder = _m;
	}

	this.setState = function(_s) {
		this.state = _s;
	}

}

function renderChatList(viewer) {
	var buffer = '';
	if(chatList != null) {
        for(var i=0;i<chatList.length;i++) {
			var moder = '';

			if(chatList[i].moder==1){
				moder = '&nbsp;*';
			} 
			if(chatList[i].moder==2){			
				moder = '&nbsp;#';
			}

            buffer += '<p>'+(chatList[i].state==4?userStatus:'')+'&nbsp;'
			if(viewer){
				buffer += "<span style='color:"+chatList[i].color+"'>"+chatList[i].name+'</span>'+moder;
			} else {
				buffer += "<a style='color: "+chatList[i].color+"' href='javascript:putUser("+chatList[i].id+")'>"
						  +chatList[i].name+'</a>'+moder;
			}
			buffer +='</p>';
        }
	}
	document.getElementById('userlist').innerHTML=buffer;
}

function doSend(prv) {
	privat = prv;

	var messEl = document.getElementById('mess');
    var mess = '' + trim(messEl.value);
	var rcpt = 0;
	var nick_in_mess = false;

	if(prv) {
	// load previous private if it was
		rcpt = lastPrivate;

		// parse message and search ID by nick
		for(var j=0;j<chatList.length;j++){
			if(mess.indexOf(chatList[j].name+':')==0){
				rcpt = chatList[j].id;
				nick_in_mess = true;
				break;
			}
		}
	    
		// search nick by ID and add insert nick into message
		if(rcpt != 0) {
			lastPrivate = rcpt;
			if(!nick_in_mess) {
				for(var j=0;j<chatList.length;j++){
					if(chatList[j].id == rcpt){
						mess = chatList[j].name+': '+mess;
						break;
					}
				}
			}
		}

	} else {
		lastPrivate = 0;		
	}

	if(rcpt==0 && prv) {
		alert(errorNick);
		messEl.focus();
		return;
	}
		
	if(trim(mess)=='') return;
	messEl.value = '';
    var req = new Subsys_JsHttpRequest_Js();
    
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
			doLoad(false);
        }
    }
    req.caching = false;
    req.open('POST', 'modules/combochat/send.php', true);

	c = htmlToInt(Color[SelColor]);
	if(prv){
	    req.send({ mess: mess, c: c, p: 1 });
	} else {
    	req.send({ mess: mess, c: c });
	}
}

function doLoad(viewer) {
    reqLoad.onreadystatechange = function() {
        if (reqLoad.readyState == 4) {
            if (reqLoad.responseJS && reqLoad.responseJS.length>0) {
				var buffer = '';
				var chat_place = document.getElementById('leftbar');

                for(var i=0;i<reqLoad.responseJS.length;i++) {
					var color = intToHtml((reqLoad.responseJS[i].c||''));

					if(reqLoad.responseJS[i].s == null) {	    
						var prv = (reqLoad.responseJS[i].p||'');
//						curColor[(reqLoad.responseJS[i].n||'')]=color;
						var member = '';
						if(viewer){
							member = (reqLoad.responseJS[i].n||'')+' >';
						} else {
							member = "<a href='javascript:putUserName("+'"'+(reqLoad.responseJS[i].n||'')+'"'+
									")' style='color:"+color+";'>"+
										(reqLoad.responseJS[i].n||'')+"</a> >";
						}
                        var message = (prv==1?'<b>':'')+(reqLoad.responseJS[i].t||'')+'&nbsp;';
						if(!viewer){
	    
							message	+= (prv==1?privateStatus+'</b>&nbsp;':'')
						}
						var mess = (reqLoad.responseJS[i].m||'');
	    
						var call_to_chat = false;
	    
						if (mess.lastIndexOf("~C"+currentUser+" ")>=0) {
							call_to_chat = true;
							if(!firstLoad){
								callCombochat();
								mess = " <h1>"+mess.replace(/~C[^\-.*]* /g,currentUser+", Зайди в чат!</h1>")
//	//							mess = " <h1>"+currentUser+", Зайди в чат!</h1>";
							} else {
								mess = '';
							}
						}
//	//					mess = mess.replace(/~C[^\-.*]* /g,"")
        
						var j = mess.indexOf(currentUser+':');
						if(j!=-1){
							var b = mess.substr(0,j);
							b += '<b style="color: red">'+mess.substr(j,currentUser.length)+'</b>';
							b += mess.substr(j+currentUser.length);
							mess = b;
						}
	    
						message		+=			'<span style="color: '
												+color+';">'
												+member+'&nbsp;'
												+mess+'</span>';
						if(call_to_chat){
							message = '<span style="color: '
												+color+';">'
												+mess+'</span>';;
						}
                        buffer += '<p>'+message+'</p>';
                        id=(reqLoad.responseJS[i].id||'')

					} else if((reqLoad.responseJS[i].s||'')==2) {
		
						chatList = new Array();
						chatListCRC = (reqLoad.responseJS[i].c||'');

					} else if((reqLoad.responseJS[i].s||'')==1) {
						var u = null;
						// read data from request
						var uid = (reqLoad.responseJS[i].id||'');
						var act = (reqLoad.responseJS[i].a||'');
						var color = intToHtml((reqLoad.responseJS[i].c||''));
						var moder = (reqLoad.responseJS[i].m||'');
						var name = (reqLoad.responseJS[i].n||'');

						// search user with given id in list
						for(var j=0;j<chatList.length;j++){
							if(chatList[j].id == uid ){
								//found and update user's data
								u = chatList[j];
								u.setState(act);
								u.setColor(color);
								u.setStatus(moder);
								break;
							}
						}
						// if user was kicked than refresh chat page 
						if(act==2){
	                        document.location.replace(forumURL+'?autocom=chatcombo');
						} else {
							// if user with given id not found then create it
							if(u == null){
								u = new ChatUser( uid, name, act, color, moder);
								chatList.push(u);
							}
						}
					}
                }

				// refresh chat users list
				renderChatList(viewer);

				var scrollarea = chat_place.scrollHeight - chat_place.offsetHeight;
				var scroll = true;
				if(scrollarea > 0 && (scrollarea - chat_place.scrollTop) > 5) scroll = false;
					
                chat_place.innerHTML += buffer;
				scrollarea = chat_place.scrollHeight - chat_place.offsetHeight;
				if(scroll){
					chat_place.scrollTop=chat_place.scrollHeight - chat_place.offsetHeight;
				}
				firstLoad = false;

				if((chat_place.children.length - maxChatHistory) > (maxChatHistory/2)){
					clearChatHistory(maxChatHistory);
				}

			}
        }
    }

    reqLoad.abort();

    reqLoad.caching = false;
    reqLoad.open('POST', 'modules/combochat/load.php', true);
	if(viewer){
    	reqLoad.send({ id: id, u: chatListCRC, v: 1 });
	} else {
	    reqLoad.send({ id: id, u: chatListCRC });
	}
/*
    setTimeout(function() {
      reqLoad.abort();
    }, refresh*1000/2); 
*/

}



function doLayout() {

	var corr = correction;                  
	var splitter = document.getElementById("splitter");
	var leftbar = document.getElementById("leftbar");
	var content = document.getElementById("content");
	var bcontent = document.getElementById("bodycontent");

	var docWidth = window.innerWidth;
	var docHeight = window.innerHeight;

	if(!docHeight){
		// if IE
		docHeight = document.documentElement.clientHeight;
		docWidth = document.documentElement.clientWidth;
		corr = correction-5;
	}

	var calculatedHeight = docHeight - corr;
	if(calculatedHeight < minChatHeight) calculatedHeight = minChatHeight;

	bcontent.style.height = calculatedHeight + "px";
	leftbar.style.height = calculatedHeight + "px";
	content.style.height = calculatedHeight + "px";
	splitter.style.height = calculatedHeight + "px";

	horResize(leftbar,content,splitter);	
}

function horResize(left,right,sizer){
	var w = right.parentNode.offsetWidth - right.offsetWidth - sizer.offsetWidth ;
	left.style.width = w+ "px";
	sizer.style.left = w -2 + "px";
	right.style.left = sizer.offsetLeft + sizer.offsetWidth  + "px";
}

function putUser(uid) {
	var u = null;
	for(var j=0;j<chatList.length;j++){
		if(chatList[j].id == uid ){
			u = chatList[j];
			break;
		}
	}
	if(u != null){
		document.forms[1].mess.value+= u.name+": "
		with (document.forms[1]) if (mess.focus) mess.focus()
	}
}

function putUserName(uname) {
	if(uname != null && uname != ''){
		document.forms[1].mess.value+= uname+": "
		with (document.forms[1]) if (mess.focus) mess.focus()
	}
}

function doLogout() {
	document.location.replace(forumURL);	
}

function ColorChanged(ColorIdx)
{
	if(ColorIdx == SelColor)
		return;

	if (document.all)
	{
		obj1 = window.document.all["C"+SelColor];
		obj2 = window.document.all["C"+ColorIdx];
	}
	else if (document.images)
	{
		obj1 = window.document.images["C"+SelColor];
		obj2 = window.document.images["C"+ColorIdx];
	}
	else return;

	if (SelColor != null)
		obj1.src = imgColor1.src;

	SelColor = ColorIdx;
	obj2.src = imgColor2.src;

	try	{
		my_setcookie( 'ipb-combochat-color' , SelColor , 1 );
	}
		catch(e) {
	}

};

function SetColor()
{
	var newcolor  = my_getcookie( 'ipb-combochat-color' );
	if(newcolor==null) newcolor=0;
	ColorChanged(newcolor);
};

function htmlToInt(html) {
	x='0123456789ABCDEF';
	html = html.toUpperCase();
	red = 16*x.indexOf(html.charAt(1))+x.indexOf(html.charAt(2));
	green = 16*x.indexOf(html.charAt(3))+x.indexOf(html.charAt(4));
	blue = 16*x.indexOf(html.charAt(5))+x.indexOf(html.charAt(6));
	return (red << 16) | (green << 8) | blue;
};

function intToHtml(rgb) {
	return rgbToHtml( ((rgb >> 16) & 0xff), ((rgb >> 8) & 0xff ), (rgb & 0xff) );
};

function rgbToHtml(red,green,blue) {
	x='0123456789ABCDEF';
	return "#" + x.charAt(red >> 4)+x.charAt(red & 15) + x.charAt(green >> 4)+x.charAt(green & 15) + x.charAt(blue >> 4) + x.charAt(blue & 15);
};


function timerStart(refresh,viewer)
{

	if (tLoad==null) tLoad = setInterval('doLoad('+viewer+');',refresh*1000)
	if (tGarbage==null && is_ie) tGarbage = setInterval('CollectGarbage()',refresh*1000*10)
}

function timerStop()
{
	if (tLoad!=null) {clearInterval(tLoad); tLoad = null;}
	if (tGarbage!=null) {clearInterval(tGarbage); tGarbage = null;}
}

function doOnKeyDown(e) {
	var event = null;
	if(e) {
		event = e;
	} else {
		event = window.event;
	}
	if (event.keyCode==13) {

		if(privat){	
		   onClickPrivate();
		} else {		
		   onClickSend();
		}
		event.preventDefault ?
        event.preventDefault() :
        event.returnValue = false;
	}
}

function debug(text) {
	var d = document.getElementById('debug');
	d.innerHTML += text+'</br>';
}

function associateEventWithObject(_obj, _method, _param) {
	return function(e)
	{
		return _obj[_method](new MouseEvent(e), this, _param);
	};
}

function isClass(_elem, _className) {
	return _elem && _elem.className &&
		new RegExp('\\b'+_className+'\\b').test(_elem.className);
}

function addClass(_elem, _className) {
	modifyClass(_elem, _className, function(_elem, _className)
		{
			if (_elem.className && !/^\s*$/.test(_elem.className))
			// element className field is set to non-empty string,
			// so we're going to add one to class to element
			{
				if (!isClass(_elem, _className))
					_elem.className=_elem.className+" "+_className;
			}
			else
				_elem.className=_className;
		}
	);
}

function delClass(_node, _className) {
	if (_node && (_node.className!=undefined))
	{
		_node.className=_node.className.replace(" "+_className, "");
		_node.className=_node.className.replace(_className, "");
	}
}

function modifyClass(_elem, _className, _func) {
	if (_elem.length)
		for (var i=0; i<_elem.length; i++)
			_func(_elem[i], _className);
	else
		_func(_elem, _className);
}

function trim(x) {
  x=x.replace(/^\s*(.*)/, "$1");
  x=x.replace(/(.*?)\s*$/, "$1");
  return x;
}

function clickSend() {
	delClass(prvb,'select-button');
	addClass(sndb,'select-button');
	privat = false;
	onClickSend();
	var m = document.getElementById('mess');
	m.focus();
}

function clickPrivate() {
	delClass(sndb,'select-button');
	addClass(prvb,'select-button');
	privat = true;
	onClickPrivate();
	var m = document.getElementById('mess');
	m.focus();
}

function callCombochat() {

	var cbc_call = getFlashMovieObject('cbc_call');

	try {
		cbc_call.StopPlay();
		cbc_call.Rewind();  
		cbc_call.Play();    
	} catch(e) {}

}

function pageLoad() {
}

function call_hide()
{
	document.getElementById('get-call-popup').style.display='none';
	call_popup_loaded = 0;
}

function call_popup()
{
	call_main     = document.getElementById( 'get-call-popup' );	
	call_drag 	   = document.getElementById( 'call-drag' );

  	call_main.style.position = 'absolute';
	call_main.style.display  = 'block';
	call_main.style.zIndex   = 99;


	if ( ! call_popup_loaded )
	{
		//----------------------------------
		// Figure width and height
		//----------------------------------
		
		var my_width  = 0;
		var my_height = 0;
		
		if ( typeof( window.innerWidth ) == 'number' )
		{
			//----------------------------------
			// Non IE
			//----------------------------------
		  
			my_width  = window.innerWidth;
			my_height = window.innerHeight;
		}
		else if ( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
		{
			//----------------------------------
			// IE 6+
			//----------------------------------
			
			my_width  = document.documentElement.clientWidth;
			my_height = document.documentElement.clientHeight;
		}
		else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) )
		{
			//----------------------------------
			// Old IE
			//----------------------------------
			
			my_width  = document.body.clientWidth;
			my_height = document.body.clientHeight;
		}
		
		//----------------------------------
		// Get div height && width
		//----------------------------------
		
		var divheight = parseInt( call_main.style.height );
		var divwidth  = parseInt( call_main.style.width );

		divheight = divheight ? divheight : 400;
		divwidth  = divwidth  ? divwidth  : 800;
		
		//----------------------------------
		// Got it stored in a cookie?
		//----------------------------------
		
		var divxy = my_getcookie( 'ipb-combochat-call' );
		var co_ords;
		
		if ( divxy && divxy != null )
		{
			co_ords = divxy.split( ',' );
		
			//----------------------------------
			// Got co-ords?
			//----------------------------------
			
			if ( co_ords.length )
			{
				var final_width  = co_ords[0];
				var final_height = co_ords[1];
				
				if ( co_ords[0] > my_width )
				{
					//----------------------------------
					// Keep it on screen
					//----------------------------------
					
					final_width = my_width - divwidth;
				}
				
				if ( co_ords[1] > my_height )
				{
					//----------------------------------
					// Keep it on screen
					//----------------------------------
					
					final_height = my_height - divheight;
				}
				
				call_main.style.left = final_width  + 'px';
				call_main.style.top  = final_height + 'px';
			}
		}
		else
		{
			//----------------------------------
			// Reposition DIV roughly centered
			//----------------------------------

			call_main.style.left = my_width  / 2  - (divwidth / 2)  + 'px';
			call_main.style.top  = my_height / 2 - (divheight / 2 ) + 'px';
		}
		
		Drag.cookiename = 'ipb-combochat-call';
		Drag.init( call_drag, call_main );

		if (document.forms[0])
			document.forms[0].elements[0].focus();

		
		call_popup_loaded = 1;
		}
}

function getFlashMovieObject(movieName)
{
  if (window.document[movieName]) 
  {
      return window.document[movieName];
  }
  if (navigator.appName.indexOf("Microsoft Internet")==-1)
  {
    if (document.embeds && document.embeds[movieName])
      return document.embeds[movieName]; 
  }
  else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
  {
    return document.getElementById(movieName);
  }
}

function run_call() {
	call_hide();
	var mess = document.getElementById('mess');
	mess.value = '#call '+UNhtmlspecialchars(document.getElementById('entered_name').value);
	doSend(false);
	return false;
}

function UNhtmlspecialchars(text)
{
		text = text.replace( /\&amp;/i , "&" );
		text = text.replace( /\&lt;/i  , "<" );
		text = text.replace( /\&gt;/i  , ">" );
		text = text.replace( /\&quot;/i, '"' );
		text = text.replace( /\&#39;/i, "'" );
		
		return text;
}

function clearChatHistory(number) {
	var chat = document.getElementById('leftbar');
	while(chat.children.length > number) {
		chat.removeChild(chat.firstChild);
	}
}
