Ext.ns('Ext.pv.fandf');
Ext.pv.fandf.ImportDialog = Ext.extend(Ext.Window, {
	frame : true,
	layout : 'card',
	activeItem: 0,
	forceLayout : true,
	autoScroll : true,
	width : 600,
	height : 450,
	modal : true,
	resizable : false,
	
	northPanelHeight : 90,
	
	// Localized strings
	title : 'Import Friends and Family',
	step1Label : 'Step 1 of 3',
	step2Label : 'Step 2 of 3',
	step3Label : 'Step 3 of 3',
	step4Label : 'Import Complete',
	instructionText1 : 'Use this page to quickly invite many people to join the friends and family group. Most email clients give the ability to export your contacts to a file. You can import that file here and select the contacts that will be sent an invitation.',
	instructionText2 : 'Here is the file that was uploaded. Use this page to specify column positions for the data that will be used to import your guests.  If required, return to the previous page to alter your settings or upload a different file.',
	instructionText3 : 'Use the checkboxes to identify the contacts that you would like to invite to the friends and family group. Expand any rows that have errors associated with them to see the details of the error.',
	instructionText4 : 'Here are the results of your import.',
	okButtonText : 'OK',
	prevButtonText : '< Previous',
	nextButtonText : 'Next >',
	importButtonText : 'Import',
	cancelButtonText : 'Cancel',
	doneButtonText : 'Done',
	alertTitle : 'Message',
	invalidInputMessage : 'Form is invalid.',
	emptySelectionMessage : 'You must select at least one row to import.',
	confirmTitle : 'Confirm',
	inviteConfirmationMessage : 'The selected users will be added as members of the friends and family. Continue?',
	progressTitle : 'Processing',
	pleaseWaitMessage : 'Please wait ...',
	
	direction : 'ltr',
	personId : 0,
	contextPath : null,
	callback : null,
	

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

		if (this.direction=='rtl') {
			this.style = 'direction:rtl';
		}
	
		// Build the wizard panels
		this.importForm = new Ext.pv.fandf.UploadFileForm({
			personId : this.personId,
			contextPath : this.contextPath,
			region : 'center',
			border : true,
			margins: {top:0, right:5, bottom:5, left:5}
		});
		
		this.csvGrid = new Ext.ux.grid.MetaGrid({
			region: 'center',
			columnLines: true,
			stripeRows : true,
			enableColumnHide : false,
			enableColumnMove : false,
			enableHdMenu : false,
			trackMouseOver : false,
			loadMask : true,
			url : this.contextPath + '/siteAdmin/family/viewUploadedFile.html',
			autoInitialize : false,
			baseParams: { personId: this.personId },
			border : true,
			margins: {top:0, right:5, bottom:0, left:5}
		});
		
		this.columnsForm = new Ext.pv.fandf.SelectColumnsForm({
			personId : this.personId,
			contextPath : this.contextPath,
			region : 'south',
			height: 145,
			border : true,
			margins: {top:5, right:5, bottom:5, left:5}
		});
		
		this.userGrid = new Ext.pv.fandf.UserGrid({
			personId : this.personId,
			contextPath : this.contextPath,
			border : true,
			margins: {top:0, right:5, bottom:5, left:5}
		});
		this.userGrid.on(
			'gridload',
			function() {
				// Hide progress dialog
				this.hideProgress();
			},
			this
		);
		
		this.items = [{
				id : 'import-step1',
				layout : 'border',
				items : [{
						layout : 'fit',
						region : 'north',
						height : this.northPanelHeight,
						bodyCssClass: 'infoBox',
						html : '<b>' + this.step1Label + ':</b><br /><br />' + this.instructionText1,
						margins: {top:5, right:5, bottom:5, left:5}
					},
					this.importForm
				]
			},{
				id : 'import-step2',
				layout : 'border',
				items : [{
						layout : 'fit',
						region : 'north',
						height : this.northPanelHeight,
						bodyCssClass: 'infoBox',
						html : '<b>' + this.step2Label + ':</b><br /><br />' + this.instructionText2,
						margins: {top:5, right:5, bottom:5, left:5}
					},
					this.csvGrid,
					this.columnsForm
				]
			},{
				id : 'import-step3',
				layout : 'border',
				items : [{
						layout : 'fit',
						region : 'north',
						height : this.northPanelHeight,
						bodyCssClass: 'infoBox',
						html : '<b>' + this.step3Label + ':</b><br /><br />' + this.instructionText3,
						margins: {top:5, right:5, bottom:5, left:5}
					},
					this.userGrid
				]
			},{
				id : 'import-step4',
				layout : 'border',
				items : [{
						layout : 'fit',
						region : 'north',
						height : this.northPanelHeight,
						bodyCssClass: 'infoBox',
						html : '<b>' + this.step4Label + ':</b><br /><br />' + this.instructionText4,
						margins: {top:5, right:5, bottom:5, left:5}
					},{
						id : 'import-results',
						layout : 'fit',
						autoScroll : true,
						region : 'center',
						bodyStyle: 'padding: 10px;',
						html : 'statuses will go here',
						margins: {top:0, right:5, bottom:5, left:5}
					}
				]
			}
		];
		
		// Build the wizard buttons
		this.buttons = [ {
			id : 'import-prevBtn',
			text : this.prevButtonText,
			handler : this.onPrevious,
			scope : this
		},{
			id : 'import-nextBtn',
			text : this.nextButtonText,
			handler : this.onNext,
			scope : this
		},{
			id : 'import-finalBtn',
			text : this.importButtonText,
			handler : this.onNext,
			scope : this
		},{
			id : 'import-cancelBtn',
			text : this.cancelButtonText,
			handler : this.onCancel,
			scope : this
		} ];
		
		// super
		Ext.pv.fandf.ImportDialog.superclass.initComponent.call(this);
		
		// Initialize the view
		this.on(
			'show',
			function () {
				this.setState();
			},
			this
		);
		
		this.on(
			'close',
			function () {
				if (this.getLayout().activeItem.id=='import-step4') {
					this.callback();
				}
			},
			this
		);
		
	},
	
	onPrevious : function() {
		if (this.getLayout().activeItem.id=='import-step1') {
			// Do nothing - already at head of list
		} else if (this.getLayout().activeItem.id=='import-step2') {
			this.getLayout().setActiveItem('import-step1');
		} else if (this.getLayout().activeItem.id=='import-step3') {
			this.getLayout().setActiveItem('import-step2');
		}
		this.setState();
	},
	
	onNext : function() {
		if (this.getLayout().activeItem.id=='import-step1') {
			this.doFileUpload();
		} else if (this.getLayout().activeItem.id=='import-step2') {
			this.doUserPreview();
		} else if (this.getLayout().activeItem.id=='import-step3') {
			this.doImport();
		} else if (this.getLayout().activeItem.id=='import-step4') {
			this.close();
		}
	},
	
	onCancel : function() {
		this.close();
	},
	
	setState : function() {
		if (this.getLayout().activeItem.id=='import-step1') {
			Ext.getCmp('import-prevBtn').setDisabled(true);
			Ext.getCmp('import-nextBtn').setDisabled(false);
			Ext.getCmp('import-finalBtn').setDisabled(true);
		} else if (this.getLayout().activeItem.id=='import-step2') {
			Ext.getCmp('import-prevBtn').setDisabled(false);
			Ext.getCmp('import-nextBtn').setDisabled(false);
			Ext.getCmp('import-finalBtn').setDisabled(true);
		} else if (this.getLayout().activeItem.id=='import-step3') {
			Ext.getCmp('import-prevBtn').setDisabled(false);
			Ext.getCmp('import-nextBtn').setDisabled(true);
			Ext.getCmp('import-finalBtn').setDisabled(false);
		} else if (this.getLayout().activeItem.id=='import-step4') {
			Ext.getCmp('import-prevBtn').setVisible(false);
			Ext.getCmp('import-nextBtn').setVisible(false);
			Ext.getCmp('import-finalBtn').setVisible(false);
			Ext.getCmp('import-cancelBtn').setText(this.doneButtonText);
		}
	},
	
	doFileUpload : function() {
		// Ensure the form input is valid
		if (!this.importForm.isValid()) {
			return false;
		}
		
		// Show progress dialog
		this.showProgress();
		
		var myThis = this;
		this.importForm.getForm().submit({
			clientValidation: true,
			url: this.contextPath + '/siteAdmin/family/uploadFile.do',
			success: function(form, action) {
				// Hide progress dialog
				myThis.hideProgress();
			
				// Change wizard to show the next step
				myThis.getLayout().setActiveItem('import-step2');
				myThis.setState();
				
				// Load the grid with a preview of the records to be uploaded
				myThis.doViewUploadedFile();
			},
			failure: function(form, action) {
				Ext.Msg.alert(myThis.alertTitle,action.result.error);
			}
		});
	},
	
	doViewUploadedFile : function() {
		this.csvGrid.load();
	},
	
	doUserPreview : function() {
		// Ensure the form input is valid
		if (!this.columnsForm.isValid()) {
			return false;
		}
		
		// Show progress dialog
		this.showProgress();
		
		this.getLayout().setActiveItem('import-step3');
		this.setState();
		
		this.userGrid.load({
			firstnameIndex : this.columnsForm.getForm().findField('firstnameIndex').getValue(),
			lastnameIndex : this.columnsForm.getForm().findField('lastnameIndex').getValue(),
			emailIndex : this.columnsForm.getForm().findField('emailIndex').getValue()
		});
	},
	
	doImport : function() {
		// Ensure that at least one record is selected for import
		if (this.userGrid.getSelectedRowCount()==0) {
			Ext.Msg.alert(this.alertTitle,this.emptySelectionMessage); 
			return false;
		}
		
		var myThis = this;
		// Get final confirmation to continue
		Ext.Msg.confirm(
			this.confirmTitle, 
			this.inviteConfirmationMessage, 
			function(btn, text){
				if (btn == 'yes'){
					
					// Show progress dialog
					myThis.showProgress();
					
					// Do the import
					Ext.Ajax.request( {
						url : myThis.contextPath + '/siteAdmin/family/import.do',
						method : 'POST',
						success : function(result, request) {
							// Hide progress dialog
							myThis.hideProgress();
							
							// Inject the results into the UI
							var panel = Ext.getCmp('import-results');
							panel.update(result.responseText);
							panel.doLayout(true,true);
						
							// Change wizard to show the next step
							myThis.getLayout().setActiveItem('import-step4');
							myThis.setState();
						},
						params : {
							personId : myThis.personId,
							json : myThis.userGrid.getSelectedRowsAsJson()
						}
					});
					
				}
			}
		);
		
	},
	
	showProgress : function() {
		// The Ext.MessageBox.wait() method seems to contain bugs when shown
		// multiple times so we need to build it from scratch.
		Ext.MessageBox.show({
			title : this.progressTitle,
			msg : this.pleaseWaitMessage,
			wait : true,
			width : 250
		});
	},
	
	hideProgress : function() {
		Ext.MessageBox.hide();
	}

});
