     var xmlDoc;
     var alertLeft= 50;
     var alertTop = 50;

     var ie_compatible=false;
     var firefox_compatible=false;
     var errorCount = 0;
     var successiveErrorCount=0;
     var successiveErrorCountLimit = 3;
     var delay=5000;
     var timerId;

     var isFocused=true; // init the isFocused var with True. Window is focused
     var docTitle = document.title;
     var unseenMsgCount=0;
     var currentUsers=new Array();
     var messagesDiv;
     var firstFetch=true;
     var RightPanelFullWidth = "248px";
     var leftPanelD;
     var PrivateTo=new Array();
     var mesInput;
     var usernameTd;
     var alertHeight=0;
     var alertWin = null;
     var showTime = true;
     var showDay = true;
     var userChosenStyle = null;
     var menusArray = null;
     var waitingResponse=false;
     var responseCheckerTimer;
     var lastRequestMillis;

    function postAchatMessage(type,msg)
    {


       mesInput = document.getElementById("message");
       if (msg == null){
       	 mesText = mesInput.value;}
       else
       { mesText=msg;}
       if (mesText != "")
            {

                mesText=encodeURIComponent(mesText);
                params="message=" + mesText;
                params += "&";

                params += "last_id=" + lastId;
                params += "&";
                if (type == null){
                params += "type=message" ;
                }
                else
                {params += "type="+ type ;}

                if (PrivateTo.length > 0)
                    {params += "&";
                     params += "private_to=";

                     for (var i=0; i<PrivateTo.length; i++ )
                            {params += PrivateTo[i][0];
                             if (PrivateTo.length > 1 && i != PrivateTo.length -1)
                                {params += ",";}
                            }
                     }


                clearTimeout(timerId);

                http( 'post'  , chatPostHref , My_Response , params);
                mesInput.value="";
            }
            else
            {
                alert("write something please");
            }


    }


    function pollMessages()
    {
        clearTimeout(timerId);
        timerId = setTimeout("getMessages()",delay);
    }


    function checkResponseReturned(){
    	no=new Date();
    	if ( no.valueOf() - lastRequestMillis > 9000)
    	{//alert("retrying to get messages");
    	getMessages();}

    }


    function getMessages()
    {

        params = "last_id=" + lastId + '&';
        params  += "users="+ currentUsers.join(',');
        
        waitingResponse=true;
        clearTimeout(responseCheckerTimer);

        n=new Date();
        lastRequestMillis= n.valueOf();
        responseCheckerTimer = setTimeout("checkResponseReturned()",10000);
        http( 'post'  , chatGetHref , My_Response , params);
    }


    function inMsg(msg)
    {

        NoteElem = document.getElementById('Note');
        NoteElem.innerHTML = msg;

    }

    function showAlerts()
    {

        alertWin = document.getElementById('alertWindow');
        if (alertWin.style.display == "block")
        {
            messagesScrollToTop();

        }
    }

    function inAlert(msg)
    {
        alertElem = document.getElementById('alert');
        alertElem.innerHTML = msg;
        alertWin = document.getElementById('alertWindow');
        alertWin.style.display="block";
        messagesScrollToTop();

    }






    function My_Response(obj)
    {		waitingResponse= false;
    		clearTimeout(responseCheckerTimer);
    		
            if (obj["type"]=="xml") 
            {
                inMsg('');
                continuousErrorCount=0;
             
                if (ie_compatible || firefox_compatible){
                	if (ie_compatible ){
                		 
                		xml = obj["data"].xml;
                        xmlDoc.loadXML(obj["data"].xml);                                       		
                		
                	}
                	else if (firefox_compatible)
                    { 
                        xmlDoc=obj["data"];
                       
                    }
                	
                	 if (xmlDoc.childNodes.length>0){
                		 
                		 if (xmlDoc.childNodes[0].nodeName != 'e'){
                			 processXml(xmlDoc);
                			 
                		 }
                	 }
                	 pollMessages();
                }
                               
                else
                {
                    alert('Your browser cannot handle this script');
                }
               
            }
            else
            {	
                successiveErrorCount +=1;
                errorCount +=1
                if (successiveErrorCount > 1)
                     {msg = successiveErrorCount + " successive errors"; }
                else
                     {msg = 'error';}
                inMsg(msg);
                appendError(obj["data"]);
                if (successiveErrorCount > successiveErrorCountLimit)
                    {
                        msg = "Succesive error count bigger than " + successiveErrorCountLimit + ". ";
                        msg +="<br/> Stopping polling messages.";
                        inAlert(msg);

                    }
                else
                    {pollMessages();}

             }

    }



    function msgbox(title , msg)
    {
        msgboxDiv = document.getElementById('msgbox');
        msgboxDiv.style.display = "block";

        msgboxTitle = document.getElementById('msgboxTitle');
        msgboxTitle.innerHTML = title;

        msgboxData = document.getElementById('msgboxData');
        msgboxData.innerHTML = msg;


    }


    function showError(id)
    {
        errorTitle = document.getElementById(id + '_title');
        title = errorTitle.innerHTML;
        errorData = document.getElementById(id + '_data');
        data = errorData.innerHTML;
        msgbox(title , data);

    }




    function appendError(data)
    {

            now = new Date();
            receivedTime = now.toString();
            id = 'error_' + receivedTime;

            errorTitle = document.createElement('h3');
            errorTitle.innerHTML = 'Non XML Response received on : ' + receivedTime ;
            errorTitle.setAttribute('id' , id + '_title');
            errorTitle.setAttribute("style","display:none");

            errorData = document.createElement('pre');
            errorData.innerHTML = data;
            errorData.setAttribute('id' , id + '_data');
            errorData.setAttribute("style","display:none");


            errorA = document.createElement('a');
            errorA.setAttribute("href","#");
            errorA.setAttribute("style","display:block;");
            errorA.setAttribute("class","smallLink");
            errorA.setAttribute("onclick" , "showError('"+ id + "');return false");
            errorA.innerHTML =  receivedTime;


            errorsDiv = document.getElementById("errors_tab");

            errorsDiv.appendChild (errorA);
            errorsDiv.appendChild (errorTitle);
            errorsDiv.appendChild (errorData);

            errorsTitleSpan = document.getElementById("errorsTitle");
            t =  "Errors (" + errorCount +  ")";
            errorsTitleSpan.innerHTML = t;

    }


    function processXml(xmlDoc)
    {
            redirect = xmlDoc.getElementsByTagName("redirect");
            if (redirect.length > 0)
            {
                window.location = redirect[0].firstChild.data ;
            }
            else
            {
				newMessagesCount=0;
                messageNodes=xmlDoc.getElementsByTagName("message");
            	now = new Date();
                receivedTime = now.toString();
                lastRefreshSpan = document.getElementById('lastRefresh');
                lastRefreshSpan.innerHTML = receivedTime;

                unseenMessages(newMessagesCount);
                onlineUsers(xmlDoc);


                timetakenNodes=xmlDoc.getElementsByTagName("time_taken");
                if (timetakenNodes.length>0)
                    {
                    timetaken_val = timetakenNodes[0].firstChild.data ;
                    serverProcessTimeSpan = document.getElementById('serverProcessTime');
                    serverProcessTimeSpan.innerHTML = timetaken_val;
                    }

                showAlerts();


                for (i=0;i<messageNodes.length;i++)
                {   msgId=messageNodes[i].getAttribute("id");
                    if (!document.getElementById(msgId))
                    {   data = messageNodes[i].firstChild.data ;

                        //data=unescape(data);
                        data = decodeURIComponent(data);

                        username=messageNodes[i].getAttribute("username");
                        usernamestyle= messageNodes[i].getAttribute("usernamestyle");
                        private_to = messageNodes[i].getAttribute("private_to");
                        type = messageNodes[i].getAttribute("type");
                        if (type == 'message')
                        	{appendMessage(msgId, username, data, usernamestyle, private_to);}
                        else if (type == 'busy')
                        	{appendInfoMessage(data,msgId);
                        	 setUserBusy(username,true);
                        	}
                         else if (type == 'notbusy')
                        	{appendInfoMessage(data,msgId);
                        	 setUserBusy(username,false);
                        	}
                        newMessagesCount += 1;
                    }
                }
                lastIdCheckedNodes=xmlDoc.getElementsByTagName("last_id_checked");
                if (lastIdCheckedNodes.length > 0)
                {
                    lastIdCheckedNode=lastIdCheckedNodes[0];
                    lastId=lastIdCheckedNode.firstChild.data ;

                }

                pollMessages();
            }
    }

	function setUserBusy(username,busy){
           userdt = document.getElementById('u_' + username);
           if (userdt){
	           	if (busy){
	    			clasn = userdt.className;
					if (clasn.search("busy") == -1 ){
						userdt.className = "busy " + clasn ;
					}
					document.getElementById("BusyButtonText").innerHTML = "not busy";
	           	}else{

					clasn = userdt.className;
					nclass = clasn.replace("busy","");
					userdt.className = nclass ;
					document.getElementById("BusyButtonText").innerHTML = "i am busy";
	           	}
            }
	}

    function unseenMessages(newMessagesCount)
    {

            if (!isFocused )
                {
                 unseenMsgCount +=  newMessagesCount;
                 if( unseenMsgCount > 0 )
                        {
                         document.title = docTitle + " [" + unseenMsgCount + "]" ;
                        }
                }

    }

    function onlineUsers(xmlDoc)
    {

            onlineUsersArr=xmlDoc.getElementsByTagName("user");
            OnlineUsersDl=document.getElementById("OnlineUsers");
            fetchedUsers=new Array();
            newUsers = new Array();
            onlineUsersHtml="";
            for (i=0;i<onlineUsersArr.length;i++)
            {       usernamestyle = onlineUsersArr[i].getAttribute("usernamestyle");
                    username = onlineUsersArr[i].firstChild.data ;

                    if (! inArray(username,currentUsers)){
					dtel = document.createElement('dt');
	                    if (username != myUsername)
	                        {
	                          ael = document.createElement('a');
	                          atext =document.createTextNode(username);
	  						  dtel.appendChild(ael);
	  						  dtel.setAttribute('id','u_' + username);
							  ael.appendChild(atext);
							  ael.setAttribute('href','#');
							  ael.setAttribute('onclick',"javascript:setPrivateTo('" +  username +"' , '" + usernamestyle + "');return false;");
							  ael.setAttribute('class','username ' + usernamestyle);
	                        }
	                    else
	                        { dtel.setAttribute('id','u_' + username);
	                          atext =document.createTextNode(username);
							  dtel.setAttribute('class','username ' + usernamestyle);
							  atext =document.createTextNode(username);
							  dtel.appendChild(atext);
	                         }


                   		newUsers.push(username);
                   		OnlineUsersDl.appendChild(dtel);
                    }
                    fetchedUsers.push(username);

            }


            if (!firstFetch)
            {

                quitedUsers=diffElements(fetchedUsers , currentUsers);

                //alert("quitedUsers= " + quitedUsers);
                for (var i=0;i<quitedUsers.length;i++)
                    {clearPrivateTo(quitedUsers[i]);

                     ouUserDt = document.getElementById('u_' + quitedUsers[i]);
                     OnlineUsersDl.removeChild(ouUserDt);
                    }
                showUserInfoMessages( quitedUsers , " quited" );
                showUserInfoMessages( newUsers," comes in" );
            }
            else
            {
                appendInfoMessage( "Welcome " + myUsername );
                firstFetch=false;
            }
			currentUsers = fetchedUsers;

    }

   function setPrivateTo(user,style)
   {
    exists=false;
    for (var i=0;i<PrivateTo.length;i++)
        {if (PrivateTo[i][0] == user)
            {
            exists=true;
            break;
            }
        }
    if (!exists)
    {
        PrivateTo.push([user,style]);
        arrangeUserNameHtml();
        mesInput.focus();
    }
    arrangeMsgBoxSize();
   }

   function arrangeUserNameHtml()
    {

    userNameElem = document.getElementById("UserName");
    tmpHtml =  myUsername;
    for(i=0;i<PrivateTo.length;i++)
    {
        if (i==0)
        {
            tmpHtml += " to " ;
        }
        privateUser = PrivateTo[i][0];
        userCssClass = PrivateTo[i][1];
        tmpHtml += '<a href="#" title="Turn off private messaging to '+  userCssClass + '" onclick="clearPrivateTo(\''+ privateUser +'\');return false" class="username ' + userCssClass + '">' + privateUser + '</a>';
        if (PrivateTo.length > 1 && i != PrivateTo.length - 1)
            {
            tmpHtml += " , ";
            }
    }

    userNameElem.innerHTML=tmpHtml;

    }


   function clearPrivateTo(user)
   {

    found=false;
    for (i=0;i<PrivateTo.length;i++)
    {if (PrivateTo[i][0]==user)
        {userIndex=i;
         found=true;
         break;}
    }

    if (found)
        {PrivateTo.splice(userIndex,1);
         arrangeUserNameHtml();
         mesInput.focus(); }

    arrangeMsgBoxSize();

   }


   function showUserInfoMessages(userArr,message)
   {//shows quit and join messages about users
        var i;
        for  (i=0;i<userArr.length;i++)
        {
            appendInfoMessage (userArr[i] + message);
        }
   }


    function timeHtml(sdate)
    {
        sday = sdate.slice(0,10);
        html = '<span class="date">';
        showDayCheck = document.getElementsByName('showDay')[0];

        if (showDayCheck.checked)
            {style = 'style="display:inline;"';}
        else
            {style = 'style="display:none;"' ;}

        html += '<span ' + style + ' id="day" name="day" class="date">'+ sday + '</span> ';

        showTimeCheck = document.getElementsByName('showTime')[0];
        if (showTimeCheck.checked)
            {style = 'style="display:inline;"';}
        else
            {style = 'style="display:none;"' ;}

        stime = sdate.slice(11,19);
        html += '<span ' + style  + ' id ="time" name="time">'+ stime + '</span>';
        html += '</span>';
        return html;
    }


   function appendInfoMessage( message,id)
   {
        newDiv=document.createElement('div');
        if (id != null){
        	newDiv.setAttribute("id",id);
        	timee = timeHtml( msgId);
        }

        else{
        	timee =timeHtml( date_now());
        }
        newDiv.innerHTML= timee + '</span><span class="info">' + message + '</span>';
        messagesDiv.appendChild(newDiv);
        messagesScrollToBottom();
        playSound();
   }

    function date_now()
    {
        var d=new Date();

        years =d.getFullYear();
        months = zeroFormat(d.getMonth()+ 1 ,2);
        days = zeroFormat(d.getDate(),2);
        hours = zeroFormat(d.getHours(),2);
        minutes = zeroFormat(d.getMinutes(),2);
        secs = zeroFormat(d.getSeconds(),2);
        nowStr= years + "-" +  months + "-" + days + " " +  hours + ":"  + minutes + ":" + secs;
        return nowStr;
    }

    function zeroFormat(num,numOfZeros)
    {//prepends necessary zeros to num to reach numOfZeros .
     //e.g. : num= 17 , numOfZeros = 6 ; result "000017"
     numStr=String(num);
     zerosToAdd=numOfZeros - numStr.length;
     var i;
     for ( i=0;i < zerosToAdd;i++)
     {
      numStr = "0" + numStr;
     }
     return numStr;

    }

   function diffElements(arr1,arr2)
    {
    //  returns:  elements that don't exist in Arr1 And exist in Arr2
        diffArr=new Array();
        var i;
        for  (i=0;i<arr2.length;i++)
        {
            if (!arrFind(arr1,arr2[i]))
            {
                diffArr.push(arr2[i]);
            }
        }
         return diffArr;

    }


    function arrFind(arr,value)
    {//returns true if value is found in array else false
        var i;
        for  (i=0;i<arr.length;i++)
        {
            if (arr[i]==value)
                {return true;}
        }
        return false;
    }



    function appendMessage(msgId,username,data,usernamestyle,private_to)
    {

        div=document.createElement('div');
        div.setAttribute("id",msgId)
		listUsername = username;
        if (private_to != null)
        {
            listUsername = username + " to " + private_to;
        }

        html = timeHtml( msgId);
        html += '<span class="username ' + usernamestyle  + '">'+  listUsername + "</span>: " + data + "\n";
        div.innerHTML = html;

        messagesDiv.appendChild(div);

        //noteD=document.getElementById("Note");
        //noteD.innerHTML=messagesD.scrollHeight;
        leftP = document.getElementById("LeftPanel");
        //leftP.scrollTop = messagesDiv.scrollHeight;
        //messagesDiv.scrollTop = messagesDiv.scrollHeight * 2;
        messagesScrollToBottom()
        if (username != myUsername)
          {playSound();}
    }


    function messagesScrollToBottom()
    {

    messagesDiv.scrollTop = messagesDiv.scrollHeight ;

    }


    function messagesScrollToTop()
    {
        leftP = document.getElementById("LeftPanel");
        if (leftP)
            {leftP.scrollTop = "0";}

    }

    function loadSound()

    {
        var enableSoundNotify = document.getElementsByName('enableSoundNotify')[0];

        if (enableSoundNotify.checked)
        {
            try {
                 soundManager.createSound('notifySound','files/sounds/notify.mp3');
                 soundManager.setVolume('notifySound',100);

                }
            catch (e) {
                inAlert("Your browser does not support playing sounds. Disabling this feature.");
                enableSoundNotify.checked=false;
                }
         }
    }


    function playSound()
    {
        var enableSoundNotify = document.getElementsByName('enableSoundNotify')[0];
        if (enableSoundNotify.checked)
        {
            try {
                  soundManager.play('notifySound');
                }
            catch (e) {
                inAlert("Your browser does not support playing sounds. Disabling this feature.");
                enableSoundNotify.checked=false;
                }
         }
     }



     function lostFocus()
     {
        isFocused=false;
     }

     function gotFocus()
     {
        isFocused=true;
        document.title = docTitle ;
        unseenMsgCount=0;
     }

    function docLoad()
    {
         loadUserStyle();
         loadWindowTitle();
         if (window.ActiveXObject)
         {   ie_compatible = true;
             xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
         }
         else if  (document.implementation && document.implementation.createDocument)
         {  firefox_compatible = true; }

         else
         {   not_supported=true;}
        initVars();
        arrangeRightPanelWidth();
        getMessages();

        mesInput.focus();

    }


    function initVars()
     {
       messagesDiv=document.getElementById("messages");
       leftPanelD=document.getElementById("LeftPanel");
        mesInput=document.getElementById("message");
        usernameTd = document.getElementById('UserName');
        menuIds = ['LogMenu','UsersMenu', 'SmileysMenu' ,'PreferencesMenu'];
        menusArray = new Array();

         for (i=0 ; i < menuIds.length ; i++)
          {
            el = document.getElementById( menuIds[i]);
            menusArray.push(el);
          }
     }



