var color = new Array("7777bb","7777ff","00bbff","00bbbb","00bb77","00bb00","007700","007777","0077bb",
			"0077ff","0000ff","0000bb","7700bb","7700ff","bb00ff","bb00bb","ff00bb","ff0000",
			"bb0000","770000","777700","bb7700","ff7700","ff7777","ff77bb","ff77ff","bb77ff",
			"bb77bb","bb7777","777777");
timerId = null;
mid = 0;
chatstr="";
onlinestr="";
midstr="";
doact = "";
i=0;
zix=100;
lastscroll=0;
ready=1;
var timing = 3;
var rollstep = 1;
var currentroll=0;
indication = 1;

    function SaveMessage(a,t,i,j) {
        JsHttpRequest.query('/back_chat.php',
     {
                'act': a,
                'mtext': t,
                'mid': i,
		'param4' : j
            },
            function(result, errors) {
//                document.getElementById("debug"+n).innerHTML = errors; 
		if (result["mid"] != "") {midstr = result["mid"];}
		chatstr = result["chat"];
		onlinestr = result["online"];  
		doact = result["doact"]; 
		pnick = result["nick"];
		document.getElementById("indic").style.backgroundPosition = "0% 100%";
		if (indication) {document.getElementById("sayfield").style.background = "#ffffff";}
		ready=1; 
//alert(pnick);
		
		if (result["nick"] != null && result["nick"] != ""){document.getElementById("nick").innerHTML = result['nick']}
		if (result["hello"] != null && result["hello"] != ""){document.getElementById("hello").value = result['hello']}
		if (result["goodbye"] != null && result["goodbye"] != ""){document.getElementById("goodbye").value = result['goodbye']}
		if (result["chatcolor"] != null && result["chatcolor"] != ""){chatcolor=result["chatcolor"]; document.getElementById(chatcolor).style.background = "#dddddd"; document.getElementById("chatcolor").value= chatcolor;	}
		
                if (doact == "exitchat"){ doact=""; parent.window.close();
		}

                if (doact == "refresh"){
                  mid = midstr;
                              document.getElementById("chat_text_in").innerHTML = document.getElementById("chat_text_in").innerHTML+chatstr;
                              document.getElementById("online").innerHTML = onlinestr;
                }
              	if (chatstr){	

			hchat = document.getElementById("chat_text").style.height;
			hchat = hchat.substr(0,hchat.length-2);
			hroll = document.getElementById("chat_text_in").scrollHeight - hchat;
// alert("i="+document.getElementById("chat_text").scrollTop+" j="+document.getElementById("chat_text_in").scrollHeight+" curr="+currentroll+" /"+hchat);
			if (hchat <= document.getElementById("chat_text_in").scrollHeight){
			RollDown(document.getElementById("chat_text"),document.getElementById("chat_text").scrollTop,hroll);
			}
//			RollDown(document.getElementById("chat_text_in"),document.getElementById("chat_text_in").scrollTop,lastscroll+500);
			//document.getElementById("chat_text_in").scrollTop=500000;
//			lastscroll = document.getElementById("chat_text_in").scrollTop;

                }
                if (doact == "init"){

                  mid = midstr; doact="refresh";
                              document.getElementById("chat_text_in").innerHTML = chatstr;
                              document.getElementById("online").innerHTML = onlinestr;
                }
                if (doact == "say" || doact=="saveuserchange" || doact=="delmessage" || doact=="initdone"){
			if (doact=="initdone" && pnick){document.getElementById("usri").innerHTML = pnick;}
			doact="refresh";
                }
                if (doact == ""){clearTimeout(timerId); if (chatstr){alert (chatstr);}
                }
                if (doact == "initadm"){doact="";
                }
                          },
            true  // do not disable caching
        );

  return;    
    }

    function SendMessage(m,n){
      SaveMessage("say",m,"",n);
	if (document.getElementById('whom').value != ""){
			document.getElementById("privsayfield").value = "";
			document.getElementById("privsay").style.display = "none";
			document.getElementById("sayfield").disabled = 0;
			document.getElementById("saysubmit").disabled = 0;
	};
      document.getElementById("sayfield").value = "";
      document.getElementById("sayfield").focus();
      return false;
    }

    function InitChat(){
// передаем пользователя, получаем Online, Chat
      if (ready) {document.getElementById("indic").style.backgroundPosition = "0% 0%"; 
		if (indication) {document.getElementById("sayfield").style.background = "#ffeeee"; }
		ready=0; SaveMessage(doact,"",mid);
		}
      timerId = setTimeout(function(){InitChat()},5000);
    }
  
  function SetWindowsSize(){
    wwidth = document.body.clientWidth;
    wheight = document.body.clientHeight;
    document.getElementById("chat_text").style.height = document.body.clientHeight - document.getElementById("links").style.height - document.getElementById("say").style.height-150;
    document.getElementById("online_all").style.height = document.body.clientHeight - document.getElementById("links").style.height - document.getElementById("say").style.height-150;
    document.getElementById("online").style.height = document.body.clientHeight - document.getElementById("links").style.height - document.getElementById("say").style.height-190;
//  document.getElementById("chat_text_in").style.width = document.body.clientwidth - document.getElementById("online").style.width - 270;
    currentroll= document.getElementById("chat_text").scrollTop;

  }

  function Init1(){
	document.getElementById("sayfield").focus();
	for (i=0; i<color.length; i++){
		document.getElementById('colors').innerHTML += "<span id=\""+color[i]+"\" class=\"chatcolor\" onMouseover=\"ColorIn(this)\" onMouseout=\"ColorIn(this)\" onClick=\"ColorCh(this)\">.:Текст:.</span>";
		document.getElementById(color[i]).style.color ="#"+color[i];
		if (Math.round((i+1)/6) == ((i+1)/6)){document.getElementById('colors').innerHTML += "<br>"}
	}

  }

  function SetInitOne(doit,n,current){
//	alert (n);
	if (doit == "reset") {SaveMessage("initone","reset", n);}
	if (doit == "block") {if (confirm('Блокируем пользователя '+n+'?')){SaveMessage("initone","block", n);}}
	current.style.background = "#ffbbbb";
  }

  function ShowChangeData(n){
	if (n == "1"){
		SaveMessage("saveuserchange",
				document.getElementById("hello").value,
				document.getElementById("goodbye").value,
				document.getElementById("chatcolor").value
				);
	}
	if ( document.getElementById("tools").style.display != "block"){
		document.getElementById("tools").style.zIndex = zix; zix++;
		document.getElementById("tools").style.display = "block";
		document.getElementById("sayfield").disabled = 1;
		document.getElementById("saysubmit").disabled = 1;
	}
	else{
		document.getElementById("tools").style.display = "none";
		if (document.getElementById("privsay").style.display != "block"){
			document.getElementById("sayfield").disabled = 0;
			document.getElementById("saysubmit").disabled = 0;
		}
		if (n != 1){
			ColorCh(document.getElementById(chatcolor));
		}
	}
	return false;
  }

	function ColorIn (n){
		if (n.style.border == "2px solid currentColor" || n.style.border == "2px solid"){
			n.style.border="0px solid"; n.style.margin = "2";	
		}
		else{
			n.style.border="2px solid"; n.style.margin = "0";	
		}
	}
	function ColorCh (n){
		var MyArray;
		i=0;
		while (color[i]){
			document.getElementById(color[i]).style.background ="none";
			i++;
		}

		if (n.style.color.length > 7){
			document.getElementById("chatcolor").value = getHexRGBColor(n.style.color);
		}
		else{
			document.getElementById("chatcolor").value = n.style.color.substring(1);
		}
	 	n.style.background="#dddddd";	
	}

	function sir(n){
	  document.getElementById("sayfield").value = n.innerHTML + ", " + document.getElementById("sayfield").value;
	  document.getElementById("sayfield").focus();
	}

	function ShowPrivateField(n){
	if ( document.getElementById("privsay").style.display != "block"){
		document.getElementById("privsay").style.zIndex = zix; zix++;
		document.getElementById("privsay").style.display = "block";
		document.getElementById("privnick").innerHTML = pnick;
		document.getElementById("recipient").innerHTML = n;
		document.getElementById("whom").value = n;
		document.getElementById("sayfield").disabled = 1;
		document.getElementById("saysubmit").disabled = 1;
		document.getElementById("privsayfield").focus();
	}
	else{
		document.getElementById("privsay").style.display = "none";
		if (document.getElementById("tools").style.display != "block"){
			document.getElementById("sayfield").disabled = 0;
			document.getElementById("saysubmit").disabled = 0;
		}
		document.getElementById("sayfield").focus();
	}
	return false;

	}


