/*
Klat.com Chat Application Copyright 2008 NeonGecko.com Inc.
All Rights Reserved.
*/




function klatchat(p_divname,p_channel,p_sid){
   var mychat=this; //required for closures;
   this._hostname='chat.klat.com';
   this._port=8080;
   this._channel=p_channel;
   this._sid=p_sid;
   this._cookie=this.cookie("KUID");
   this._divname=p_divname;
   var div=document.getElementById(this._divname);
   if (!div){
      alert("div not found");
      return(false);
   }
   this.div=div;
   this._sock=new socket('http://chat.klat.com/chat/sock.swf');
   this._userlist=new Object;
   this._userlista=new Array;
   this._grouplist=new Object;
   this._settings=new Object;
   this.connect=function(){
      this._sock.connect(this._hostname,this._port); 
   }
   this.doCommand=function(cmd){
      var c=cmd.shift();
      if (c == 'M'){
         var dest=cmd.shift();
         var from=cmd.shift();
         var msg=cmd.shift();
         this.message(dest,from,msg);
      }else if (c == 'S'){
         this._settings=eval(cmd.shift());
      }else if (c == 'U'){
         for (var i=0; i < cmd.length; i++){
            eval("var user="+cmd[i]);
            this.updateUser(user);
         }
      }else if (c == 'G'){
         for (var i=0; i < cmd.length; i++){
            var group=eval(cmd[i]);
            if (group.status == 0){
               delete this._grouplist[group.id];
            }else{
               this._grouplist[group.id]=group;
            } 
         } 
         this.refreshGroupList();
      }else if (c == 'C'){
         eval(cmd.shift());
      }
   }
   this._sock.ondata=function(data){
      var list=data.split("\n");
      var cmd=new Array();
      while (list.length>0){
         cmd.push(unescape(list.shift()));
      }
      mychat.doCommand(cmd);
   }
   this.send=function(data){
      this._sock.send(data);
   }
   this.message=function(dest,from,msg){
      var max=200;
      var d;
      var sh1=roomdiv.scrollHeight;
      var st1=roomdiv.scrollTop;
      if (roomdiv._cntChildren > max){
         d=roomdiv.removeChild(roomdiv.firstChild);
         var sh2=roomdiv.scrollHeight;
      }else{
         d=socket.ce("div");
         roomdiv._cntChildren++;
      }
      if (from == 'SYS'){
         d.innerHTML=msg;
         d.className="klatchat_sysmsg";
      }else if (from == 'Q'){
         d.innerHTML=msg;
         d.className="klatchat_msg";
      }else if (from == 'TSR'){
         d.innerHTML=msg;
         d.className="klatchat_teaser";
      }else if (from == this._hash){
         d.innerHTML=this._userlist[from].name + ": " +msg;
         d.className="klatchat_mymsg";
         st1=sh1-roomdiv.clientHeight;
      }else{
         d.innerHTML=this._userlist[from].name + ": " +msg;
         d.className="klatchat_msg";
      }
      roomdiv.appendChild(d);
      sh3=roomdiv.scrollHeight;
      if (st1 > sh1-roomdiv.clientHeight-15){
         roomdiv.scrollTop=roomdiv.scrollHeight;
      }else{
         if(sh2){
            var st2=st1-(sh1-sh2);
            roomdiv.scrollTop=st2<0 ? 0 : st2;
         }
      }
   }
   this.sortByName=function(a,b){
      if (mychat._userlist[a] && mychat._userlist[b]){
         var aname=mychat._userlist[a].name.toUpperCase();
         var bname=mychat._userlist[b].name.toUpperCase();
         if (aname == bname){
            return 0;
         }else if (aname > bname){
            return 1;
         }else{
            return -1;
         }
      }else{
         return true;
      }
   }
   this.refreshUserName=function(){
      usernameinput.value=this._username;
   }
   this.refreshGroupList=function(){
   }
   this.fixCss("klatroom");
   var divWidth=div.clientWidth;
   var divHeight=div.clientHeight;
   if(!divWidth) divWidth=div.style.pixelWidth;
   if(!divHeight) divHeight=div.style.pixelHeight;
   if(!divWidth) divWidth=parseInt(div.style.width);
   if(!divHeight) divHeight=parseInt(div.style.height);
   div.className="klatmain";
   this.mkCorners(div,true);
   var listdivo=socket.ce("div");
   var listdiv=socket.ce("div");
   var grip=socket.ce("div");
   var roomdivo=socket.ce("div");
   var roomdiv=socket.ce("div");
   roomdiv._cntChildren=0;
   var senddiv=socket.ce("div");
   listdivo.className="klatlisto";
   roomdivo.className="klatroomo";
   listdiv.className="klatlist";
   roomdiv.className="klatroom";
   senddiv.className="klatsend";
   grip.className="klatgrip";
   var gimg=socket.ce("img");
   gimg.className="klatgimg";
   gimg.src="http://chat.klat.com/chat/corners/grip.png";
   grip.appendChild(gimg);
   roomdiv.style.height=(divHeight-44)+"px";
   roomdiv.style.width=(divWidth-22)+"px";
   listdiv.style.height=(divHeight-46)+"px";
   grip.style.height=(divHeight-39)+"px";
   gimg.style.marginTop=Math.round(((divHeight-39)/2)-12)+"px";
   senddiv.style.position="absolute";
   senddiv.style.left="120px";
   senddiv.style.bottom="6px";
   senddiv.style.width=(divWidth - 162) + "px";
   listdivo.appendChild(listdiv);
   div.appendChild(listdivo);
   roomdivo.appendChild(grip);
   roomdivo.appendChild(roomdiv);
   div.appendChild(roomdivo);
   this.mkCorners(roomdivo);
   this.mkCorners(listdivo);
   grip.onmouseover=function(){
      roomdiv.style.width=(divWidth-145)+"px";
      //roomdivo.style.width=(divWidth-145)+"px";
   }
   grip.onclick=function(){
      roomdiv.style.width=(divWidth-22)+"px";
      //roomdivo.style.width=(divWidth-22)+"px";
   }
   var namediv=socket.ce("div");
   namediv.setAttribute("className","klatusername");
   namediv.setAttribute("class","klatusername");

   div.appendChild(namediv);
   div.appendChild(senddiv);
   this.mkCorners(namediv);
   this.mkCorners(senddiv);
   var logo=socket.ce("img");
   logo.src="http://chat.klat.com/chat/corners/klat.gif";
   logo.style.position="absolute";
   logo.style.right="2px";
   logo.style.bottom="2px";
   logo.style.padding="0px";
   logo.style.margin="0px";
   div.appendChild(logo);
 
   var usernameinput=socket.ce("input");
   usernameinput.setAttribute("class","klatusernameinput");
   usernameinput.setAttribute("className","klatusernameinput");
   usernameinput.value="";
   usernameinput.onchange=function(){
      var newname=this.value;
      if(newname.length > 50){
          newname=newname.substring(0,10);
      }
      if(newname != this._username){
         mychat.send("L\n"+this.value);
      }
   }
   usernameinput.onkeypress=function(e){
      if (!e) e=window.event;
      if (e.keyCode ==13){
         //this.onchange();
         roominput.focus();
         return false;
      }
   }
   var form=socket.ce("form");
   form.style.display="inline";
   var roominput=socket.ce("input");
   form.onsubmit=function(){ 
      var msg=this.firstChild.value;
      msg=msg.replace(/^\s+|\s+$/g,"");
      if(msg.length > 0){
         if (msg.length > 255){
            msg=msg.substring(0,255);
         }
         try {
            mychat.send("S\nr\n"+msg);
         } catch(e){ }
      }
      this.firstChild.value="";
      this.firstChild.focus();
      return false;
   }
   logo.onclick=function() { form.onsubmit(); }
   roominput.setAttribute("className","klatsendinput");
   roominput.setAttribute("class","klatsendinput");
   roominput.setAttribute("name","send");
   roominput.style.width=(divWidth-165)+"px";
   form.appendChild(roominput);
   namediv.appendChild(usernameinput);
   senddiv.appendChild(form);
   //roominput.focus();
   this.connect();
   this.send(["C",this._sid,this._cookie,this._channel,location.host].join("\n"))
   var debugdiv=socket.ce("div");
   debugdiv.style.position="absolute";
   debugdiv.style.bottom="0px";
   debugdiv.style.right="0px";
   debugdiv.style.color="white";
   debugdiv.style.backgroundColor="red";
   div.appendChild(debugdiv);
   function debug(a){
      //debugdiv.innerHTML=a;
      mychat.message('r','SYS',a);
   }
   this.updateUser=function(user){
      var ukey=user.hash;
      if (user.me ==1){
         this._username=user.name;
         this._hash=user.hash;
         this.refreshUserName();
      }
      if (user.status == 0){
         for (var i=0 ; i < this._userlista.length ; i++){
            if (this._userlista[i] == user.hash){
               this._userlista.splice(i,1);
            }
         }
         if(this._userlist[user.hash].div){
            try { listdiv.removeChild(this._userlist[user.hash].div);} catch(e) {};
         }
         delete this._userlist[user.hash];
      }else{
         var insertNeed=true;
         var sortNeed=true;
         var udiv=false;
         if(this._userlist[user.hash]){
            insertNeed=false;
            udiv=this._userlist[user.hash].div;
            if (this._userlist[user.hash].name == user.name){
               sortNeed=false;
            }
         }
         var insertPos=-1;
         var deletePos=-1;
         var dupName=false;
         if(sortNeed){
            if (this._userlista.length>0){
               var nameCmp=(user.name ? user.name.toUpperCase() : '');
               for (var i=0 ; i < this._userlista.length ; i++){
                  if(this._userlist[this._userlista[i]].name == user.name){
                     dupName=true;
                  }
                  if (insertPos==-1 && this._userlist[this._userlista[i]].name && this._userlist[this._userlista[i]].name.toUpperCase() >= nameCmp){
                     insertPos=i;
                     //break;   
                  }
                  if (deletePos==-1 && this._userlista[i] == user.hash){
                     deletePos=i;
                  }         
                  if(deletePos !=-1 && insertPos !=-1){
                     break;
                  }
               }
            }
         }
         this._userlist[user.hash]=user;
         var classname = (user.gray && user.gray == 1) ? 'klatgray' : (user.me && user.me == 1) ? 'klatself' : 'klatuser';
         if(user.mute && user.mute ==1) classname='klatmute';
         if(udiv){
            if(sortNeed){
               try{ listdiv.removeChild(udiv);} catch(e) {};
               if (deletePos !=-1){
                  this._userlista.splice(deletePos,1);
                  if (deletePos < insertPos){
                     insertPos--;
                  }
               }
            }
         }else{
            udiv=socket.ce("div");
            udiv.onclick=function(){
               mychat.send("O\nM\n"+ukey);
            }
         }
         udiv.setAttribute("class",classname);
         udiv.setAttribute("className",classname);
         udiv.innerHTML=user.name;
         //udiv.innerHTML=ukey + user.name;
         if(!dupName){
            if(sortNeed){
               if(insertPos==-1 || insertPos >= this._userlista.length){
                  listdiv.appendChild(udiv);
                  this._userlista.push(user.hash);
               }else{
                  listdiv.insertBefore(udiv,this._userlist[this._userlista[insertPos]].div);
                  this._userlista.splice(insertPos,0,user.hash);
               }
            }
            this._userlist[user.hash].div=udiv;
         }
      }
   }
}
klatchat.prototype.mkCorners=function(tdiv,isOuter){
   var dim=isOuter ? 8 : 6;
   var oi=isOuter ? 'o' : 'i';
   var ie6=navigator.userAgent.indexOf("MSIE 6") > 0 ? true : false;
   var i1=socket.ce("img");
   var i2=socket.ce("img");
   var i3=socket.ce("img");
   var i4=socket.ce("img");
   if(isOuter){
      i1.className="klatcornero";
      i2.className="klatcornero";
      i3.className="klatcornero";
      i4.className="klatcornero";
   }else{
      i1.className="klatcorner";
      i2.className="klatcorner";
      i3.className="klatcorner";
      i4.className="klatcorner";
   }
   i1.style.top="0px";
   i1.style.left="0px";
   i2.style.top="0px";
   i2.style.right="0px";
   i3.style.bottom="0px";
   i3.style.left="0px";
   i4.style.bottom="0px";
   i4.style.right="0px";
   i1.src="http://chat.klat.com/chat/corners/"+oi+"ul."+(ie6 ? 'gif' : 'png');
   i2.src="http://chat.klat.com/chat/corners/"+oi+"ur."+(ie6 ? 'gif' : 'png');
   i3.src="http://chat.klat.com/chat/corners/"+oi+"ll."+(ie6 ? 'gif' : 'png');
   i4.src="http://chat.klat.com/chat/corners/"+oi+"lr."+(ie6 ? 'gif' : 'png');
   tdiv.appendChild(i1);
   tdiv.appendChild(i2);
   tdiv.appendChild(i3);
   tdiv.appendChild(i4);
}
klatchat.prototype.mkCorners2=function(tdiv,width,height,isOuter){
   var dim=isOuter ? 8 : 6;
   var oi=isOuter ? 'o' : 'i';
   var ie6=navigator.userAgent.indexOf("MSIE 6") > 0 ? true : false;
   var offsettop=tdiv.offsetTop;
   var offsetleft=tdiv.offsetLeft;
   if (isOuter){
      offsettop=0;
      offsetleft=0;
   }
   var i1=socket.ce("img");
   var i2=socket.ce("img");
   var i3=socket.ce("img");
   var i4=socket.ce("img");
   i1.style.position='absolute';
   i2.style.position='absolute';
   i3.style.position='absolute';
   i4.style.position='absolute';
   i1.style.width=dim+'px';
   i2.style.width=dim+'px';
   i3.style.width=dim+'px';
   i4.style.width=dim+'px';
   i1.style.height=dim+'px';
   i2.style.height=dim+'px';
   i3.style.height=dim+'px';
   i4.style.height=dim+'px';
   i1.style.top=offsettop+'px';
   i2.style.top=offsettop+'px';
   i3.style.top=(offsettop+height-dim)+'px';
   i4.style.top=(offsettop+height-dim)+'px';
   i1.style.left=offsetleft+'px';
   i2.style.left=(offsetleft+width-dim)+'px';
   i3.style.left=(offsetleft+width-dim)+'px';
   i4.style.left=offsetleft+'px';
   i1.src="http://chat.klat.com/chat/corners/"+oi+"ul."+(ie6 ? 'gif' : 'png');
   i2.src="http://chat.klat.com/chat/corners/"+oi+"ur."+(ie6 ? 'gif' : 'png');
   i3.src="http://chat.klat.com/chat/corners/"+oi+"lr."+(ie6 ? 'gif' : 'png');
   i4.src="http://chat.klat.com/chat/corners/"+oi+"ll."+(ie6 ? 'gif' : 'png');
   this.div.appendChild(i1);
   this.div.appendChild(i2);
   this.div.appendChild(i3);
   this.div.appendChild(i4);
}

