/*************************************************************
 *                                                           *
 *   Created by Tamas Manhertz (PYLON)/Manhertz-Pylon Ltd.   *
 *            All rights reserved. 2010.                     *
 *                                                           *
 *************************************************************/
/*************************************************************
 *    #DEP: DOMComponent, singletons                         *
 *************************************************************/
/*************************************************************
 *  JSO Object:  LogonHandler                                *
 *        Type:  singleton                                   *
 *                                                           *
 * Description: Javascript logon handler object              *
 *    It provides client sides functions for user logon/out  *
 *   and informations.                                       *
 *                                                           *
 *                                                           *
 *************************************************************/

jso_LogonHandler = new pDOMComponent( "jso_LogonHandler", "jso_LogonHandler" );
jso_LogonHandler.extend(
 {
   // ***************************************************
   //                  PROPERTIES
   // ***************************************************

     /*
      *    SYSTEM_VAR variables
      *
      *   @type: string
      *     - SYSTEM_VAR_<variable names>: received from server (database fields)
      */
        U_USERNAME : "",
        U_FIRSTNAME : "",
        U_LASTNAME : "",
        U_EMAIL : "",
        U_LASTLOGIN : "",
        U_IPADDR : "",
        U_CREATED : "",
       
   // ***************************************************
   //                  PRIVATE PROPERTIES
   // ***************************************************
           /**
            *  It gives a simple security. It will be concatenated
            * with the password together before the SHA1 coding.
            * @type: string
            */
       _sRandomString : "",
           /**
            *  Coded password to send
            * @type: string
            */
       _sCodedPassword : "",
           /**
            *  True if a user is logged on
            * @type: boolean
            */
       _bLoggedIn : false,
           /**
            *  True if a logon request is in progress
            * @type: boolean
            */
       _bLogonInProgress : false,
           /**
            *  In case of a logoff, which webpage should we go?
            * @type: boolean
            */
       _sLogoffURL : null,
           /**
            *  If this variable is true, the object will look for the username in a cookie and sets it automatically
            * @type: boolean
            */
       _bRememberMe : false,
           /**
            *  The fn_MsgBox handler object of the "Please wait" message box
            * @type: object (fn_MsgBox)
            */
       _oPWait_MsgBox : null,
           /**
            *  The fn_MsgBox handler object of the "Bad username or password" message box
            * @type: object (fn_MsgBox)
            */
       _oBadPW_MsgBox : null,
           /**
            *  A default error message when the user hasn't specified the username. It will be overwritten
            * by the server if it is specified in the config XML file.
            * @type: string
            */
       _sEmptyUsernameText : "Please specifiy a username!",
   // ***************************************************
   //             SERVER ANSWER PROPERTIES
   // ***************************************************
           /**
            *  Server answer.
            * @type: object
            */
       _oLogonInfo : null,
   // ***************************************************
   //                  CONFIG PROPERTIES
   // ***************************************************
           /**
            *  Default showing time of the message time
            * @type: integer
            */
       iLOGON_HANDLER_DEFAULT_MSGBOX_SHOW_TIME : 30,
           /**
            *  Default fading time upon logon or logoff (mSec)
            * @type: integer
            */
       iLOGON_HANDLER_DEFAULT_LOGON_PANEL_FADE_TIME : 5,
   // ***************************************************
   //                  PRIVATE  METHODS
   // ***************************************************
           /**
            * Component ID string.
            */
       _getIDString : function ()
        {
           return "JSO User logon/logoff object.";
        },

           /**
            * Shows/hides the logon-logged on panels in HTML code.
            */
       _setPanels : function ()
        {
            this._setPanelsOff();
            this._setPanelsOn();
        },

           /**
            * Hides the logon-logged on panels in HTML code.
            */
       _setPanelsOff : function ()
        {
            var _oDOMObject;
            if (this._bLoggedIn)
             {
               if (_oDOMObject = document.getElementById( this._sLogonName+"_logonform" ))
                  _oDOMObject.fadeOut( this.iLOGON_HANDLER_DEFAULT_LOGON_PANEL_FADE_TIME );
             }
            else
             {
               if (_oDOMObject = document.getElementById( this._sLogonName+"_loggedon" ))
                  _oDOMObject.fadeOut( this.iLOGON_HANDLER_DEFAULT_LOGON_PANEL_FADE_TIME );
             }
        },
           /**
            * Shows the current logon-logged on panels in HTML code.
            */
       _setPanelsOn : function ()
        {
            var _oDOMObject;
            if (this._bLoggedIn)
             {
               if (_oDOMObject = document.getElementById( this._sLogonName+"_loggedon" ))
                  _oDOMObject.fadeIn( this.iLOGON_HANDLER_DEFAULT_LOGON_PANEL_FADE_TIME );
             }
            else
             {
               if (_oDOMObject = document.getElementById( this._sLogonName+"_logonform" ))
                  _oDOMObject.fadeIn( this.iLOGON_HANDLER_DEFAULT_LOGON_PANEL_FADE_TIME );
             }
        },

           /**
            *   setFocus()
            *        sets the focus to the specified element of logon form
            */
       _setFocus : function ( sElement )
        {
			if (this._iFocusTimer)
			{
				clearTimeout(this._iFocusTimer);
				delete (this._iFocusTimer);
			}
			this._iFocusTimer = setTimeout( "var _oDOMObject = document.getElementById( '"+this._sLogonName+"_input_"+sElement+"' ); if (_oDOMObject) try {_oDOMObject.focus();} catch (ex) {}", 1 );
        },

   // ***************************************************
   //                   PUBLIC METHODS
   // ***************************************************
           /**
            *   Initializes the LogonHandler object:
            *       - set the basic variables,
            */
       init : function ( sLogonName, sPleaseWaitText, sEmptyUsernameText, bRememberMe, bLoggedIn )
        {
             /*  stores the necessery data  */
           this._sLogonName = sLogonName;
           if ((!document.getElementById( this._sLogonName+"_input_username" )) ||
               (!document.getElementById( this._sLogonName+"_input_password" )))
               throw Error("No username and password DOM Elements have been specified for Logon Handler.");

           if (( sEmptyUsernameText ) && (typeof(sEmptyUsernameText) == "string") && (sEmptyUsernameText.length>2))
                this._sEmptyUsernameText = sEmptyUsernameText;

           if ((bRememberMe === true) || (bRememberMe === false))
                this._bRememberMe = bRememberMe;
           
             /*  checking and setting a message box panel handled by DOMHandler - Bad Password Panel */
           if (typeof(pMsgBox))
            {
                    /*   Creates the "please wait" message box  */
                this._oPWait_MsgBox = new pMsgBox( this.sName+'_MsgBox', this.sName+'_MsgBox' );
                this._oPWait_MsgBox.init( 'PleaseWait' );
                this._oPWait_MsgBox.setText( sPleaseWaitText+"" );
                this._oPWait_MsgBox.setProgressBar( true );
                this._oPWait_MsgBox.setHideOnClick( false );

                    /*   Creates the "bad username or password" message box  */
                this._oBadPW_MsgBox = new pMsgBox( this.sName+'_MsgBox', this.sName+'_MsgBox' );
                this._oBadPW_MsgBox.init( 'BadPW' );
                this._oBadPW_MsgBox.setText( "" );
                this._oBadPW_MsgBox.setHideOnClick( true );
            }
           else
                syLog ("LH: no MsgBox class object, can't create informational message boxes." );

           this._bLoggedIn = bLoggedIn || false;
           this._bLogonInProgress = false;
           this.U_USERNAME = "";

              /*  Setting KeyPress event for on the two input fields  */
           this._setEventHandler( document.getElementById( this._sLogonName+"_input_username" ), "onkeydown", this.onKey );
           this._setEventHandler( document.getElementById( this._sLogonName+"_input_password" ), "onkeydown", this.onKey );

              /*  sets the event of the logon button if it exists  */
           var _oDOMButton;
           if (_oDOMButton = document.getElementById( this._sLogonName+"_button_logon" )) 
                this._setEventHandler( _oDOMButton, "onclick", this.doLogon );

              /*  sets the event of the logoff button if it exists  */
           if (_oDOMButton = document.getElementById( this._sLogonName+"_button_logoff" )) 
                this._setEventHandler( _oDOMButton, "onclick", this.doLogoff );

             /*  setting up DOMHandler for logon panels - if they exist */
           if (document.getElementById( this._sLogonName+"_logonform" ))
            {
               jso_DOMHandler.set( this._sLogonName+"_logonform" );
               jso_DOMHandler.hide( this._sLogonName+"_logonform" );
            }
           if (document.getElementById( this._sLogonName+"_loggedon" ))
            {
               jso_DOMHandler.set( this._sLogonName+"_loggedon" );
               jso_DOMHandler.hide( this._sLogonName+"_loggedon" );
            }


             /*  must be displayed the current panel in HTML code  */
           this._setPanels();

             /*  if enabled and the cookie has a username, it will be set  */
           if (this._bRememberMe)
            {
               if (document.cookie.indexOf("G3USER=")>-1)
                {
                    var _sCookieUsername = getCookie( 'G3USER' )+"";
                    document.getElementById( this._sLogonName+"_input_username" ).value = _sCookieUsername;
                    if (_sCookieUsername.length>0)
						this._setFocus( "password" );
                    else
						this._setFocus( "username" );
                }
               else
                    this._setFocus( "username" );
            }
           else
               setCookie( 'G3USER', '' );
        },


           /**
            *   _doLogon()
            *        initiates the user logon process, sending to the server
            */
       doLogon : function ()
        {
              /*  if a logon request is already in progress  */
            if ((this._bLogonInProgress) || (this._bLoggedIn))
                return false;

              /*  hideing the message box if it has been showed before  */
            if (this._oBadPW_MsgBox)
                this._oBadPW_MsgBox.hide();

              /*  getting username and password from the input fields  */
            _oDOMUsername = document.getElementById( this._sLogonName+"_input_username" );
            _oDOMPassword = document.getElementById( this._sLogonName+"_input_password" );
            if (
                (_oDOMUsername) &&
                (_oDOMPassword)
               )
             {
                  /*  to remember the username and coding the password  */
                this.U_USERNAME = _oDOMUsername.value+"";
                _sCodedPassword = sha.calcSHA1( this._sRandomString + _oDOMPassword.value+"" );
                if (this.U_USERNAME.length == 0)
                 {
                    if (this._oBadPW_MsgBox)
                     {
                        this._oBadPW_MsgBox.setText( this._sEmptyUsernameText);
                        this._oBadPW_MsgBox.show( this.iLOGON_HANDLER_DEFAULT_MSGBOX_SHOW_TIME );
                     }
                    else
                        alert( this._sEmptyUsernameText );
                    return false;
                 }
                
                  /*  calling the server doUserLogon procedure  */
                this._call( "doUserLogon", this.U_USERNAME, _sCodedPassword );
                this._bLogonInProgress = true;
                if (this._oPWait_MsgBox) this._oPWait_MsgBox.show();
             }
            return true;
        },
           /**
            *   doLogoff()
            *        initiates the user logoff process
            */
       doLogoff : function ()
        {
              /*  calling the server Logoff process  */
           this._call( "doUserLogoff" );
           this._callRegisteredCallback( "Logoff" );

              /*  sets the status to not logged on and displaying the correct panel  */
           this._bLoggedIn = false;
           return true;
        },
           /**
            *   Enables or disables the "remember username" feature
            */
       setRememberMe : function ( bEnable )
        {
            this._bRememberMe = bEnable;
            if (!bEnable)
               setCookie( 'G3USER', '' );
        },

           /**
            *   setVar()
            *        sets the SYSTEM_VAR explicit
            */
       setVar : function ( sVarname, sValue )
        {
            this[sVarname] = sValue;
            if (!jso_Parameterizer)
             {
                syLog ("jso_Parameterizer object does not exists, cannot write the parameter "+sVarName );
                return false;
             }
            jso_Parameterizer.setVar( sVarname, sValue );
        },

           /**
            *   KeyPress event to detect the [ENTER] key on the username or password fields
            */
       onKey : function ( oEvent, oTarget )
        {
                /* ENTER */
            if (oEvent.keyCode == 13)
                this.doLogon();

                /* ESC - if it is possible to detect */
            if (oEvent.keyCode == 27)
             {
                if (this._oBadPW_MsgBox) this._oBadPW_MsgBox.hide();
                if (this._oPWait_MsgBox) this._oPWait_MsgBox.hide();
             }
            return true;
        },

           /**
            *   Server Response Processor:
            *     it checks the result for the logon-logoff procedure
            *     if it was successfully, it will also call the callback functions registered by other components
            */
       processServerData : function ( sDName )
        {
              /*  clear the password input field  */
            if (_oDOMPassword = document.getElementById( this._sLogonName+"_input_password" ))
                _oDOMPassword.value = "";

            switch (sDName)
             {
                case "_oLogonInfo":
                    this._bLogonInProgress = false;
                    if (this._oPWait_MsgBox) this._oPWait_MsgBox.hide();
                    switch (this._oLogonInfo.sEventType)
                     {
                        case "I":   /*  Logged In  */
                            syLog( "Successfull logon for user "+this.U_USERNAME+"." );
                            this._bLoggedIn = true;
                            this._sLogoffURL = this._oLogonInfo.sLogoffURL;
                            this._callRegisteredCallback( "Logon" );
                            if (this._oLogonInfo.sLogonURL)
                                window.location = this._oLogonInfo.sLogonURL;
                            else
                                this._setPanels();

                                /*  if enabled, it stores the username in the cookie  */
                            if (this._bRememberMe)
                                setCookie( 'G3USER', this.U_USERNAME, 999 );
                            break;

                        case "B":   /*  Bad Password  */
                            syLog( "Bad username or password was entered." );
                            if (this._oBadPW_MsgBox)
                             {
								this._oBadPW_MsgBox.setText( this._oLogonInfo.sMessage );
								this._oBadPW_MsgBox.show( (this._oLogonInfo.iShowTime ? this._oLogonInfo.iShowTime : this.iLOGON_HANDLER_DEFAULT_MSGBOX_SHOW_TIME ) );
								this._setFocus( "password" );
                             }
                            else
                               this.notifyUser( this._oLogonInfo.sMessage );
                            this._replaceSystemVar( "U_USERNAME" );
                            this._setPanels();
                            break;

                        default:
                        case "O":   /*  Logged Off  */
                            this._bLoggedIn = false;
                            this._callRegisteredCallback( "Logoff" );

                            if ((this._sLogoffURL) || (this._oLogonInfo.sLogoffURL))
                             {
                                if (this._sLogoffURL)
                                    window.location = this._sLogoffURL;
                                else
                                    window.location = this._oLogonInfo.sLogoffURL;
                                this._setPanelsOff();
                             }
                            else
                                this._setPanels();
                            break;
                     }
                    delete(this._oLogonInfo);
                    break;

                default:
                      /* in case of a logon, the server will send the SYSTEM_VARs by AJAX call */
                    this._replaceSystemVar( sDName );
                    break;
             }
        },
           /**
            *   Sends the log buffer to the server.
            */
       onServerError : function ( sMethodName )
        {
           syLog( "LH: server communication error at "+sMethodName );
           this._bLogonInProgress = false;
           if (this._oPWait_MsgBox) this._oPWait_MsgBox.hide();
           return;
        }
});

syLog("jso_LogonHandler object is created.", CONSTANTS.LOG_TYPE_DEBUG_INFO);
   // ***************************************************
   //                Construct statements
   // ***************************************************