document.onmousemove = moveTip;

	function moveTip(e) {
	  choosechatStyle = document.getElementById("usri").style;
	  w = 250; // Ширина слоя
	  // Для браузера IE
	  if (document.all) { 
	    x = event.x + document.body.scrollLeft; 
	    y = event.y + document.body.scrollTop; 
	  // Для остальных браузеров
	  } else { 
	    x = e.pageX; // Координата X курсора
	    y = e.pageY; // Координата Y курсора
	  }
	  // Показывать слой справа от курсора 
	  if ((x + w + 10) < document.body.clientWidth) { 
	    choosechatStyle.left = x + 20 + 'px';
	  // Показывать слой слева от курсора
	  } else { 
	    choosechatStyle.left = x - w + 'px';
	  }
	  // Положение от верхнего края окна браузера
	  choosechatStyle.top = y + 10 + 'px';
	}
	function toolTip(msg) {
	  choosechatStyle = document.getElementById("usri").style;
	  if (msg == "usri") {
	    document.getElementById("usri").innerHTML = "<img src='/images/loader.gif' width='11' height='11'>";
	    choosechatStyle.display = "block"; // Показываем слой
	  } 
	  else if (msg && msg != "ursi") {
	    // Выводим текст подсказки
	    document.getElementById("usri").innerHTML = msg;
	    choosechatStyle.display = "block"; // Показываем слой
	  } 
 	  else { 
	    choosechatStyle.display = "none"; // Прячем слой
	  } 
	}