klatchat.prototype.checkCss=function(searchstring){
   var flavor;
   for (si=0; si < document.styleSheets.length; si++){
      if(!flavor){
         if (document.styleSheets[si].cssRules){
            flavor=1;
         }else if (document.styleSheets[si].rules){
            flavor=2;
         }
      }
      var rules;
      if(flavor==1){
         rules=document.styleSheets[si].cssRules;
      }else if (flavor==2){
         rules=document.styleSheets[si].rules;
      }
      for (ri=0; ri < rules.length; ri++){
         if (rules[ri].selectorText && rules[ri].selectorText.indexOf(searchstring) != -1 ){
            return true;
         }
      }
   }
   return false;
}

klatchat.prototype.fixCss=function(searchstring){
   if(this.checkCss(searchstring)) return false;
   if(document.styleSheets.length == 0){
      var ss=socket.ce('style');   
      ss.setAttribute("type","text/css");
      var head=document.getElementsByTagName("head")[0];
      if (head){
         head.appendChild(ss);
      }else{
         head=document.getElementsByTagName("head").item(0);
         if (head){
            head.appendChild(ss);
         }else{
            return false;
         }
      }
   }
   var sheet=document.styleSheets[0];
   var s={
	"div.klatroomo":"position: absolute; top: 6px; left: 6px; font-size: 12px; font-family: sans-serif; background-color: #777; z-index: 1; margin: 0px;",
	"div.klatroom":"overflow-y: scroll; padding: 3px; line-height: 1em;position: relative; background-color: #fff; margin: 0px;",
	"div.klatmain":"background-color: #777; padding: 0px; position: relative; text-align: left;",
	"div.klatlisto":"font-size: 12px; font-family: sans-serif; width: 120px; background-color: #e7f1f4; position: absolute; top: 6px; right: 6px; z-index: 0",
	"div.klatlist":"position: relative; padding: 4px;  line-height: 1em; overflow-y: scroll; overflow-x: hidden;",
	"div.klatsend":"background-color: #fff; height: 20px; padding-left: 3px; font-size: 10px;",
	"div.klatusername":"background-color: #e7f1f4; height: 20px; padding-left: 3px; position: absolute; left: 6px; bottom: 6px; width: 105px;",
	"input.klatsendinput":"font-size: 15px; border: none; background: none; line-height: 1em;",
	"input.klatusernameinput":"font-size: 12px; font-weight: bold; border: none; background: none; width: 102px; position: relative; margin-top: 1px; color: #970f00;",
	"div.klatchat_sysmsg":"color: #999; font-style: italic;",
	"div.klatchat_mymsg":"margin-left: 2em; text-indent: -2em; color: #970f00;",
	"div.klatchat_msg":"margin-left: 2em; text-indent: -2em;",
	"div.klatchat_teaser":"margin-left: 2em; text-indent: -2em;",
	"div.klatuser":"color: black;",
	"div.klatself":"color: #970f00;",
	"div.klatgray":"color: #888;",
	"div.klatmute":"color: black; text-decoration: line-through;",
	"img.klatcorner":"width: 6px; height: 6px; position: absolute; z-index: 1",
	"img.klatcornero":"width: 8px; height: 8px; position: absolute; z-index: 1",
	"div.klatgrip":"width: 5px; background-color: #777; position: absolute; right: -5px;",
	"div.klatgimg":"position: absolute;"
	};
   if (sheet.insertRule){
      for (var i in s){
         sheet.insertRule(i + " { " + s[i] + " }",0);
      }
   }else if (sheet.addRule){
      for (var i in s){
         sheet.addRule(i,s[i]);
      }
   }
}

