Ext.ns('Ext.pv.security');
Ext.pv.security.LoginDialog = Ext.extend(Ext.Window, {
	id : 'loginDialogId',
	frame : true,
	forceLayout : true,
	width : 420,
	autoHeight : true,
	modal : true,
	resizable : false,
	
	// Localized strings
	title : 'Login',
	usernameLabelText : 'Email',
	passwordLabelText : 'Password',
	rememberMeLabel : 'Remember me on this computer',
	changePasswordText : 'Change Password?',
	forgotPasswordText : 'Forgot Password?',
	requestFriendshipButtonText : 'Request Friendship',
	requestFriendshipText : 'If you do not have a user and password for this profile, you may request to be added to the Family and Friends by clicking {0}here{1}',
	loginButtonText : 'Login',
	cancelButtonText : 'Cancel',
	invalidLoginText : 'The email/password combination is invalid.',
	
	initialMessage : '',
	
	direction : 'ltr',
	vendorId : 0,
	personId : 0,
	contextPath : null,
	showChangePassword : false,
	showForgotPassword : false,
	showRequestFriendship : false,
	
	successfullLoginCallback : function() {},
	

	/**
	 * initComponent
	 * 
	 * @protected
	 */
	initComponent : function() {

		if (this.direction=='rtl') {
			this.style = 'direction:rtl';
		}
		
		// Initialize the data store
		if (this.initialMessage==null || this.initialMessage.length==0) {
			this.initialMessage = '';
		}
		this.items = [ this.buildErrorsPanel(this.initialMessage), this.buildLoginForm(), this.buildLinksPanel() ];
	
		this.buttons = [ {
			text : this.loginButtonText,
			handler : this.doAjaxLogin,
			scope : this
		},{
			text : this.cancelButtonText,
			handler : this.onCancel,
			scope : this
	    } ];
		
		this.on(
			'show',
			function() {
				var fld = Ext.getCmp("login_username");
				fld.focus('',true);
				fld.clearInvalid();
			},
			this
		);
		
		// super
		Ext.pv.security.LoginDialog.superclass.initComponent.call(this);
	},
	
	/**
	 * buildLinksPanel
	 * 
	 * @private
	 */
	buildErrorsPanel: function(message) {
	
		this.errorsPanel = new Ext.Panel({
		    border: false,
		    height: 40,
			bodyStyle: 'background-color:#f0f0f0;padding: 10 20 10 20px;',
			html: '<div style="text-align: center; color: #FF0000;">' + message + '</div>'
		});
	
		return this.errorsPanel;
	},
	
	/**
	 * buildLoginForm
	 * 
	 * @private
	 */
	buildLoginForm : function() {
	
		this.loginForm = new Ext.FormPanel( {
			frame : false,
			border : false,
			bodyStyle: 'background-color:#f0f0f0;padding:0 20 0 20px;',
			labelWidth : 75,
			autoWidth : true,
			autoHeight : true,
			monitorValid : true,
			
			// For when we are doing a Form submit login
			standardSubmit : true,
			url : this.contextPath + '/j_spring_security_check',
			method : 'POST',
			
			defaults: {width: 280},
			defaultType : 'textfield',
			items : [ 
			{
				xtype : 'hidden',
				id : 'j_username'
			}, 
			{
				xtype : 'emailfield',
				id : 'login_username',
				fieldLabel : this.usernameLabelText,
				allowBlank : false,
				validateOnBlur : false,
				style: {marginBottom: '0px', marginTop: '0px'}
			}, {
				id : 'j_password',
				fieldLabel : this.passwordLabelText,
				inputType : 'password',
				allowBlank : false,
				enableKeyEvents : true,
				listeners : {
					specialkey : function(f, o) {
			            if (o.getKey() == 13) {
			            	o.stopEvent(); // prevent event propogation in Chrome/Safari
			                this.doAjaxLogin();
						}
					},
					scope : this
				},
				style: {marginBottom: '0px', marginTop: '0px'}
			},{
				xtype : 'checkbox',
				id : 'remember_me',
				boxLabel : this.rememberMeLabel,
				labelSeparator: ''
			}]
		});
	
		return this.loginForm;
	},
	
	/**
	 * buildLinksPanel
	 * 
	 * @private
	 */
	buildLinksPanel: function() {
	
		var changeStyle = 'font-weight:bold;color:#666666;';
		var forgotStyle = 'font-weight:bold;color:#666666;';
		if (this.direction=='rtl') {
			changeStyle += 'float:right;padding-right:80px;';
			forgotStyle += 'float:left;';
		} else {
			changeStyle += 'float:left;padding-left:80px;';
			forgotStyle += 'float:right;';
		}
		
		var html = '';
		if (this.showChangePassword) {
			html += '<a style="' + changeStyle + '" '
				+ 'href="javascript:Ext.getCmp(\'' + this.id + '\').changePassword()">' + this.changePasswordText + '</a>';
		}
		if (this.showForgotPassword) {
			html += '<a style="' + forgotStyle + '" '
				+ 'href="javascript:Ext.getCmp(\'' + this.id + '\').forgotPassword()">' + this.forgotPasswordText + '</a>';
		}
		if (this.showRequestFriendship) {
			html += '<br/><br/>' + String.format(this.requestFriendshipText,
				'<a style="font-weight:bold;color:#666666;" href="javascript:Ext.getCmp(\'' + this.id + '\').requestFriendship()">', 
				'</a>');
		}
		
	    this.linksPanel = new Ext.Panel({
		    border: false,
			bodyStyle: 'background-color:#f0f0f0;padding: 5 20 30 20px;',
			html: html
		});
	
		return this.linksPanel;
	},
	
	onCancel : function() {
		this.close();
	},

	autoLogin : function(username, password, isAjaxLogin) {
		this.loginForm.getForm().findField('login_username').setValue(username);
		this.loginForm.getForm().findField('j_password').setValue(password);
		if (isAjaxLogin) {
			this.doAjaxLogin();
		} else {
			this.doFormSubmitLogin();
		}
	},

	
	doAjaxLogin : function(button, event) {
	    if(this.loginForm.getForm().isValid()){
			this.errorsPanel.body.update('&nbsp;');
			
			var thisDialog = this;
			Ext.Ajax.request( {
				url : this.contextPath + '/j_spring_security_check',
				method : 'POST',
				success : function(result, request) {

					var response = null;
					cmd = 'response = ' + result.responseText + ';';
					try {
						// If a JSON response was not returned then the login failed.
						// The following eval will also fail and the try/catch will
						// ensure that we show the user an error message specifying
						// invalid login.
						eval(cmd);
					} catch (error) {
						// Show the invalid login error
						var msg = ''
							+ '<div style="text-align: center; color: #FF0000;">'
							+ thisDialog.invalidLoginText
							+ '</div>';
						thisDialog.errorsPanel.body.update(msg);
					}
					
					if (response!=null && response.success!=null) {
						// User is logged in
						thisDialog.successfullLoginCallback();
					}

				},
				params : {
					"onSuccess" : '/user/ajaxSuccess.jsp',
					j_username : this.vendorId + ':' + this.loginForm.getForm().findField('login_username').getValue(),
					j_password : Ext.util.Format.trim(this.loginForm.getForm().findField('j_password').getValue()),
					_spring_security_remember_me : this.loginForm.getForm().findField('remember_me').getValue()
				}
				
			});
			
		}
	},
	
	doFormSubmitLogin : function(button, event) {
		if(this.loginForm.getForm().isValid()){

			this.loginForm.getForm().findField('j_username').setValue(
					this.vendorId + ':'
					+ this.loginForm.getForm().findField('login_username').getValue());
			
			// Trim leading and trailing whitespace from password
			this.loginForm.getForm().findField('j_password').setValue(
					Ext.util.Format.trim(this.loginForm.getForm().findField('j_password').getValue()));
			
			if(this.loginForm.url) {
				this.loginForm.getForm().getEl().dom.action = this.loginForm.url;
			}
			
			this.loginForm.getForm().submit();
		}
	},
	
	changePassword : function() {
		var username = this.loginForm.getForm().findField('login_username').getValue();
		var dlg = new Ext.pv.security.ChangePasswordDialog({
			vendorId : this.vendorId,
			personId : this.personId,
			contextPath : this.contextPath,
			successfullLoginCallback : this.successfullLoginCallback,
			username : username,
			doAjaxLogin : true,
			direction: this.direction
		});
		dlg.show();
		
		this.close();
	},
	
	forgotPassword : function() {
		var username = this.loginForm.getForm().findField('login_username').getValue();
		var dlg = new Ext.pv.security.ForgotPasswordDialog({
			personId : this.personId,
			contextPath : this.contextPath,
			username : username,
			direction: this.direction
		});
		dlg.show();
		
		this.close();
	},
	
	requestFriendship : function() {
		var dlg = new Ext.pv.security.RequestFriendshipDialog({
			personId : this.personId,
			contextPath : this.contextPath,
			direction: this.direction
		});
		dlg.show();
		
		this.close();
	}

});