//	RollDown(object,source sense, target sense);
	function RollDown(n,i,j){
		if (i < j && document.getElementById("chat_text").scrollTop >= (currentroll-40)){
		     i = i+rollstep;
		 	if (i>j){i=j}
		     n.scrollTop = i; currentroll = i;
		     setTimeout(function(){RollDown(n,i,j)},timing);
		}
		else{}
	}

	function ChangeIndication(){
		if (!indication){
			document.getElementById("sayfield").style.background = "#ffffff";
			document.getElementById("indicator_button").innerHTML = "Выключить индикацию в строке";
			indication = 1;
		}
		else{
			document.getElementById("sayfield").style.background = "#ffffff";
			document.getElementById("indicator_button").innerHTML = "Включить индикацию в строке";
			indication = 0;
		}


//	alert(document.getElementById("indicator_button").value);

	}

	function getHexRGBColor(color)
	{
	  color = color.replace(/\s/g,"");
	  var aRGB = color.match(/^rgb\((\d{1,3}[%]?),(\d{1,3}[%]?),(\d{1,3}[%]?)\)$/i);
	
	  if(aRGB)
	  {
	    color = '';
	    for (var i=1;  i<=3; i++) color += Math.round((aRGB[i][aRGB[i].length-1]=="%"?2.55:1)*parseInt(aRGB[i])).toString(16).replace(/^(.)$/,'0$1');
	  }
	  else color = color.replace(/^#?([\da-f])([\da-f])([\da-f])$/i, '$1$1$2$2$3$3');
	  
	  return color;
	}
