var ManagerSms={

    
    registerListener: function(){
        setTimeout("ManagerSms.Ping();", pingFrequency); //2.5 sec x ping
    },
    
    registerEvent: function(){
        var fLogout= $("LinkLogout");
        if ( fLogout!=null)
            Event.observe(fLogout, 'click', function() {ManagerSms.Logout();});
    },
    unregisterListener: function(){
        setTimeout("ManagerSms.Ping();", 0); 
        this.UserName=null;
        if (debugMode) window.status='Stop';
    },
    
    setUserName: function(pUser,pKC){
        if (pUser!=null) pUser=pUser.toLowerCase();
        this.UserName=pUser;
        this.KC=pKC;
        
    },

    init: function(){
    	this.registerListener();
    	this.registerEvent();
    	
    	
    },
    
    
    Logout: function(mode){
            
            if (!ManagerSms.KC || !ManagerSms.UserName) {
                //Martellata x chrome
                var f=document.form_Logout;
                if (f!=null) f.submit();
                    
            }
            
            if (mode=="1"){
                ManagerSms.unregisterListener();
                window.document.location.href=window.document.location.href;
                //Martellata x chrome
                var f=document.form_Logout;
                if (f!=null) f.submit();
                return;    
            }
            
            var us=ManagerSms.UserName+"";
            var qPing="call=LogUTSL&username="+us+"&kc="+this.KC;
            
            var xhConn = new XHConn();      
            xhConn.connect(pingTo, "POST", qPing,function(xh) {
              var respSTR=xh.responseText;
                respSTR=respSTR.replace(/\n/g,'');
                respSTR=respSTR.replace(/\r/g,'');
                
                var isInValid = (respSTR.indexOf('invalid')!=-1)  || 
                                (respSTR.indexOf('banned')!=-1) || 
                                (respSTR.indexOf('undefined')!=-1)  || 
                                respSTR==''; // errore php
                
                if(!isInValid) {
                    
                    
                    ManagerSms.unregisterListener();
                    ManagerSms.setCookie("LOGOUT_"+us.toLowerCase(),"1",0,pingFrequency*2); 
                    
                    window.document.location.href="/index.php";
                    
                    //Martellata x chrome
                    var f=document.form_Logout;
                    if (f!=null) f.submit();
                    
                    
                    
                }else{
                    alert("Errore! "+respSTR);
                }
                
            });
            
    },
   
   
   
   CheckLogout: function(){
        return ManagerSms.getCookie("LOGOUT_"+this.UserName.toLowerCase());
   },
   
   
    Ping: function(){
 
 
        if (this.UserName && this.KC){
        
            var iLg=ManagerSms.CheckLogout();
            if (iLg!=""){
                ManagerSms.Logout(iLg);
                return;
            }
            if (debugSms) window.status='ping';
            var pageHome=(window.location.href=="http://www.spritzlandia.it/" || window.location.href=="http://www.spritzlandia.it/index.php" || window.location.href=="http://localhost/");
            var qPing="call=PingSL&username="+this.UserName+"&kc="+this.KC;
            if (pageHome) qPing+="&RLIDP=1";
            var xhConn = new XHConn();      
          
            xhConn.connect(pingTo, "POST", qPing,function(xh) {
                var respSTR=xh.responseText;
                respSTR=respSTR.replace(/\n/g,'');
                respSTR=respSTR.replace(/\r/g,'');
                
                var isInValid = (respSTR.indexOf('invalid')!=-1)  || 
                                (respSTR.indexOf('banned')!=-1) || 
                                (respSTR.indexOf('undefined')!=-1)  || 
                                respSTR==''; // errore php
                
                if(!isInValid) {
                        //OK 
                        try {
                           var rispObj=respSTR.parseJSON(); 
                            if (debugSms) alert(xh.responseText);
           
                           if (rispObj!=false){
                           
                               // if (debugSms) alert(xh.responseText);
                                
                                //Gestione risposte
                                if (rispObj.RP!=null){
                                    var listP=rispObj.RP;
                                    for(var i=0;i<rispObj.RP.length;i++){
                                        var userRP=listP[i];
                                        if (debugSms) window.status='ping>'+userRP;
                                        ManagerSms.openCharUser(userRP);
                                    }
                                }
                                
                                //Gestione amici
                                if (rispObj.SF!=null){
                                    var listF=rispObj.SF;
                                    for(var a=0;a<rispObj.SF.length;a++){
                                        ManagerSms.checkFriend(listF[a]);
                                    }
                                }
                                
                                //Gestione piazza
                                if (window.location.href.indexOf("page=")==-1 || window.location.href.indexOf("index.php?page=1")!=-1){
                                    //Agg qui msg
                                }
                                
                           }else{
                                if (debugOnlyErrorSms) alert(xh.responseText);
                           }
                           
                           //Attivo il ping se è ok
                           ManagerSms.registerListener();
                        } catch(e){
                            if (debugOnlyErrorSms)  alert(e);
                        }
                }//Valid
                else{
                    if (debugOnlyErrorSms) alert(respSTR);
        
                }
            }
          );//Connect
     
          
        }else{
            //Ricontrollo tra 1/2 secondo
            setTimeout("ManagerSms.Ping();", 500); 
        }
    	
    	
    },//Ping: function
   
  
   setCookie: function(c_name,value,expiredays,mssec)
    {
        var exdate=new Date();
        if (expiredays!=0)
            exdate.setDate(exdate.getDate()+expiredays);
        if (mssec!=0)
            exdate.setTime(exdate.getTime()+mssec);
        
        document.cookie=c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString())+"; path=/";
    },
    
    getCookie: function(c_name)
    {
    if (document.cookie.length>0)
      {
      c_start=document.cookie.indexOf(c_name + "=");
      if (c_start!=-1)
        { 
        c_start=c_start + c_name.length+1; 
        c_end=document.cookie.indexOf(";",c_start);
        if (c_end==-1) c_end=document.cookie.length;
        return unescape(document.cookie.substring(c_start,c_end));
        } 
      }
        return "";
    },

     checkFriend:function(infoFriend){
        var ef='friend_'+infoFriend.I;
        var online=infoFriend.O;
        var objectRow=$(ef);
        
        if (online){
            if (objectRow==null){
                //Inserisce amico
                try{
                  ManagerSms.addFriendOnLine("friend",ef,infoFriend);
                }catch(ex){
                
                }
            }
        }else{
            //Remove
            if (objectRow!=null){
                new Effect.Puff(objectRow);
               
               var d = document.getElementById('friend');
               var olddiv = document.getElementById(ef);
               if (d!=null && olddiv!=null)
                    d.removeChild(olddiv);
               
            }
        }
        
        
     },
     
     addFriendOnLine:function(parentObj,idEl,info){
        var cMpz=$(parentObj);
		if (cMpz==null) return;
     
	    var cu=info.N;
		var winTitle=cu;
		if (winTitle.indexOf('.')!=-1)
		    winTitle=winTitle.replace(".","_");
		if (winTitle.indexOf(' ')!=-1)
            winTitle=winTitle.replace(" ","_");

        //Start row
        var 
        sHt='<table id="'+idEl+'" >';
        sHt+='<tr>';
    
        //Scrivi msg
        sHt+='<td>';
        sHt+='<a href="#" onClick="MyWindow=window.open(\'/chat.php?dest='+cu+'\' ,\''+winTitle+'\',\'toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=450,height=500,left=100,top=100\'); return false;">';
		sHt+='<img src="/images/shouts.gif" alt="Scrivi a '+cu+'" border="0" />';
		sHt+='</a>';
        sHt+='</td>';
        
        
        
        //Profilo
        sHt+='<td>';
        sHt+='<A href="/profilo/'+cu+'"> ';
        sHt+='<span class="text1">';
        sHt+=cu;
        if (cu == 'erny83pd') sHt+=' <sup>Webmaster</sup>';
    		if (cu == 'querela')  sHt+=' <sup>Developer</sup>';

        sHt+='</span>';
        sHt+='</a>';
        sHt+='</td>';

        //Blog                
        sHt+='<td>';
        if (info.B>0)				
			sHt+=' <a href="/blog/'+cu+'" target="_blank"><img src="/images/blog.gif" border="0" alt="'+cu+' Blog"></a>';
        sHt+='</td>';
        
        //Fine row
        sHt+='</tr>';
        
        //Row slogan
        if (info.SL!='-'){
            sHt+='<tr><td></td><td colspan="2"><span class="slogan"><i>';
            sHt+=info.SL;
            sHt+='</i></span></td></tr>';
        }
    
        sHt+='</table>';

		
	//	txt=txt.replace('\\\"','"');
		
		var fc=cMpz.firstChild;
		if  (fc!=null){
		     new Insertion.Before(fc, sHt);
		     new Effect.Pulsate($(idEl));
		}else{
		    if (isIE>0){
		        new Insertion.Top(cMpz,sHt);
		    }else{
		        new Insertion.Before(cMpz,sHt);
		    }
		    new Effect.Pulsate($(idEl));
		}
		
		
			
     },
     
   
    CheckOpenCharUser:function(nameUser,winTitle){
    
        var existW=false;
        if(window[winTitle]){
            existW=true;
        }
        
        if (existW==false){
            var exdate=new Date();
            var ic= ManagerSms.getCookie("RP_USER_"+winTitle);
            if (ic==""){
                ManagerSms.setCookie("RP_USER_"+winTitle,exdate.toGMTString(),0,6000); 
            }else{
               existW=true;
            }
        }
        return existW;
           
    },
   
   openCharUser: function(nameUser){
        try{
            if (debugSms) window.status='OpenChat>'+nameUser;
            var pagename = "/chat.php?dest="+nameUser;
            var openChat=false;
            
            //TFix replace point
            var winTitle=nameUser;
            if (winTitle.indexOf('.')!=-1)
                winTitle=winTitle.replace(".","_");
            
            if (winTitle.indexOf(' ')!=-1)
                winTitle=winTitle.replace(" ","_");
            
            openChat=ManagerSms.CheckOpenCharUser(nameUser,winTitle);
            
            if (openChat==false){
                var opt='toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=450,height=500,left=350,top=200,location';
			    if(!window.open(pagename,winTitle,opt)) {
			        window.status=nameUser + " ti ha invitato un messaggio disattiva il blocco popup per riceverlo";
			        //alert(nameUser + " ti ha invitato un messaggio disattiva il blocco popup per riceverlo");
			    }else{
			        //Setto i msg letti
			        var qSetRead="call=SetMsgReaded&username="+this.UserName+"&kc="+this.KC+"&D="+nameUser;
                    var xhConnInt = new XHConn();      
                    xhConnInt.connect(pingTo, "POST", qSetRead,function(xh) {
                    
                    });
                    
			    }
			}
        }catch(e){
            if (debugSms) InMyCode.ManageEx(e);
        }
   }//manageResponseFail

};

function initMCSMS(){
  if (document.getElementById && document.createElement && document.body.appendChild) {
    ManagerSms.init();
  }
}

addLoadEvent(initMCSMS);