klatchat.prototype.cookie=function(cookieName){
   if(!this._cookiecache){
      this._cookiecache=new Object;
      var cookies=document.cookie.split("; ");
      for (var c in cookies){
         var pair=cookies[c].split("=");
         this._cookiecache[pair[0]]=pair[1];
      }
   }
   return this._cookiecache[cookieName];
}
klatchat.prototype.setCookie=function(cookieName,cookieVal){
   document.cookie=cookieName + "=" + cookieVal + "; domain="+window.location.host+"; expires=Mon, 27-Jul-2020 23:59:59 GMT; path=/";
}



function socket(swfUrl) {
   var sId;
   sId='socket' + Math.round(Math.random()*99999999).toString();
   if (!document._socks){
      document._socks = new Object;
   }
   document._socks[sId]=new _socket(sId,swfUrl);
   return document._socks[sId];
}
function socket_callback(sId,func,data) {
   var sock=document._socks[sId];
   if (sock){
      try {eval("sock."+ func + "(data)");} catch(e) { alert(e)};
   }else{
      //alert("callback could not find sID: "+sId);
   }
}

function _socket(sId,swfUrl){
   this._id=sId;
   this._ready=false;
   this._connected=false;
   this._host='';
   this._port=0;
   this._sndqueue=new Array;
   this._cmdqueue=new Array;
   if (!swfUrl){
      swfUrl="/chat/sock.swf";
   }
   swfUrl+="?"+sId;
   var body=document.getElementsByTagName("body")[0];
   if (body){
      this._div=socket.ce("div");
      this._div.style.position='absolute';
      this._div.style.width='0px';
      this._div.style.height='0px';
      if(body.firstChild){
         body.insertBefore(this._div,body.firstChild);
      }else{
         //alert("appending to body");
         body.appendChild(this._div);
      }
   }else{
      //alert("no body, gonna write");
      document.write("<div id=\"div_" + sId + "\" style=\"position: absolute; width: 0px; height: 0px;\"></div>");
      this._div=document.getElementById("div_"+sId);
   }
   if(window.ActiveXObject){
      var html="";
      html += "<div><object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0\" width=\"0\" height=\"0\" id=\"flash_" + sId + "\" align=\"middle\">";
      html += "<param name=\"allowScriptAccess\" value=\"always\" />";
      html += "<param name=\"movie\" value=\""+swfUrl+"\" />";
      html += "<param name=\"quality\" value=\"high\" />";
      html += "<param name=\"bgcolor\" value=\"#ffffff\" />";
      html += "<param name=\"FlashVars\" value=\"sId="+sId+"\" />";
      html += "<embed src=\""+swfUrl+"\" FlashVars=\"sId="+sId+"\" quality=\"high\" bgcolor=\"#ffffff\" width=\"0\" height=\"0\" name=\"flash_"+sId+"\" align=\"middle\" allowscriptaccess=\"always\" allowFullScreen=\"false\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" />";
      html += "</object></div>";
      this._div.outerHTML=html;
      this._flash=document["flash_"+sId];
   }else{
      var o=document.createElement("object");;
      o.setAttribute("type","application/x-shockwave-flash");
      o.setAttribute("width","0");
      o.setAttribute("height","0");
      o.setAttribute("data",swfUrl);
      o.setAttribute("id","flash_"+sId);
      var parms={"allowscriptaccess":"always","flashvars":"sId="+sId };
      for (var i in parms){
         //var p=socket.ce("PARAM");
         var p=document.createElement("param");
         p.setAttribute("name",i);
	 p.setAttribute("value",parms[i]);
         o.appendChild(p);
      }
      this._div.style.visibility='hidden';
      this._div.appendChild(o);
      this._div.style.visibility='visible';
      //body.appendChild(o);
      //this._div.parentNode.replaceChild(o,this._div);
      this._flash=o;
   }
   this.ondata=function() { return false; }
   this.onevent=function() { return false; }
   this._onevent=function(evt) {
      if (evt=='CONNECT'){
         this._connected=true;
         while (this._sndqueue.length > 0){
            this.send(this._sndqueue.shift());
         }
      }else if (evt=='CLOSE'){
         this._connected=false;
         //alert('disconnect!');
      }
      this.onevent(evt);
   }
   this.echo=function(msg){
      alert(msg);
   }
   this.connect=function(host,port){
      this._host=host;
      this._port=port;  
      if (this._ready){
         this._flash.connect(host,port);
      }else{
         this._cmdqueue.push("this.connect(\""+host+"\","+port+")");
      }
   }
   this.send=function(data){
      if (this._connected){
         this._flash.send(data);
      }else{
         this._sndqueue.push(data);
      }
   }
   this.disconnect=function(){
      this._flash.disconnect();
   }
   this.ready=function(){
      this._ready=true;
      while (this._cmdqueue.length > 0){
         eval(this._cmdqueue.shift());
      }
   }
   return this; 
}   

socket.ce=function(type){
   if(!type) return false;
   if(!this._isIE){
      if(window.ActiveXObject){
         this._isIE=1;
      }else{
         this._isIE=2;
      }
   }
   if(this._isIE == 1){
      return document.createElement(type);
   }else{
      return document.createElementNS("http://www.w3.org/1999/xhtml",type);
   }
}


