﻿// javascript for TheChat control
//debugger;
var msgTimer = "";
var tmrNetwalkerOnOff=""
var isClickedPlus=0;
var alreadyReadCookie=0;
var newalkerRequestTimer;
var changed=0;
var oldNW="";
var colUser="";
var chk=0;
var nwcount=0;
var showmode="*";
var isPageLoad=1;
var isRefresh=1;
ns4 = document.layers
ie4 = document.all 
nn6 = document.getElementById && !document.all
var GobalNetwalkerId=0;
var timer;
var plusParameter=0;
var usrControlChat="";
var isChangeTopic=0;
var gblGroupTopic="";
var privateURL="";
var privateWindowName="";
var privateID="";
var refNetwakerTimer;
var alreadyAddUser=0;
var arrStatus = ['(Offline)', '(Online)', '(Busy)', '(Away)', '(Out for Lunch)'];
////The openedPrivateWindow array will hold the handles of all open child windows
var openedPrivateWindow = new Array();
var openedNetwalkerPrivateWindow = new Array();

//Generate the Random No
function getRandomNo()
{
    var ranNo = Math.random()*100;
    ranNo=Math.round(ranNo);
    return ranNo;
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

//Track open adds the new child window handle to the array.
function trackOpen(winName)
{
    openedPrivateWindow[openedPrivateWindow.length]=winName;
}

//loop over all known child windows and try to close them.  No error is
//thrown if a child window(s) was already closed.
function closePrivateWindows() 
{
    var openCount = openedPrivateWindow.length;
    for(r=0;r<openCount;r++) 
    {
        openedPrivateWindow[r].close();
    }
}

function closePrivateWindowByWindowName(windowName) 
{
    var openCount = openedPrivateWindow.length;
    for(r=0;r<openCount;r++) 
    {
        if(openedPrivateWindow[r]==windowName)
            openedPrivateWindow[r].close();
    }
}

function EditProfile()
{
    var check=null;
    check = window.open('../Fryshuset_Chat/NetwalkerDescription.aspx','NetwalkerDescripstion','width=800,height=1000,left=0,top=0,scrollbars=1,resizable=0');
}
function Launch(url,windowName,id) 
{       var ranNo=getRandomNo();
    privateURL=url;
    privateWindowName=windowName+ranNo;
    privateID=id;
    Fryshuset.Chat.TheCafe.Business.ChatWebMethod.CreatePrivateRoom(id,openPrivateWindow,errorAlert);      
}

function openPrivateWindow(RoomId)
{
    if(RoomId>1)
    {
        var check=null;
        check = window.open('','','width=1,height=1,left=0,top=0,scrollbars=0,resizable=0');        if(check)        {            check.close();
            privateURL = privateURL.replace("../Fryshuset_Chat/"," ");
            privateURL = privateURL.trim();
            privateURL="../Fryshuset_Chat/"+privateURL;
            openedPrivateWindow[openedPrivateWindow.length] = window.open(privateURL+"&RoomId="+RoomId,privateWindowName, "toolbar=0,menubar=0,statusbar=0,location=0,scrollbars=0,resizable=0,width=500,height=440"); 
         }         else         {           alert("Din browser har blockerat ett pop-up fönster. Vänligen stäng av pop-up blockeraren innan du startar en privat chat.");         }  
    }
}

function btnPrivateLoginClick()
{   
   var usrName=document.getElementById("txtUserName");   
   var netwalkerId=document.getElementById("hdnNetwalkerID");
   userClass="asdfg";
   if(usrName && usrName.value!="")
   {
       userClass="clsOn";
       if(usrName.value.trim()!="")
       {
           document.getElementById('n1').style.display="none";
           if(colUser=="")
           {
                colUser=GetColor();
           }
           createCookie("UserName",usrName.value,30);
           var name="<span style='color:#"+colUser+";' class='"+userClass+"'>"+usrName.value+"</span>";
           PageMethods.btnPrivateLoginClick(netwalkerId.value,name,processPrivateLogin,errorAlert);           
       }
   }         
}

function processPrivateLogin(st)
{
    var ArrHFValue = st.split('###');
    for(var i=0;i<ArrHFValue.length;i++)
    {
        var ArrHValue = ArrHFValue[i].split("=");
        var tag=document.getElementById(ArrHValue[0]);//assigned roomid and userid to the hnd variable 
        if(tag)
        { 
            tag.value = ArrHValue[1];
        }
        if(ArrHValue[0]=="hdnRoomID")
        {
            if($get(ArrHValue[0]).value.trim()!="")
            {
              hideObject();
            }
        }
    }            
}
function showObjectById(id)
{
    var obj = document.getElementById(id);
    if(obj)
        obj.style.display="block";
    else    
        alert("Object having id,"+id+", is not found! Show Fail");
}
function hideObjectById(id)
{
    var obj = document.getElementById(id);
    if(obj)
        obj.style.display="none";
    else    
        alert("Object having id,"+id+", is not found! Hide Fail");
}
function LaunchNetwalkerPrivateWindow(url,windowName,RoomId)
{
    var ranNo=getRandomNo();
    openedNetwalkerPrivateWindow[RoomId] = window.open("../Fryshuset_Chat/"+url, windowName+ranNo, "toolbar=0,menubar=0,statusbar=0,location=0,scrollbars=0,resizable=0,width=500,height=350,"); 
}

function openNetwalklerPrivateWindow(RoomId)
{   
    if(RoomId>1)
    {
       openedNetwalkerPrivateWindow[RoomId] = window.open("../Fryshuset_Chat/"+privateURL+"&RoomId="+RoomId,privateWindowName, "toolbar=0,menubar=0,statusbar=0,location=0,scrollbars=0,resizable=0,width=500,height=452"); 
    }
}
function showObject()
{
    document.getElementById('n1').style.display = "block";    
}
function hideObject() {
    document.getElementById("n1").style.display = "none";
}

function showMailDiv(id)
{
    var tg = document.getElementById("divMail"+id);
    if(tg)
        tg.style.display="block";
}

function hideMailDiv(id)
{
    var tg = document.getElementById("divMail"+id);
    if(tg)
        tg.style.display="none";
}

function showOnline(id)
{
    toggle("divOnLine"+id);
    toggle("divOffLine"+id);
}

function showOffLine(id)
{
    toggle("divOnLine"+id);
    toggle("divOffLine"+id);
}
        
function hideMessage()
{
    setTimeout("showMessage()", 3000);
}
        
window.onunload = function closeALLWindows()
                {
                    window.clearTimeout(msgTimer);
                }

var c=1;
function increase()
{	
	var obj1=document.getElementById(usrControlChat+"_divText");
	if(obj1!=null){
		if(c<205) {
		   c=c+(c/8)+1;		   
		   obj1.style.height=c+'px';
	  	}
		if(c==205){
		obj1.style="";
		window.clearInterval(time);
		window.clearTimeout(timer);
		}
	 }
}

function showGeneralChat()
{
    var div=document.getElementById(usrControlChat+"_divText");
    if(div)
    {
        div.style.height=0+"px";
        time=window.setInterval("increase()",5);
    }
}

function onFocusHandler(tag,value)
{
    if(tag.value==value)
        tag.value='';
}

function onBlurHandler(tag,value)
{
    if(tag.value=='')
        tag.value=value;
}

function sendMail(id)
{
   var emailFrom=document.getElementById('textfield'+id);
   var ePost=document.getElementById('textfield2'+id);
   var body=document.getElementById('textarea'+id); 
   if(emailFrom.value==null || emailFrom.value=="" || ePost.value==null || ePost.value=="" || body.value==null || body.value=="")
   {
        //alert("Invalid Username or ePost or Body");
        var inlinewin=dhtmlwindow.open("broadcastbox", "inline","<span style='font-size:16px;margin-left:auto;margin-right:auto;'>Invalid Username or ePost or Body</span>", "Alert", "width=150,height=75,left=750px,top=100px,resize=0,scrolling=0", "recal");
   }
   else
   {
        if(ValidateForm(id))
        {
            Fryshuset.Chat.TheCafe.Business.ChatWebMethod.sendMail(id,emailFrom.value,ePost.value,body.value,skickat);
            document.getElementById("ajaxIcon"+id).style.display="block";
        } 
   }
}

function skickat(st)
{
    var arrRet=st.split("##@#");
    clearMailContents(eval(arrRet[1]))
    var inlinewin=dhtmlwindow.open("broadcastbox", "inline","<div style='font-size:12px;padding: 10px 25px 10px 25px; align:center;'>"+ arrRet[0] +"</div>", "Sending Mail Alert", "width=150,height=75,left=750px,top=200px,resize=0,scrolling=0", "recal");
    
}

function TopicPrivateChat_onclick()
{    
    if(GobalNetwalkerId>0)
    {
        Launch('Privatechat.aspx?NetwalkerID='+GobalNetwalkerId,'mywinGobalNetwalkerId',GobalNetwalkerId);
    }
}

function closeWindow()
{
   var hiddenNetwalkerID=document.getElementById(usrControlChat+"_hdnNetwalkerId");
   var userId = document.getElementById(usrControlChat+"_hdnSessionId");
    if(hiddenNetwalkerID)
    {
        if(hiddenNetwalkerID.value>0)
        {
            Fryshuset.Chat.TheCafe.Business.ChatWebMethod.LogOffNetwalkerByID(hiddenNetwalkerID.value,userId.value);
        }
        else
        {
            Fryshuset.Chat.TheCafe.Business.ChatWebMethod.LogOffNetwalkerByID(0,userId.value);
        }
    }
   window.clearTimeout(msgTimer);
}

function shownw_onclick(nwc)
{
    var userId = document.getElementById(usrControlChat+"_hdnSessionId");
    Fryshuset.Chat.TheCafe.Business.ChatWebMethod.CountAllUser(userId,countUser);
}

function countUser(val)
{
//    var arr=val.split("!@#");
//    for(i=1;i<arr[0];i++)
//    {   
//        v="nwhideshow"+i;
//        nwhideshow=document.getElementById(v)
//        if(nwhideshow)
//            nwhideshow.style.display='block';
//    }
    var isBlackListed = val; //arr[1];
    //alert(isBlackListed);
    if(alreadyAddUser==1)
    {
        createCookie("isBlackListed",isBlackListed,30);
        //alert("Inside isBlackListed "+isBlackListed);
    }
}

function hideme()   //to hide netwalker requester DIV 
{
    var d= document.getElementById(usrControlChat+"_confirmnetwalker")
    if(d)
        d.style.display="none";
}

function CheckNetwalker(varr)
{
    var va=varr.split("##");
    var va1=va[0];          //yes for netwalker is requesting
    var va2=va[1];          //
    var va3=va[2];          //netwalker ID    
    if(va1=="no" && va2=="no" && va3=="no")
    {
        //do nothing
    }
    else
    {
        var d= document.getElementById(usrControlChat+"_confirmnetwalker");
        var dd=document.getElementById(usrControlChat+"_lblNetWalker");
        if(va1=='Yes')           //i.e another netwalker is waiting
        {
            if(d)            //ie. if DIV is present
            {
                //identify the netwalker BROSER by taking value from hndNetWalkerId
                var NetwalkerId=document.getElementById(usrControlChat+"_hdnNetwalkerid").value;
                if(va3==NetwalkerId)    //ie. is the broser is of netwalker
                {
                    d.style.display="block";
                    dd.innerHTML=va2;
                }
            }
        }
        if(va1=='xyz')
            if(d)
                d.style.display="none";
    }
}
function printTopic(val)
{
    if(val!="no")
    {
        var divTopic=document.getElementById(usrControlChat+"_Topic");
        if(divTopic)
            divTopic.innerText=val;
    }    
}

function NetwalkerInterval()
{
    var NetwalkerId=document.getElementById(usrControlChat+"_hdnNetwalkerid").value; 
    Fryshuset.Chat.TheCafe.Business.ChatWebMethod.NetWalkerOnOff(UpdateNetwalkers,errorAlert);//this is to check whether any netwalker is online or offline from the database but it is not used now you can use it if u want
    Fryshuset.Chat.TheCafe.Business.ChatWebMethod.CountAllUser(document.getElementById(usrControlChat+"_hdnSessionId").value,countUser,errorAlert);
    if(NetwalkerId >0)
    {  
        Fryshuset.Chat.TheCafe.Business.ChatWebMethod.NetwalkerPrivateRoom(NetwalkerId,UpdateNetwalkerPrivateRoom);// if a netwalker is online then loop is started to check any private messages posted for him
    }
    else
    {
        Fryshuset.Chat.TheCafe.Business.ChatWebMethod.UserPrivateRoom(document.getElementById(usrControlChat+"_hdnSessionId").value,UpdateUserPrivateRoom,errorAlert1);
    }
    tmrNetwalkerOnOff=window.setTimeout('NetwalkerInterval();',2000);
}   

function onErrorCountUser(st)
{
    //alert(st);
}  

function updateUser(id)//timer for groupchat
{
    usrControlChat=id;   
    Fryshuset.Chat.TheCafe.Business.ChatWebMethod.UpdateMessage(document.getElementById(usrControlChat+"_"+"hdnRoomID").value,document.getElementById(usrControlChat+"_"+"hdnSessionId").value, UpdateMessages,errorAlert);// to check new message and update the message in the message box       
    msgTimer=window.setTimeout("updateUser('"+id+"');",2000);    
    
}          

function errorAlert(obj)
{
//   var result = ""
//   for (var i in obj)
//      result += "Object." + i + " = " + obj[i] + "<hr>";
//   var err1=getRandomNo();
//   var err2=getRandomNo();
//   var err3=getRandomNo();   
//   var inlinewin=dhtmlwindow.open("broadcastbox", "inline","<div style='font-size:12px;padding: 10px 25px 10px 25px; align:center;'>"+ result +"</div>", "Web Service Error "+err1, "width=800,height=600,left=0px,top=0px,resize=1,scrolling=1", "recal");
}
function errorAlert1(obj)
{
//   var result = ""
//   for (var i in obj)
//      result += i + " = " + obj[i] + "<hr>";
//   var inlinewin=dhtmlwindow.open("broadcastbox", "inline","<div style='font-size:12px;padding: 10px 25px 10px 25px; align:center;'>"+ result +"</div>", "Web Service Error user", "width=400,height=300,left=100px,top=100px,resize=1,scrolling=1", "recal");
}

function button_clicked()
{
    var usrName=null;
    aField = document.getElementById(usrControlChat+"_txtUserName"); 
    netUsername = document.getElementById(usrControlChat+"_hdnNetwalkerName");
    userType = document.getElementById(usrControlChat+"_UserType").value;
    userClass = 'asdfg';
    if(netUsername.value=="")
    {
        usrName=readCookie("UserName");
        if(usrName==null && aField.value.length>0)
        {
            userClass="clsOn";
            usrName = aField.value;
        }
    }
    else
    {
        if(userType=="0")
            userClass="clsNw";
        else
            userClass="clsOn";
            
        usrName=netUsername.value;
    }
    if(usrName && alreadyReadCookie!=1)
    {   
        alreadyReadCookie=1;
        var hdnSessionId=document.getElementById(usrControlChat+"_hdnSessionId");
        aField.value=usrName;
        var isBlackListed = readCookie("isBlackListed");
        //alert(isBlackListed);
        if(isBlackListed==null)
            isBlackListed = 0;
        if (colUser==""){colUser=GetColor();}
        usrName="<span style='color:#"+colUser+"' class='"+userClass+"'>"+usrName+"</span>";           
        Fryshuset.Chat.TheCafe.Business.ChatWebMethod.GetGroupDetail(usrName,hdnSessionId.value,isBlackListed,readCookie("UniqueChatUserID"),getDetail,errorAlert);
    }
    else if(usrName==null)
    {
        showObject(); //Username Entry Form
    }
    else if(document.getElementById(usrControlChat+"_txtMsg").value.trim()=="")
    {
        return;
    }        
    else
    {
        try
        {
            if(document.getElementById(usrControlChat+"_txtMsg").value.trim()!="")
            {
                Fryshuset.Chat.TheCafe.Business.ChatWebMethod.SendMessage(document.getElementById(usrControlChat+"_txtMsg").value.trim(),document.getElementById(usrControlChat+"_hdnSessionId").value,document.getElementById(usrControlChat+"_hdnRoomID").value,isSuccessful,errorAlert);
                document.getElementById(usrControlChat+"_txtMsg").value="";    
            }
        }
        catch(ex)
        {
            throw ex;
        }
    }
}
function isSuccessful(result)
{
    if(result!="")
    {
        var msgBox=document.getElementById(usrControlChat+"_msg");
        msgBox.innerHTML=msgBox.innerHTML+result;   
        msgBox.scrollTop = msgBox.scrollHeight;
    }  
}
    
function clickButton(e, buttonid)//SEnDING MESSAGE TO OTHERS
{
    var keyCode = window.event ? window.event.keyCode : e.which;
    var bt = document.getElementById(buttonid); 
    if(bt)
    { 
        if (keyCode == 13)
        {   
            bt.click(); 
            return false; 
        } 
    }	 
}

function changeUserName()
{
    var usrName=document.getElementById('txtNamn');    
    var usrId=document.getElementById(usrControlChat+"_hdnSessionId");
    createCookie("UserName",usrName.value,30);
    Fryshuset.Chat.TheCafe.Business.ChatWebMethod.changeUserName(usrId.value,usrName.value,readCookie("UniqueChatUserID"),processChangeUserName)
}
function processChangeUserName(result)
{
    if(result==1)
    {
        showObjectById('cngUsrNam');
        hideObjectById('Namn');
    }
}
function UpdateMessages(result)
{
    if(result!="")
    {
        var msgBox=document.getElementById(usrControlChat+"_msg");
        msgBox.innerHTML=msgBox.innerHTML+result;   
        msgBox.scrollTop = msgBox.scrollHeight;
    }      
}

function UpdateNetwalkers(result)
{ 
    try
    {    
        var arr = result.split("!@#");
        var obj = document.getElementById(usrControlChat+"_OnlineNetwalkerNo");
        var hdnOnlineCount = obj.value;
        if((arr[1]*1)!= (hdnOnlineCount*1))
        {
            obj.value=arr[1];
            Fryshuset.Chat.TheCafe.Business.ChatWebMethod.RefreshNetwalkerList(GobalNetwalkerId,removeOldNetwalkerList,errorAlert);
            Fryshuset.Chat.TheCafe.Business.ChatWebMethod.RefreshOnlinUserList(GobalNetwalkerId,removeOldOnlineUser,errorAlert);
        }
        var users=arr[0];
        var user=users.split(";");
        var netwalkerid;
        for(var i=0;i<user.length;i++)
        {
            var Netwalker=user[i].split(":");
            var userid=Netwalker[0];
            var isonline=Netwalker[1];
            netwalkerid=Netwalker[2]; 
            var netwalkerStatus = Netwalker[3];   
            //if(isonline==1)
            //{
                var netStat=document.getElementById("netwalkerstatus"+userid);
                if(netStat)
                    netStat.innerHTML = arrStatus[netwalkerStatus];
            //}   
            if(netwalkerid==document.getElementById(usrControlChat+"_hdnNetwalkerid").value)
            {
                document.getElementById("PrivateChatImg").style.display='none';
            }
            else
            {
                document.getElementById("PrivateChatImg").style.display='block';
            }
                
//            var masterdiv = document.getElementById('masterdiv'+userid);
//            var divOnLine = document.getElementById('divOnLine'+userid);
//            var divOffLine = document.getElementById('divOffLine'+userid);
//            var tblsend = document.getElementById('tblsend');
//            if(isonline>0)
//            {  
//                if(divOnLine)
//                {
//                    divOnLine.style.display='block';
//                }
//                if(divOffLine)
//                {
//                    divOffLine.style.display='none';
//                }
//            }
//            else
//            {
//                if(divOnLine)
//                {
//                    divOnLine.style.display="none";
//                }
//                if(divOffLine)
//                {
//                    divOffLine.style.display="block";
//                }
//            }     
        }
        GobalNetwalkerId=netwalkerid;
        if(netwalkerid>0)       //room is On
        {
            //shownw_onclick(3);            //show default 3/4 netwalker                      
            var tag1=document.getElementById('tblsend');
            if(tag1)
            {
                 tag1.style.display="block";                 
            }
            var tag2=document.getElementById(usrControlChat+"_Topic");
            if(tag2)
            {
                tag2.style.display="block";
            }
            var tag3=document.getElementById(usrControlChat+"_txt");
            if(tag3)
            {
                tag3.style.display="block";
            }
            var tag4=document.getElementById('wpnl');
            if(tag4)
            {
                tag4.style.display="block";
            }
            if(changed==1)
            {
                changed=0;
                img=document.getElementById(usrControlChat+"_netwalkerPhoto");
                if(img)
                {
                    img.src = "../Uploads/NetwalkerImage/Big/" + netwalkerid + ".png";
                }
            }
            Fryshuset.Chat.TheCafe.Business.ChatWebMethod.GroupTopic(UpdateLoggedNetwalker,errorAlert);
            isRefresh=0;
        }
        else            //room is on
        {
            //shownw_onclick('7'); //show 7 netwalker
            changed=1;
            oldNW=0;      
            hidePageObject('wpnl');
            hidePageObject(usrControlChat+"_Topic");
            hidePageObject(usrControlChat+"_txt");
            hidePageObject('tblsend');
            if(isRefresh==0)
            {
                isRefresh=1;
                Fryshuset.Chat.TheCafe.Business.ChatWebMethod.RefreshNetwalkerList(GobalNetwalkerId,removeOldNetwalkerList,errorAlert);
                Fryshuset.Chat.TheCafe.Business.ChatWebMethod.RefreshOnlinUserList(GobalNetwalkerId,removeOldOnlineUser,errorAlert);                
            }    
        }
        if(oldNW!="" && (oldNW!=netwalkerid || isChangeTopic==1))
        {
            oldNW=netwalkerid;
        }
        else
        {
            oldNW=netwalkerid;
        }      
    }
    catch(ex)
    {
        throw ex;   
    }
}
function removeOldOnlineUser(retVal)
{
    if(retVal!="")
    {
        var divOnlineList = document.getElementById(usrControlChat+"_divOnlineList");
        if(divOnlineList)
            divOnlineList.innerHTML=retVal;
    }
}
function removeOldNetwalkerList(retVal)
{
    if(retVal!="")
    {       
        var divNetwalkerList = document.getElementById(usrControlChat+"_divNetwalkerList");
        if(divNetwalkerList)
            divNetwalkerList.innerHTML=retVal;
    }
}


function toggle(id)
{
    var tg = document.getElementById(id);
    if(tg)
    {
        if(tg.style.display=="none")    //if display is hidden/false
        {
            tg.style.display="block";   //i.e show
        }
        else if(tg.style.display=="block" || tg.style.display=="")
        {
            tg.style.display="none";
        }
    }
}
        

function UpdateLoggedNetwalker(result)
{     
    var img;
    var GroupTopic=document.getElementById(usrControlChat+"_hdnTopic");
    if(result!="" && result!="notopic")// (result.length>7)
    {                
        var arrVal=result.split("###");
        var StringNewalkerDetail=arrVal[0];
        var NewalkerDetail=StringNewalkerDetail.split(";");
        var userId=NewalkerDetail[0];
        var username=NewalkerDetail[1];
        var BriefDescription=NewalkerDetail[2];
        var Age=NewalkerDetail[3];
        var UserOccupation=document.getElementById(usrControlChat+"_UserOccupation");
        var netwalkerName=document.getElementById(usrControlChat+"_netwalkerName");    
        netwalkerName.innerHTML=username; 
        UserOccupation.className ="showTip "+userId; 
        if(arrVal[1]!="" && arrVal[1]!= null)
        {
            var arrRoom=arrVal[1].split("=");
            if(arrRoom[0]=="Room")
            {   
                if(GroupTopic.value.trim()!=arrRoom[1].trim())
                {
                    GroupTopic.value=arrRoom[1];
                    Fryshuset.Chat.TheCafe.Business.ChatWebMethod.GroupTopic(UpdateLoggedNetwalker,errorAlert);
                    Fryshuset.Chat.TheCafe.Business.ChatWebMethod.RefreshNetwalkerList(GobalNetwalkerId,removeOldNetwalkerList,errorAlert);
                    Fryshuset.Chat.TheCafe.Business.ChatWebMethod.RefreshOnlinUserList(GobalNetwalkerId,removeOldOnlineUser,errorAlert);
                    var msgUL = document.getElementById(usrControlChat+"_msg");
                    if(msgUL)
                    {
                        msgUL.innerHTML=""; 
                    }
                    img=document.getElementById(usrControlChat+"_netwalkerPhoto");
                    img.src = "../Uploads/NetwalkerImage/Big/" + userId + ".png";
                    hideme();  
                }                
                var divTopic=document.getElementById(usrControlChat+"_Topic");              
               
                if(divTopic)
                {
                    divTopic.innerHTML="<b>"+arrRoom[1]+" </b>";
                }
                
               
               var wrapperColTitle = document.getElementById(usrControlChat+"_wrapperColTitle")               
              if(NewalkerDetail[5] == 1)
              {
                if(UserOccupation)
                {                   
                    wrapperColTitle.innerHTML="<div class=colTitleBlue id=colTitle runat=server><h3 style='color:white; font-size:18px; font-weight:bold; font-family:'Arial Bold''>ONLINE</h3></div>";
                    UserOccupation.innerHTML=NewalkerDetail[4];                    
                }
              }
              else
              {
                    UserOccupation.innerHTML ="Nätvandrare";
                    wrapperColTitle.innerHTML="<div class=colTitle id=colTitle runat=server><h3>Nätvandrare</h3></div>";   
               }                
            }
            if(userId>0)
            {
                img=document.getElementById(usrControlChat+"_netwalkerPhoto");
                img.src="../Uploads/NetwalkerImage/Big/" + userId + ".png";
                var hdnNetID = document.getElementById(usrControlChat+"_hdnNetwalkerid");
                if(hdnNetID)
                {
                    if(hdnNetID.value==userId )
                    {
                        Fryshuset.Chat.TheCafe.Business.ChatWebMethod.NetwalkerRequest(document.getElementById(usrControlChat+"_hdnRoomID").value,document.getElementById(usrControlChat+"_hdnSessionId").value,CheckNetwalker,errorAlert);
                    }
                }
            }
        }
    }
    else
    {
    
    }
}

function UpdateMembersList(result)
{
    var users=result.split(",");
    var i=0;
    document.getElementById("lstMembers").options.length=0;
    while (i < users.length)
    {
        if (users[i]!="")
        {
            var op=new Option(users[i],users[i]);
            document.getElementById("lstMembers").options[document.getElementById("lstMembers").options.length]= op;
        }
        i+=1;
    }
}

function UpdateNetwalkerPrivateRoom(result)
{
    if(result!="")
    {
        var rooms=result.split("###&");
        for(var i=0;i<rooms.length-1;i++)
        { 
            var EachRoom=rooms[i];
            var Netwalkerid=document.getElementById(usrControlChat+'_hdnNetwalkerid').value;
            var url="NetwalkerPrivateChat.aspx?NId="+Netwalkerid+"&RId="+EachRoom;
            var windowName="PrivateRoom"+EachRoom;
            LaunchNetwalkerPrivateWindow(url,windowName,EachRoom);
        }
    }
}

function errorCallback(result)
{    
    window.clearTimeout(msgTimer);
    window.clearTimeout(tmrNetwalkerOnOff);
    msgTimer=window.setTimeout("updateUser('"+usrControlChat+"');",2000);
    tmrNetwalkerOnOff=window.setTimeout('NetwalkerInterval();',2000);
}

function  deletejunk()
{
    var UserId;
    var RoomId;
    window.clearTimeout(msgTimer);
    if(document.getElementById(usrControlChat+"_hdnSessionId")!=null)
    {
       UserId=document.getElementById(usrControlChat+"_hdnSessionId").value;
       RoomId=document.getElementById(usrControlChat+"_hdnRoomID").value;
       if(UserId=="")
       {
           UserId=0;
       }
       if(RoomId=="")
       {
           RoomId=0;
       }
        window.clearTimeout(msgTimer);
        Fryshuset.Chat.TheCafe.Business.ChatWebMethod.DeleteJunkFromDatabase(UserId,RoomId);
        window.close();        
    }
}

function btnLoginClick()
{
    var usrName = document.getElementById(usrControlChat+"_txtUserName").value;
    userType = document.getElementById(usrControlChat+"_UserType").value;
    userClass = 'asdfg';
    if(usrName!=null || usrName!="")
    {
        userClass="clsOn";
            
        var hdn=document.getElementById(usrControlChat+"_hdnSessionId").value;
        createCookie("UserName",usrName,30);
        var isBlackListed = readCookie("isBlackListed");
        if(isBlackListed==null)
            isBlackListed=0;
        colUser=GetColor();
        usrName="<span style='color:#"+colUser+"' class='"+userClass+"'>"+usrName+"</span>";     
        alreadyReadCookie=1;       
        Fryshuset.Chat.TheCafe.Business.ChatWebMethod.GetGroupDetail(usrName,hdn,isBlackListed,readCookie("UniqueChatUserID"),getDetail,errorAlert);
        var div = document.getElementById(usrControlChat+"_n1");
        if(div)
            div.style.display="none";
    }
} 
 
//function to return random color 
function GetColor(){
    colors = new Array(14)
    colors[0]="0"
    colors[1]="9"
    colors[2]="8"
    colors[3]="7"
    colors[4]="6"
    colors[15]="5"
    colors[5]="4"
    colors[6]="3"
    colors[7]="2"
    colors[8]="1"
    colors[9]="f"
    colors[10]="e"
    colors[11]="d"
    colors[12]="c"
    colors[13]="b"
    colors[14]="a"

    digit = new Array(5)
    color=""
    for (i=0;i<6;i++)
    {
        digit[i]=colors[Math.round(Math.random()*15)];
        color = color+digit[i];
    }
    return color;
}
//end of random color generator
 
//--------------- read , write cookie-------------------
function createCookie(name,value,days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires="+date.toGMTString();
    }
    else
        expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(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 hidePageObject(object)
{
   var objecttohide=document.getElementById(object);
    objecttohide.style.display="none";
}
function DisplayPageObject(object)
{
    var objecttohide=document.getElementById(object);  
    objecttohide.style.display="block";
}
function AssignValueToObject(control,controlvalue)
{
    var ControlName;
    if(document.getElementById(control)!=null)
    {
        ControlName=document.getElementById(control);    
    }
    ControlName.value=controlvalue;
}

function getDetail(st)
{
    
    var ArrHFValue = st.split('#');
    for(var i=0;i<ArrHFValue.length;i++)
    {
        var ArrHValue = ArrHFValue[i].split("=");
        var tag=document.getElementById(usrControlChat+"_"+ArrHValue[0]);//assigned roomid to the hnd variable 
        if(tag)
        { 
            tag.value = ArrHValue[1];
        }
        if(ArrHValue[0]=="hdnSessionId")
        {
            if(ArrHValue[1]>0)
            {
               hideObject();
               if(document.getElementById(usrControlChat+"_txtMsg").value.trim()!=="")
               {
                    Fryshuset.Chat.TheCafe.Business.ChatWebMethod.SendMessage(document.getElementById(usrControlChat+"_txtMsg").value.trim(),document.getElementById(usrControlChat+"_hdnSessionId").value,document.getElementById(usrControlChat+"_hdnRoomID").value,isSuccessful,errorAlert);
                    document.getElementById(usrControlChat+"_txtMsg").value="";
               }               
            }
            if(ArrHValue[1]==-1)
            {
                AssignValueToObject('LblUserMessage','User already exist select a different name');
            }
        }
    }    
    alreadyAddUser=1;     
}

function echeck(str)
{
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
	   return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
	    return false
	}

	 if (str.indexOf(at,(lat+1))!=-1){
	    return false
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
	    return false
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
	    return false
	 }
	
	 if (str.indexOf(" ")!=-1){
	    return false
	 }
	 return true					
}

function ValidateForm(Id){
	var emailID=document.getElementById("textfield2"+Id);	
	if ((emailID.value==null)||(emailID.value=="")){
		emailID.focus()
		return false
	}
	if (echeck(emailID.value)==false){
		emailID.select();
		return false
	}
	var mesg=document.getElementById("textarea"+Id)
	if(mesg)
	    mesg.focus();
	return true
}

 function disableenter(e,id)
 {
    var keycode = window.event ? window.event.keyCode : e.which;
     if(e.keyCode==13)
     {
        ValidateForm(id);
        return false;
     }
 }
 function disableFromtextField(e,id)
 {
    var mesg=document.getElementById("textfield"+id)
   	var emailID=document.getElementById("textfield2"+id);
   	var keycode = window.event ? window.event.keyCode : e.which;
      if(keycode==13)
      {
          if ((mesg.value==null)||(mesg.value==""))
          {
	        mesg.focus()
	        return false
          }
          else
          {
            if(mesg)
                emailID.focus();
            
             return false;
           }
      }
 }
 
function showdivOffLineMessage(id)
{
    var tg = document.getElementById("divOffLineMessage"+id);
    if(tg)
        tg.style.display="block";
}

function hidedivOffLineMessage(id)
{
    var tg = document.getElementById("divOffLineMessage"+id);
    if(tg)
        tg.style.display="none";
}

function sendOfflineMessage(id)
{
    var sender="";
    var txtArea=document.getElementById("txtareaOfflineMessage"+id);
    if(document.getElementById(usrControlChat+"_hdnNetwalkerName").value!="")
    {
        sender = document.getElementById(usrControlChat+"_hdnNetwalkerName").value;
    }
    else
    {
        sender=readCookie("UserName");
    }
    if(txtArea.value.trim().length>0)
    {
        Fryshuset.Chat.TheCafe.Business.ChatWebMethod.sendOfflineMessage(sender,id,txtArea.value);
        cancelOfflineMessage(id);
    }
    else
    {
        var inlinewin=dhtmlwindow.open("broadcastbox", "inline","<span style='font-size:16px;margin-left:auto;margin-right:auto;'>Blank message</span>", "Alert", "width=300px,height=100px,left=750px,top=100px,resize=1,scrolling=0", "recal");
    }
}

function cancelOfflineMessage(id)
{
    var textarea=document.getElementById("txtareaOfflineMessage"+id);
    textarea.value="";
    hidedivOffLineMessage(id);
}

function divshowOfflineMessage()
{
    var tg=document.getElementById("divshowOfflineMessages");
    if(tg)
        tg.style.display="block"; 
    
}

function clearMailContents(id)
{
    var emailFrom=document.getElementById('textfield'+id);
    var ePost=document.getElementById('textfield2'+id);
    var body=document.getElementById('textarea'+id); 
    emailFrom.value="Namn";
    ePost.value="E-Post";
    body.value="Meddelande";
    document.getElementById("ajaxIcon"+id).style.display="none";
    hideMailDiv(id);
}

function btnAllow1_onclick() {
   var netwalkername=document.getElementById(usrControlChat+"_lblNetWalker").innerHTML;
    Fryshuset.Chat.TheCafe.Business.ChatWebMethod.Accept("1",netwalkername,"Allow");
    Fryshuset.Chat.TheCafe.Business.ChatWebMethod.DeleOldMsg("1");                //deleting old message after next re-loged on by new NetWalker
    hideme();    
    window.clearInterval(newalkerRequestTimer);
}

function Button1_onclick() {
    var netwalkername=document.getElementById(usrControlChat+"_lblNetWalker").innerHTML;
    Fryshuset.Chat.TheCafe.Business.ChatWebMethod.Accept("1",netwalkername,"Ignore");
    hideme();
}

function ActiveNetwalkerPrivateWindow(RoomId,Netwalkerid)
{
    if(openedNetwalkerPrivateWindow[RoomId])
    {
       var browserName = window.navigator.userAgent;
       if(browserName.indexOf("Safari") > -1)
       {
            alertspan.innerHTML="This Function is not Supported in Safari";           
       }
       else
       {
            try
            {
                openedNetwalkerPrivateWindow[RoomId].focus();
            }
            catch(ex)
            {
            }
       }
    }
    else
    {
        var url="NetwalkerPrivateChat.aspx?NId="+Netwalkerid+"&RId="+RoomId;
        var windowName="PrivateRoom"+RoomId;
        LaunchNetwalkerPrivateWindow(url,windowName,RoomId);        
    }
}

function clearAllTimer()
{
    window.clearTimeout(msgTimer);
    window.clearTimeout(tmrNetwalkerOnOff);
    window.clearTimeout(timerAdminPanel);
    window.clearTimeout(timer);
}


/// status change
function netWalkerStatus()
{
 clientID=document.getElementById("ClientID").value;
 var value=document.getElementById("statusCheck").value; 
 var ID = document.getElementById(clientID + "_curNetwalkertID").value;
Fryshuset.Chat.TheCafe.Business.ChatWebMethod.netWalkerStatusChange(ID,value);
}


function UpdateUserPrivateRoom(result)
{    
    if(result!="")
    {
        var rooms=result.split("###&");
        for(var i=0;i<rooms.length-1;i++)
        {
            var arrEachRoom=rooms[i].split("@@#@");
            var url="PrivateChat.aspx?NetwalkerID="+arrEachRoom[1]+"&RoomId="+arrEachRoom[0];
            var windowName="PrivateRoom"+arrEachRoom[0]+getRandomNo();
            
            var check=null;
            check = window.open('','','width=1,height=1,left=0,top=0,scrollbars=0,resizable=0');            if(check)            {                check.close();
                openedPrivateWindow[openedPrivateWindow.length] = window.open("../Fryshuset_Chat/"+url,windowName, "toolbar=0,menubar=0,statusbar=0,location=0,scrollbars=0,resizable=0,width=500,height=440"); 
             }             else             {               alert("Din browser har blockerat ett pop-up fönster. Vänligen stäng av pop-up blockeraren innan du startar en privat chat.");             }  
        }
    }
}

