if( typeof( AdmeaDossier ) == 'undefined' ) AdmeaDossier = {};

AdmeaDossier.Session = function()
{
	// Private properties
	var _filled = false;
	
	var authorized = false;
	var username = AdmeaDossier.Locale.SessionAnonymous;
	var manageruri = '';
	var loginPanel = null;
	var loginWindow = null;
	var mode = 'none';
	var server = '';
	var databse = '';
	var saveSession = true;
	var sitetype = '';
	
	// Private methods
	function updateStatus( response, options )
	{
		try
		{
			var statusinfo = Ext.util.JSON.decode(response.responseText);
			
			authorized = statusinfo.authenticated;
			username = statusinfo.name;
			manageruri = statusinfo.manageruri;
			mode = statusinfo.mode;
			sitetype = statusinfo.sitetype;
			
			if( AdmeaDossier.Session.isManager() )
			{
				server = statusinfo.server;
				database = statusinfo.database;
			}
			
			AdmeaDossier.app.updateInterface();
		}
		catch (err) {
			Ext.MessageBox.alert('ERROR', 'Could not decode session information' );
			console.log( 'ERROR: ', err, '\n', 'Could not decode ', response.responseText );
		}
	};

	// Public
	return {

		isAuthorized : function()
		{
			return authorized;
		},
		
		getUsername : function()
		{
			return username;
		},
		
		getManagerUri : function()
		{
			return manageruri;
		},
		
		getMode : function()
		{
			return mode;
		},
		
		getDatabase : function()
		{
			return database;
		},
		
		getServer : function()
		{
			return server;
		},
		
		isManager : function()
		{
			return ( 'manager' == mode );
		},
		
		isDossier : function()
		{
			return ( 'site' == mode );
		},

		getSiteType : function()
		{
			return sitetype;
		},

		fill : function()
		{
			if( !_filled )
			{
				_filled = true;

				this.refresh();
			}
		},
		
		refresh : function()
		{
			Ext.Ajax.request({
					url: AdmeaDossier.getURLForMethod( 'sessionstatus' ),
					success: updateStatus
				});
		},
		
		showLogin : function()
		{
			// AdmeaDossier.app.loginPanel.show( 'toolBtnLogin' );
			// AdmeaDossier.app.loginPanel.findById( 'username' ).focus( true, 500 );
			
			loginPanel.show( 'toolBtnLogin' );
			loginPanel.findById( 'username' ).focus( true, 500 );
		},

		handleLoginResponse : function( form, action )
		{
			// AdmeaDossier.app.loginPanel.findById( 'password' ).setRawValue( '' );
			loginPanel.findById( 'password' ).setRawValue( '' );

			if( action.result.approved )
			{
				// AdmeaDossier.app.loginPanel.hide();
				loginPanel.hide();

				// AdmeaDossier.app.tree.getRootNode().reload();
				AdmeaDossier.NodeTree.getTree().getRootNode().reload();
				
				authorized = true;
				username = action.result.name;

				AdmeaDossier.Session.refresh();
				
				AdmeaDossier.app.updateInterface();
				AdmeaDossier.Content.reload();
			}
			else
				Ext.Msg.alert(
					AdmeaDossier.Locale.SessionLoginFailedTitle,
					action.result.message,
					// function() { AdmeaDossier.app.loginPanel.findById( 'password' ).focus( true ); }
					function() { loginPanel.findById( 'password' ).focus( true ); }
				);
				
				
		},

		confirmLogout : function()
		{
			Ext.Msg.show({
				title: AdmeaDossier.Locale.SessionConfirmLogoutTitle,
				msg:  AdmeaDossier.Locale.SessionConfirmLogoutMessage,
				buttons: Ext.Msg.OKCANCEL,
				fn: AdmeaDossier.Session.doLogout,
				animEl: 'btnLogout',
				icon: Ext.MessageBox.QUESTION
			});
		},

		doLogout: function(btn, text)
		{
			if (btn == 'ok')
			{
				if( AdmeaDossier.Session.isManager() )
				{
					document.location = 'logout.aspx';
				}
				else
				{
					// Basic request
					Ext.Ajax.request({
						url: AdmeaDossier.getURLForMethod( 'logout' ),
						success: function( response, options ) 
						{
							authorized = false;
							username = AdmeaDossier.Locale.SessionAnonymous;

							AdmeaDossier.NodeTree.getTree().getRootNode().select();
							AdmeaDossier.Content.nodeGetPage( 'source', null );
							AdmeaDossier.NodeTree.getTree().getRootNode().reload();
							AdmeaDossier.app.updateInterface();
						}
					});
				}
			}
		},
		
		requestPasswordReset: function( )
		{
			var userfield = loginPanel.findById( 'username' );
			
			if( userfield && userfield.validate() )
			{
				Ext.Ajax.request({
					url: AdmeaDossier.getURLForMethod( 'resetpassword' ),
					params: {
						username: userfield.getValue()
					},
					success: function( response, options )
					{
						try
						{
							var statusinfo = Ext.util.JSON.decode(response.responseText);
							
							// AdmeaDossier.app.loginPanel.hide();
							loginPanel.hide();
							
							Ext.MessageBox.alert( AdmeaDossier.Locale.SessionPasswordResetResponseTitle, statusinfo.message );			
						}
						catch (err) {
							Ext.MessageBox.alert('ERROR', 'Could not decode ' + stringData);
						}
					}
				});
			}
			else
				Ext.MessageBox.alert( 'Error', AdmeaDossier.Locale.SessionMissingUsername );
		},
		
		init : function()
		{
    		loginPanel = new Ext.Window( {
    			visible: false,
    			// contentEl: 'loginWindow',
    			title: AdmeaDossier.Locale.LoginWindowTitle,
    			width: 270,
    			modal: true,
    			closeAction: 'hide',
    			resizable: false,
    			// autoHeight: true,
    			// layout: 'fill',
    			items:
    			[
    				loginForm = new Ext.FormPanel( {
		    			labelWidth: 75,
		    			defaultType: 'textfield',
		    			frame: true,
		    			bodyStyle:'padding:5px 5px 0',
		    			keys: [{
							key: Ext.EventObject.ENTER,
							fn: function() { submitBtn.handler.call( submitBtn.scope ); }
							// scope : submitBtn
						}],
    					items:
  						[
   							{
								fieldLabel: AdmeaDossier.Locale.LoginUserName,
								id: 'username',
								vtype:'email',
								autoWidth: true,
								allowBlank: false,
				    			stateful: true,
				    			stateEvents: [ 'valid', 'blur' ],
				    			getState: function()
				    			{
				    				if( saveSession )
				    					return { value: this.getValue() };
				    				else
				    					return null;
				    			},
								applyState: function(state) { this.setValue(state.value); } 
							},
							{
								fieldLabel: AdmeaDossier.Locale.LoginPassword,
								id: 'password',
								autoWidth: true,
								inputType: 'password',
								allowBlank: false
							},
							new Ext.form.Checkbox( {
								boxLabel: AdmeaDossier.Locale.LoginRememberMe,
								id: 'rememberme',
								autoWidth: true,
								hideLabel: true,
								allowBlank: false,
								checked: true,
				    			stateful: true,
				    			stateEvents: [ 'check' ],
				    			getState: function() { return { value: this.getValue() }; },
								applyState: function(state)
								{
									saveSession = state.value;
									// this.value = state.value;
									if( this.rendered )
										this.setValue(state.value);
									// this.value = state.value;
									// Ext.getCmp( 'rememberme' ).setRawValue( state.value ); //setValue( state.value );
								},
								listeners: {
									'check': {
										fn: function( box, checkstate )
										{
											saveSession = checkstate;

											if( loginPanel )
												loginPanel.findById( 'username' ).validate();
										},
										scope: this
									}
								}
							} ),
							new Ext.Component( {
								xtype: 'box',
								autoEl: { tag: 'a', href: '#', onclick: 'AdmeaDossier.Session.requestPasswordReset(); return false;', html: AdmeaDossier.Locale.SessionRequestPassword+'<br />' }
							} ),
							new Ext.Component( {
								xtype: 'box',
								autoEl: {
									tag: 'a',
									href: 'clear.aspx',
									html: '<br />' + AdmeaDossier.Locale.SessionResetCookies
								}
							} )
						]
       				} )
    			]
    		} );
    		
    		loginForm.addButton( submitBtn = new Ext.Button( {
					text: AdmeaDossier.Locale.LoginAction,
					type: 'submit',
					handler: function()
					{
						loginForm.getForm().submit( {
							url: AdmeaDossier.getURLForMethod( 'authenticate' ),
							waitTitle: AdmeaDossier.Locale.LoginWaitTitle,
							waitMsg: AdmeaDossier.Locale.LoginWaitMessage,
							success: AdmeaDossier.Session.handleLoginResponse,
							failure: function() { loginPanel.findById( 'password' ).focus( true ).setRawValue( '' ); }
						});
					}
				}
			) );
			
			loginForm.addButton( new Ext.Button( {
				text: AdmeaDossier.Locale.LoginCancel,
				handler: function()
				{
					loginForm.findById( 'password' ).setRawValue( '' );
					loginPanel.hide();
				}
			} ) );
		}
	};
}();