function insertText(input, insTexte)
    {

    startTag = '';
    endTag = '';


         if (input.createTextRange)
         {
          var text;
          input.focus(input.caretPos);
          input.caretPos = document.selection.createRange().duplicate();
          if(input.caretPos.text.length>0)
          {
           input.caretPos.text = startTag + input.caretPos.text + endTag;
          }
          else
          {
           input.caretPos.text = startTag + " " + insTexte + " " + endTag;
          }
         }
         else input.value += startTag + " " + insTexte + " " + endTag;
    }


    function swapDivDisplay(sender , divId)
    {

        div=document.getElementById(divId);
        if (div.style.display=="none")
            { display = "block";
                sender.className = "toolButton_pressed toolButton ";}
        else
            { display = "none";
             sender.className = "toolButton" }


        div.style.display = display;
        saveDisplayState(divId, display);
        arrangeRightPanelWidth();

    }





    function arrangeRightPanelWidth()
    {

    	
      menusVisible = false;
      for (i=0 ; i < menusArray.length ; i++)
      {
        el = menusArray[i] ;
        if (el.style.display != 'none')
        {menusVisible = true;
         break;}
      }
      rPanel = document.getElementById("RightPanel");
      if (menusVisible)
      {

       messagesDiv.style.right="280px";
       messagesDiv.style.width = parseInt(document.documentElement.clientWidth)-300 + 'px';
       rPanel.style.width="240px";
      }
      else
      {
        messagesDiv.style.right="70px";
        messagesDiv.style.width = parseInt(document.documentElement.clientWidth)-100 + 'px';
        rPanel.style.width="70px";
      }

        messagesDiv.style.height = parseInt(document.documentElement.clientHeight)-130 + 'px';
        arrangeMsgBoxSize();
    }


    function arrangeMsgBoxSize()
    {

        mesInput.style.width=parseInt(document.documentElement.clientWidth)-usernameTd.offsetWidth - 135 + 'px';
    }


    function loadCheckStates()
    {

     loadCheckState("enableSoundNotify");
     loadCheckState("showTime" );
     loadCheckState("showDay" );
     loadCheckState("showSmileys" );
     loadSmileysStyle();


    }


    function loadCheckState(name  )
    {
    elems = document.getElementsByName(name);
    if (elems.length > 0)
       {
           cookieName = name + '_checked';
           check = elems[0];
           value = Get_Cookie (cookieName );
           if (value != null)
           {
               if (value == 't')
               {
                  check.checked = true;
               }
               else
               {
                  check.checked = false;
               }
           }
           saveCheckState(check );
       }
    }


    function saveCheckState(elem )
    {
           cookieName = elem.name + '_checked';
           if (elem.checked)
              {Set_Cookie(cookieName, 't' , 180);}
           else
              {Set_Cookie(cookieName, 'f' , 180);}
    }



    function saveDisplayState(elemId , value)
    {
    cookieName= elemId + 'Display';
    Set_Cookie(cookieName, value , 180);
    }


    function loadMenusDisplayStates()
    {
        loadDisplayState("UsersMenu");
        loadDisplayState("SmileysMenu");
        loadDisplayState("PreferencesMenu");
        loadDisplayState("LogMenu");
    }


    function loadDisplayState(elemId)
    {
    cookieName= elemId + 'Display';
    changeDisplay= Get_Cookie(cookieName);
    if (changeDisplay)
        {
        elem=document.getElementById(elemId);
        if (elem)
            {elem.style.display=changeDisplay;
            arrangeRightPanelWidth();
            saveDisplayState(elemId, changeDisplay);

            menuButton = document.getElementById(elemId + 'Button');
            if (menuButton)
                {
                if (changeDisplay == 'none')
                   { menuButton.className= "toolButton"; }
                else
                   { menuButton.className= "toolButton toolButton_pressed"; }
                }
            }

        }


    }


    function loadUserStyle()
    {
      style= Get_Cookie('stylesheet');

      if (style != 'null')
      {userChosenStyle = style;
       changeStyle(userChosenStyle);}
    }


    function updateCssStyleSelect()
    {

    if (userChosenStyle != null)
        {style= userChosenStyle;}
    else
        {style = defaultStylesheet;}


    elem = document.getElementById("cssStyleSelect");
    if (elem != null)
    {
        options = elem.options;
        for (i=0 ; i < elem.length ; i++ )
              {  opt = options[i];
                 if (opt.text == style)
                      {elem.selectedIndex = i;
                       break; }
              }
     }
     else
     {
        alert("Cant get element with id cssStyleSel");
     }


    }


    function selectStyleChanged(elem)
    {

    style = elem.options [ elem.selectedIndex].value ;
    changeStyle(style);

    }


    function changeStyle(stylesheet)
    {
    	
    ustyle=document.getElementById('userStyle');
    
    if (stylesheet != 'default')
        {styleHref =  'files/styles/' + stylesheet + '.css';
        
        if (ustyle != null)
        	{ 	ustyle.href = styleHref;  }
        }
       else
       {
         
    	   if (ustyle != null)	{ustyle.href = '';}
       }
        Set_Cookie('stylesheet' , stylesheet , 180);
    }



    function Get_Cookie( check_name ) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split( ';' );
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f

        for ( i = 0; i < a_all_cookies.length; i++ )
        {
            // now we'll split apart each name=value pair
            a_temp_cookie = a_all_cookies[i].split( '=' );
            // and trim left/right whitespace while we're at it
            cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

            // if the extracted name matches passed check_name
            if ( cookie_name == check_name )
            {
                b_cookie_found = true;
                cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
                return cookie_value;
                break;
            }
            a_temp_cookie = null;
            cookie_name = '';
        }
        if ( !b_cookie_found )
        {
            return null;
        }
    }



    function Set_Cookie( name, value, expires, path, domain, secure )
    {
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime( today.getTime() );

    /*
    if the expires variable is set, make the correct
    expires time, the current script below will set
    it for x number of days, to make it for hours,
    delete * 24, for minutes, delete * 60 * 24
    */
    if ( expires )
        {expires = expires * 1000 * 60 * 60 * 24;}
    var expires_date = new Date( today.getTime() + (expires) );

    document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
    }



    function switchMenuTab(titleId , tabId , menuId)
    {

        menu = document.getElementById(menuId);
        aHrefs = menu.getElementsByTagName( 'a' );

        for (i=0; i<aHrefs.length; i++)

        {   a = aHrefs[i];
            id = a.id;

            if (id.substring( id.length - 5 , id.length) == 'Title')
            {
                if (id != titleId)
                {a.className = "tablabel tablabel_inactive";  }
                else
                {a.className = "tablabel tablabel_active";}
            }
        }

        divs = menu.getElementsByTagName( 'div' );
        for (i=0; i< divs.length ; i++)
        {
            div = divs[i];
            if (div.id.substring( div.id.length - 4,div.id.length) == '_tab')
                {
                if (div.id != tabId)
                    {
                    div.className="tab tab_inactive";

                    }
                else
                    {

                      div.className="tab tab_active";
                    }
                }

        }
    }


    function displayByName(name , state)
    {
            if (state)
            {setDisplayByName(name , 'inline') ;}
            else
            {setDisplayByName(name , 'none');}
    }


    function setDisplayByName(name , display)
    {

    elems = document.getElementsByName(name);
    for (i=0; i < elems.length; i++)
        {
            elem= elems[i];
            elem.style.display =display;
        }

    }




    function loadSmileysStyle()
    {
        showSm = document.getElementById("showSmileys").checked;
        setSmileysStyle(showSm);

    }

    function setSmileysStyle(showSm)

    {
        for (i=0; i< document.styleSheets.length ; i++)

        {
            sheet = document.styleSheets[i];
            var rules = new Array();

            if (sheet.cssRules)
                rules = sheet.cssRules
            else if (sheet.rules)
                rules = sheet.rules


            if (showSm)
            {
               rules[0].style.display = "inline";
               rules[1].style.display = "none";
            }
            else
            {
               rules[1].style.display = "inline";
               rules[0].style.display = "none";
            }
        }

    }



    function setWinTitle(val)
    {
     docTitle = val;
    }

    function loadWindowTitle()
    {
        t= Get_Cookie("windowTitleInput");
        if (t)
        {
            setWindowTitleInputVal( t);
            docTitle = t;
            document.title= t;

        }
        else
        {
            setWindowTitleInputVal(document.title);

        }
    }

    function setWindowTitleInputVal(val)
        {elem= document.getElementById("windowTitleInput");
            if (elem)
            {elem.value=val;}
        }


    function saveText(elem)
    {

        Set_Cookie(elem.id , elem.value , 180);

    }


var newwindow;
function popWin(url)
{
    newwindow=window.open(url,'achat' , 'menubar=0,toolbar=0,status=0,resizable=0,width=550,height=550');
    if (window.focus) {newwindow.focus()}
}

function showAllMes()
    {
    elemm= document.getElementById("messages");
    divm = elemm.getElementsByTagName( 'div' );
    for (i=0; i< divm.length ; i++)
                {
                    div = divm[i];
                    div.style.display = "block";
                }
    }
function hideAllMes()
    {
    elemm= document.getElementById("messages");
    divm = elemm.getElementsByTagName( 'div' );
    for (i=0; i< divm.length ; i++)
            {
                div = divm[i];
                div.style.display = "none";
            }
    }

function nothing(){}



function showAllSmileys(){
smilDiv = document.getElementById("SmileysMenu");
imgs= smilDiv.getElementsByTagName('img');
  for (i=0; i< imgs.length ; i++)
     {
            img = imgs[i];
            src = img.getAttribute('src');
            if (! src ){
			img.setAttribute('src', img.getAttribute('xsrc') ) ;
	 		}
	}

 document.getElementById("showall_smileys").style.display="none";
 document.getElementById("SmileysMenu").style.height="200px";

}

function setBusy(){

	txt=document.getElementById("BusyButtonText").innerHTML;
	if (txt == "i am busy"){
	postAchatMessage('busy',myUsername+" is busy");
	}else{
	postAchatMessage('notbusy',myUsername+" is back to chat");
	}
}


function inArray(val,arr){
 for (i=0; i< arr.length ; i++)
     {
            if (val==arr[i]){
            	return true;
            }
	  }
 return false;

}

