function setEditorDefaults(editor){
	var ifr = Ext.get(editor.nextSibling);
	var j = 0;
}

var citationForm = function(conf) { //= new Ext.form.FormPanel({
	this.proj = conf.proj || '';
	this.store = conf.store || '';
	var hookcallback = conf.hookcallback || '';
	var rec = conf.data || '';
	this.saveCitationbtn = new Ext.Button({
		text: 'Save Citation',
		icon: 'extjs/resources/images/icons/database_save.png',
		handler: function(){
			if(this.getForm().isValid()){
				var f = this.getForm().getValues();
				Ext.Ajax.request({
					url: 'addCitation.php',
					params: f,
					success: function(resp){
						var json = Ext.util.JSON.decode(resp.responseText);
						if(json.success){
							var title = 'Citation Added';
							if(conf.hookcallback == 'save'){
								conf.store.reload();
							}
						} else {
							var title = 'ERROR';
						}
						Ext.MessageBox.show({
							title: title,
							msg: json.msg,
							buttons: Ext.MessageBox.OK
						});
					},
					failure: function(){
						Ext.MessageBox.show({
							title: 'ERROR',
							msg: 'An error occurred processing your request.  Session timed out?',
							buttons: Ext.MessageBox.OK
						});
					}
				});
			} else {
				// autofocus on first invalid field here...
			}
		},
		scope: this
	});
	
	this.deleteCitationbtn = new Ext.Button({
		text: 'Delete Citation',
		icon: 'extjs/resources/images/icons/database_delete.png',
		handler: function(){
			Ext.MessageBox.confirm(
				'Confirm Delete',
				'You have requested that the selected citation be permanently deleted from the project.  Proceed?',
				function(btn){
					if(btn == "yes"){
						var i = this.getForm().findField('id').getValue();
						Ext.Ajax.request({
							url: 'deleteCitation.php',
							params: {i: i},
							success: function(resp){
								var json = Ext.util.JSON.decode(resp.responseText);
								if(json.success){
									if(conf.hookcallback == 'delete') conf.store.reload();
								}
							},
							failure: function(){
								Ext.MessageBox.alert('ERROR', 'Session time out or server failure.');	
							}
						});
					}
				},
				this
			);
		},
		scope: this
	});
	
	this.clearCitationbtn = new Ext.Button({
		text: 'Clear Form',
		icon: 'extjs/resources/images/icons/page_white.png',
		handler: function() {
			this.getForm().reset();
		},
		scope: this
	});
	
	if(rec == ""){
		var citid = '';
		var title = '';
		var citationdate = "";
		var citationtext = '';
		var buttons = [this.saveCitationbtn, this.clearCitationbtn];
	} else {
		var buttons = [this.saveCitationbtn, this.deleteCitationbtn];
		var citid = rec.id;
		var title= rec.citationtitle;
		var citationdate = rec.citationdate;
		var citationtext = rec.citation;
	}
	
	this.recid = new Ext.form.Hidden({
		name: 'id',
		value: citid
	});
	
	this.projectid = new Ext.form.Hidden({
		name: 'projectid',
		value: this.proj
	});
	
	this.citationtitle = new Ext.form.TextField({
		fieldLabel: 'Title',
		name: 'citationtitle',
		maxLength: 30,
		allowBlank: false,
		value: title
	});
	
	this.citationdate = new Ext.form.DateField({
		fieldLabel: 'Citation Date',
		format: "Y-m-d",
		name: 'citationdate',
		allowBlank: false,
		value: citationdate
	});
	
	this.citation = new Ext.form.HtmlEditor({
		name: 'citation',
		height: 160,
		width: 490,
		fieldLabel: 'Citation',
		width: 480,
		hideLabel: true,
		allowBlank: false,
		height: 150,
		maxLength: 500,
		enableAlignments: false,
		enableLists: false,
		enableSourceEdit: false,
		enableFontsize: false,
		enableFont: false,
		value: citationtext
	});
	
	this.width = 500;
	this.frame = false;
	this.border = false;
	this.autoHeight = true;
	this.items = [this.projectid, this.recid, this.citationtitle, this.citationdate, this.citation];
	this.bbar = buttons;
	citationForm.superclass.constructor.call(this);
}
Ext.extend(citationForm, Ext.form.FormPanel, {});

var citationWin = function(proj){
	this.proj = proj;
	this.title = 'Manage Project '+proj+' Citations';
	this.width = 525;
	this.style = 'background: black;';
	this.closable = true;
	this.autoHeight = true;
	this.modal = true,
	this.store = new Ext.data.JsonStore({
		url: 'getProjCitations.php',
		root: 'data',
		baseParams: {p: proj},
		fields: ['id','projectid','citation','citationdate','citationtitle'],
		sortInfo: {field: 'citationdate', direction: 'ASC'}
	});
	citationWin.superclass.constructor.call(this);
	this.store.on('load', this.getTabs, this);
	this.on('show', function(){
		this.store.load();
	})
}
Ext.extend(citationWin, Ext.Window, {
	getTabs: function(){
		var tabpanel = new Ext.TabPanel({
			activeTab: 0,
			height: 265,
			enableTabScroll: true,
			//autoHeight: true,
			width: 500,
			deferredRender: true,
			layoutOnTabChange: true,
			defaults: {
				autoHeight: true,
				frame: false,
				bodyStyle: 'padding: 5px;',
				border: false
			}
		});
		
		var items = [];
		this.store.each(function(rec){
			items.push({panel: new citationForm({proj: this.proj, hookcallback: 'delete', data: rec.data, store: this.store}), title: rec.data.citationtitle});
		}, this);
		Ext.each(items, function(item){
			tabpanel.add({
				title: item.title,
				items: item.panel
			})
		}, this);
		this.addcitationform = new citationForm({proj: this.proj, hookcallback: 'save', store: this.store});
		this.addcitationform.on('actioncomplete', function(f, a){
			alert("GOT HERE!");
		});
		
		tabpanel.add({
			title: 'New Citation',
			items: this.addcitationform
		});
		this.removeAll();
		this.add(tabpanel);
		this.setPosition(175, 150);
		this.doLayout();
	}
})

var projectForm = function(proj) {
	var cfg = {};
	var myproj = "";
	var needsNotice = false;
	var datachanged = false;
	
	var piStore = new Ext.data.JsonStore({
		url: 'getPIs.php',
		fields: ['users_name'],
		sortInfo: {field: "users_name", order: "ASC"}
	});
	
	var instituteStore = new Ext.data.JsonStore({
		url: 'getOrgs.php',
		fields: ['organization']
	});
	
	var projectsStore = new Ext.data.JsonStore({
		url: 'getProjects.php',
		fields: ['projects_projectid'],
		sortInfo: {field: 'projects_projectid', direction: 'ASC'}
	})

	var managerStore = new Ext.data.DirectStore({
		//url: 'getProjectManagers.php',
		autoLoad: true,
		paramsAsHash: true,
		baseParams: {addNone: false},
		directFn: ICCI.ICCI.getManagers,
		root: 'data',
		fields: ['manager'],
		sortInfo: {field: 'manager', direction: 'ASC'}
	});
	
	var mykeywordsStore = new Ext.data.JsonStore({
		url: 'getKeywords.php',
		sortInfo: {field: "keyword", direction: "ASC"},
		baseParams: {proj: myproj},
		fields: ['id', 'keyword']
	});
	
	var keywordcm = new Ext.grid.ColumnModel([{
		header: '<center><font style="font-size: 15px;"><b>Attached Keywords</b></font></center>',
		width: 158,
		dataIndex: 'keyword',
		renderer: function(v) {
			var html = '<font style="font-size: 13px;">'+v+'</font>';
			return html;
		} 
	}]);
	
	var keywordgrid = new Ext.grid.GridPanel({
		id: 'keywordgrid',
		store: mykeywordsStore,
		cm: keywordcm,
		frame: true,
		border: false,
		collapsible: false,
		height: 250,
		width: 162,
		frame: true,
		buttonAlign: 'center'
	});
	
	var globalKeywords = new Ext.data.JsonStore({
		url: 'getGlobalKeywords.php',
		baseParams: {proj: myproj},
		sortInfo: {field: "keyword", direction: "ASC"},
		fields: ['id', 'keyword']
	});
	
	var globalcm = new Ext.grid.ColumnModel([{
		header: '<center><font style="font-size: 15px;"><b>Available Keywords</b></font></center>',
		width: 158,
		dataIndex: 'keyword',
		renderer: function(v) {
			var html = '<font style="font-size: 13px;">'+v+'</font>';
			return html;
		}
	}]);
	
	var globalkeywordgrid = new Ext.grid.GridPanel({
		id: 'globalkeywordgrid',
		store: globalKeywords,
		cm: globalcm,
		frame: true,
		border: false,
		collapsible: false,
		height: 250,
		width: 162,
		frame: true
	});
	
	function checkNewProject() {
		if(this.id == "projects_projectid"){
			var v = this.getValue().toUpperCase();
			this.setValue(v.toUpperCase());
			if (v == "") return false;
			var q = projectsStore.query('projects_projectid', v);
			if(q.length == 0) {
				this.disable();
				myproj = v;
				// mykeywordsStore.removeAll();
				Ext.getCmp('generalfields').show();
				Ext.getCmp('generalfields').doLayout();
				projectcompleted.show();
				proprietary.show();
				featureproject.show();
				Ext.getCmp('savedata').enable();
				Ext.getCmp('resetprojsform').enable();
				Ext.getCmp('uploadreport').enable();
				Ext.getCmp('uploadimage').enable();
				Ext.getCmp('managecitationsbtn').enable();
				Ext.getCmp('addproject').setValue('true');
				Ext.getCmp('resetprojsform').enable();
				Ext.getCmp('completed').enable();
				Ext.getCmp('projects_isfeatured').enable();
				Ext.getCmp('projects_title').focus(true, 50);
			}
		}
		checkForm();
	}
	
	function registerChange() {
		datachanged = true;
	}
	
	function checkForm() {
		var resetbtn = Ext.getCmp('resetprojsform');
		if(resetbtn.disabled) {
			resetbtn.enable();
		}
		if(myform.getForm().isValid()) {
			Ext.getCmp('savedata').enable();
		}
	}

	function proprietaryNag() {
			var isproprietary = Ext.getCmp('project').getForm().findField('projects_proprietary').getValue();
			if(isproprietary){
				Ext.MessageBox.alert(
					'Proprietary Content Warning', 
					'This project contains information that is deemed proprietary to the researcher.  Be certain that you do not upload any proprietary content in the file you are attaching in this operation.',
					function(id){
						fileUpload({title: "Upload Project Report", url: "projFileUpload.php", type: "R"});
					}
				);
			} else {
				fileUpload({title: "Upload Project Report", url: "projFileUpload.php", type: "R"});
			}
		};
	
	var viewapplicationbtn = new Ext.Button({
		id: 'viewapplication',
		text: 'View Original Application',
		icon: 'extjs/resources/images/icons/page_find.png',
		disabled: true,
		handler: function(){
			var id = projectidselector.getValue().replace("/", "-slash-");
			var appwin = new Ext.Window({
				width: 850,
				height: 600,
				closeAction: 'close',
				modal: true,
				html: '<iframe src="/home/domains/icci.org/public_html/applications/'+id+'" width="850" height="600" scrolling="true"></iframe>'
			});
			appwin.show();
		}
	});
	
	var uploadreportbtn = new Ext.Button({
		id: 'uploadreport',
		text: 'Upload Report',
		icon: 'extjs/resources/images/icons/report_add.png',
		disabled: true,
		handler: proprietaryNag
	});
	var uploadimagebtn = new Ext.Button({
		id: 'uploadimage',
		text: 'Upload Image',
		icon: 'extjs/resources/images/icons/image_add.png',
		handler: function() {
			fileUpload({title: "Upload Featured Project Image", url: "projFileUpload.php", type: "I"});
		}
	});
	var deleteimagebtn = new Ext.Button({
		id: 'deleteimage',
		icon: 'extjs/resources/images/icons/image_delete.png',
		disabled: true,
		text: 'Delete Image',
		handler: function() {
			fileUpload({title: "Upload Featured Project Image", url: "projFileUpload.php", type: "I"});
		}
	});

	var deletereportbtn = new Ext.Button({
		id: 'deletereport',
		icon: 'extjs/resources/images/icons/report_delete.png',
		disabled: true,
		text: 'Delete Report',
		handler: function() {
			fileUpload({title: "Upload Featured Project Image", url: "projFileUpload.php", type: "I"});
		}
	});
	
	function manageCitations(){
		var mywin = new citationWin(myproj);
		// mywin.add(new citationForm(myproj));
		mywin.show();
	}

	var managecitationsbtn = new Ext.Button({
		id: 'managecitationsbtn',
		icon: 'extjs/resources/images/icons/folder_database.png',
		disabled: true,
		text: 'Citation Mgr',
		handler: manageCitations
	});

	var imagebtns = [uploadimagebtn, deleteimagebtn];
	var reportbtns = [uploadreportbtn, deletereportbtn];
	
	var reportwidget = new Ext.Panel({
		layout: 'form',
		border: false,
		frame: false,
		width: 230,
		labelWidth: 40,
		items: new Ext.form.TextField({
			id: 'projects_reporttitle',
			layout: 'form',
			fieldLabel: 'Report',
			itemCls: 'reporttitleplacement',
			cls: 'blacktext',
			width: 175
		})
	});
	
	var imagewidget = new Ext.Panel({
		layout: 'form',
		border: false,
		frame: false,
		width: 500,
		labelWidth: 100,
		bodyStyle: 'padding-left: 8px;',
		items: new Ext.form.TextField({
			id: 'projects_featureimage',
			layout: 'form',
			fieldLabel: 'Image',
			itemCls: 'featureimageplacement',
			cls: 'blacktext',
			width: 375
		})
	});
	
	var featurebuttons = [ uploadreportbtn, uploadimagebtn];
	
	var editor = new Ext.form.HtmlEditor({
		id: 'projects_featureheadline',
		fieldLabel: 'Article Text',
		width: 615,
		// height: 225,
		maxLength: 65535,
		plugins: [ new Ext.ux.form.HtmlEditor.WordWin() ]
	});
	
	var featureset = new Ext.Panel({
		id: 'featureset',
		border: false,
		frame: false,
		layout: 'fit',
		items: [editor, imagewidget]
	});
	
	var projectidselector = new Ext.form.ComboBox({
		id: 'projects_projectid',
		fieldLabel: 'Project ID',
		mode: 'local',
		enableKeyEvents: true,
		selectOnFocus: true,
		editable: true,
		allowBlank: false,
		disabled: false,
		height: 35,
		width: 150,
		minChars: 2,
		displayField: 'projects_projectid',
		triggerAction: 'all',
		listeners: {
			blur: checkNewProject,
			select: loadSelection
		},
		maxLength: 20,
		mode: 'local',
		store: projectsStore
	});
	
	var projectcompleted = new Ext.Container({
		layout: 'form',
		hidden: true,
		items: new Ext.form.Checkbox({
			id: 'completed',
			cls: 'completedcheckbox',
			disabled: true,
			width: 'auto',
			border: true,
			frame: false,
			fieldLabel: 'Completed'
		})
	});
	
	var featureproject = new Ext.Container({
		layout: 'form',
		hidden: true,
		items: new Ext.form.Checkbox({
			id: 'projects_isfeatured',
			disabled: false,
			width: 'auto',
			labelWidth: 75,
			fieldLabel: 'Feature Project',
			allowBlank: true,
			listeners: {check: enableFeaturesManager, scope: this}
		})
	});
	
	var proprietary = new Ext.Container({
		layout: 'form',
		hidden: true,
		items: new Ext.form.Checkbox({
			id: 'projects_proprietary',
			disabled: false,
			fieldLabel: 'Proprietary',
			allowBlank: true
		})
	});

	function notifyLisa(){
		needsNotice = false;
		var st = projectcompleted.items.items[0].getValue();
		if(st) {
			Ext.Ajax.request({
				url: 'notifyLisa.php',
				params: {p: projectidselector.getValue()},
				failure: function(resp){
					Ext.MessageBox.alert("Communication Error", resp.responseText);
				}
			})
		}
	}

	var selector = new Ext.Container({
		layout: 'column',
		autoEl: {},
		border: false,
		frame: false,
		defaults: {
			border: false,
			frame: false,
			layout: 'form',
			xtype: 'container',
			width: 150,
			autoEl: {}
		},
		items: [{
			width: 275,
			items: projectidselector
		},{
			// width: 100,
			labelWidth: 65,
			items: projectcompleted
		},{
			labelWidth: 93,
			items: featureproject
		},{
			labelWidth: 80,
			items: proprietary 
		}]
	});
	
	var myform = new Ext.form.FormPanel({
		id: 'project',
		labelAlign: 'right',
		width: 780,
		autoHeight: true,
		//height: 450,
		autoScroll: true,
		cls: 'mgtconsole',
		border: false,
		frame: false,
		//bodyStyle: "align: center;",
		//style: "text-align: left;",
		buttonAlign: 'right',
		defaults: {
			itemCls: 'mgtconsole',
			layout: 'form',
			frame: false,
			border: false,
			allowBlank: false
		},
		items: [{
			xtype: 'panel',
			width: 780,
			items: selector
		},{
			xtype: 'panel',
			id: 'generalfields',
			autoHeight: true,
			width: 780,
			forceLayout: true,
			frame: false,
			border: false,
			hidden: true,
			defaults: {
				frame: false,
				border: false,
				forceLayout: true
			},
			items: [{
				xtype: 'container',
				layout: 'form',
				width: 700,
				labelWidth: 75,
				// width: '96%',
				items: [{
					xtype: 'textarea',
					id: 'projects_title',
					fieldLabel: 'Title',
					width: 657,
					height: 50,
					style: 'text-transform: uppercase;',
					allowBlank: false,
					listeners: {blur: checkForm, change: registerChange},
					maxLength: 250
				}]
			},{
				xtype: 'panel',
				layout: 'column',
				frame: false,
				border: false,
				width: 800,
				cls: 'padleft',
				defaults: {
					layout: 'form',
					frame: false,
					border: false
				},
				items: [{
					width: 370,
					items: [{
						xtype: 'combo',
						mode: 'local',
						store: piStore,
						listWidth: 260,
						displayField: 'users_name',
						itemCls: 'combo',
						editable: true,
						listeners: {select: processPISel, blur: checkPI},
						id: 'projects_investigator',
						fieldLabel: 'P.I. ',
						allowBlank: false,
						width: 260,
						maxLength: 50
					}]
				},{
					width: 390,
					items: [{
						xtype: 'combo',
						store: instituteStore,
						mode: 'local',
						displayField: 'organization',
						itemCls: 'combo',
						editable: true,
						listeners: {select: registerChange, blur: registerChange},
						id: 'projects_institution',
						fieldLabel: 'Institution',
						allowBlank: false,
						width: 270,
						maxLength: 150
					}]
				}]
			},{
				xtype: 'container',
				layout: 'column',
				width: 700,
				defaults: {
					border: false,
					frame: false,
					layout: 'form'
				},
				items: [{
					layout: 'form',
					width: 425,
					items: [{
						xtype: 'combo',
						id: 'projects_manager',
						store: managerStore,
						editable: true,
						mode: 'local',
						forceSelection: true,
						displayField: 'manager',
						width: 270,
						border: false,
						frame: false,
						maxLength: 150,
						allowBlank: false,
						fieldLabel: 'Project Manager',
						listeners: {blur: checkForm, change: registerChange, focus: function(){ this.setValue("");}}
					}]
				},{
					width: 275,
					layout: 'form',
					items: reportwidget
				}]
			},{
				xtype: 'panel',
				layout: 'column',
				frame: false,
				border: false,
				width: 850,
				defaults: {
					border: false,
					frame: false
				},
				items: [{
					layout: 'form',
					width: 370,
					items: [{
						xtype: 'textfield',
						id: 'projects_yearfunded',
						fieldLabel: 'Year Funded',
						border: false,
						frame: false,
						style: 'text-align: left;',
						allowBlank: false,
						maxLength: 4,
						listeners: {blur: checkForm, change: registerChange}
					}]
				},{
					width: 225,
					layout: 'form',
					items: [{
						xtype: 'datefield',
						id: 'projects_startdate',
						border: false,
						frame: false,
						allowBlank: false,
						fieldLabel: 'Start Date',
						width: 90,
						listeners: {blur: checkForm, change: registerChange},
						format: 'Y-m-d'
					}]
				},{
					width: 225,
					layout: 'form',
					labelWidth: 70,
					items: [{
						xtype: 'datefield',
						id: 'projects_enddate',
						fieldLabel: 'End Date',
						width: 90,
						border: false,
						frame: false,
						allowBlank: false,
						listeners: {blur: checkForm, change: registerChange},
						format: 'Y-m-d'
					}]
				}]
			},{
				xtype: 'panel',
				layout: 'column',
				border: false,
				frame: false,
				bodyStyle: "padding-right: 5px; margin-bottom: 5px;",
				width: 782,
				defaults: {
					border: false,
					frame: false
				},
				items: [{
					columnWidth: 1,
					id: 'abstractcolumn',
					defaults: {
						border: false,
						frame: false,
						layout: 'form',
						labelWidth: 55
					},
					items: [{
						xtype: 'panel',
						layout: 'form',
						items: [ new Ext.form.HtmlEditor({
							id: 'projects_abstract',
							fieldLabel: 'Abstract',
							allowBlank: true,
							defaultFont: 'arial',
							height: 360,
							listeners: {beforepush: setEditorDefaults, blur: checkForm, change: registerChange},
							width: 700,
							plugins: [ new Ext.ux.form.HtmlEditor.WordWin() ]
						})]
					}]
				}]
			},{
				xtype: 'window',
				title: 'Featured Report Attachment Management Console',
				id: 'featurefieldset',
				floating: true,
				closeAction: 'hide',
				frame: true,
				border: true,
				width: 770,
				hidden: true,
				items: [{
					xtype: 'fieldset',
					height: 350,
					width: 750,
					hideMode: 'display',
					collapsible: false,
					border: false,
					title: 'Featured Article Additions',
					items: featureset
				}],
				listeners: { 'show': function() {
						Ext.getCmp('featurefieldset').setPosition(5,5);
					}
				},
				bbar: [{
					text: 'Finished Editing',
					handler: function() {
						Ext.getCmp('featurefieldset').hide();
					}
				/*},{
					text: 'Clear' */
				},
					imagebtns
				]
			},{
				xtype: 'hidden',
				id: 'application_on_file'
			},{
				xtype: 'hidden',
				id: 'addproject',
				value: false
			}]
		}]
	});
	
	function deleteProject() {
		var j = myform.getForm().findField('projects_projectid').getValue();
		Ext.MessageBox.show({
			title: 'Confirm Delete',
			msg: 'You have requested to delete the currently selected project ('+myproj+') and all of its attachments.  This cannot be undone.  Proceed?',
			buttons: Ext.MessageBox.YESNO,
			icon: Ext.MessageBox.NOTICE,
			fn: function(btn){
				if(btn == "yes"){
					var params = {projectid: j};
					Ext.Ajax.request({
						url: 'deleteProject.php',
						params: params,
						success: function(resp){
							var json = Ext.util.JSON.decode(resp.responseText);
							if(json.success){
								Ext.MessageBox.show({
									title: 'Task Confirmed',
									msg: json.msg,
									buttons: Ext.MessageBox.OK,
									icon: Ext.MessageBox.INFO
								});
								clearProjForm();
								// remove record from projectsStore
								var ind = projectsStore.find('projects_projectid', j);
								if(ind != -1){
									projectsStore.removeAt(ind);
								}
								// projectsStore.reload();
							} else {
								Ext.MessageBox.show({
									title: 'Error',
									msg: json.msg,
									buttons: Ext.MessageBox.OK,
									icon: Ext.MessageBox.ERROR
								});
							}
						},
						failure: function(resp){
							Ext.MessageBox.show({
								title: 'Communication Error',
								msg: 'Error communicating with remote server.  Please check your internet connection and/or server status.',
								buttons: Ext.MessageBox.OK,
								icon: Ext.MessageBox.ERROR
							});
						}
					})
				}
			}
		});
	}
	
	function registerNotice(btn, checked){
		if(checked){
			needsNotice = true;
			projectcompleted.items.items[0].removeListener('check', registerNotice);
		} else {
			needsNotice = false;
			projectcompleted.items.items[0].addListener('check', registerNotice);
		}
	}
	
	function prepFormPreprocess(){
		prepForm(myform.getForm());
	}
	
	function prepForm(form, action) {
		var myproj = projectidselector.getValue();	//Ext.getCmp('projects_projectid').getValue();
		var isfeatured = Ext.getCmp('projects_isfeatured').getValue();
		var iscomplete = Ext.getCmp('completed').getValue();
		if(iscomplete === false){
			projectcompleted.items.items[0].addListener('check', registerNotice);
		}
		projectidselector.disable();
		projectcompleted.show();
		proprietary.show();
		featureproject.show();
		Ext.getCmp('generalfields').show();
		Ext.getCmp('generalfields').doLayout();
		Ext.getCmp('savedata').enable();
		if(form.findField('application_on_file').getValue() != 'false') 
			Ext.getCmp('viewapplication').enable();
		else
			Ext.getCmp('viewapplication').disable();
		Ext.getCmp('deleteprojectbtn').enable();
		Ext.getCmp('resetprojsform').enable();
		Ext.getCmp('uploadreport').enable();
		Ext.getCmp('uploadimage').enable();
		Ext.getCmp('managecitationsbtn').enable();
		// Ext.getCmp('keywordbtn').enable();
		Ext.getCmp('projects_isfeatured').enable();
		Ext.getCmp('projects_projectid').disable();
		Ext.getCmp('uploadreport').enable();
		Ext.getCmp('completed').enable();
		if(Ext.getCmp('projects_reporttitle').getValue() != ''){
			Ext.getCmp('deletereport').enable();
		}
		if(isfeatured) {
			Ext.getCmp('attachmentmgr').enable();
			if(Ext.getCmp('projects_featureimage').getValue() != ''){
				Ext.getCmp('deleteimage').enable();
			}
			Ext.getCmp('featurepreview').enable();
		}
		Ext.getCmp('projects_title').focus(true, 50);
		datachanged = false;
	}
	
	function loadSelection() {
		myproj = Ext.getCmp('projects_projectid').getValue();
		var j = keywordgrid;
		j.store.baseParams.proj = myproj;
		myform.load({
			url: 'getProject.php',
			params: {projects_projectid: myproj},
			// waitMsg: "Retrieving project data.  Standby.",
			success: prepFormPreprocess,
			failure: function(resp) {
				var json = Ext.util.JSON.decode(resp.responseText);
				Ext.MessageBox.show({
					title: 'Data Error',
					msg: "Unable to communicate with remote server.  Check your internet connection and/or server status.",
					buttons: Ext.MessageBox.OK,
					icon: Ext.MessageBox.ERROR
				});
			}
		})
	}
	
	function updateProjectsStore(val){
		if(projectsStore.find('projects_projectid', myproj) == -1){
			var datarec = new Ext.data.Record.create([{name: 'projects_projectid', type: 'string'}]);
			var r = new datarec({projects_projectid: ''});
			r.set('projects_projectid', val);
			r.commit();
			projectsStore.addSorted(r);
		}		
	}
	
	function saveProject() {
		Ext.getCmp('projects_projectid').enable();
		var f = myform.getForm().getValues();
		if(needsNotice) notifyLisa();
		Ext.Ajax.request({
			url: 'postProject.php',
			// waitMsg: "Saving your changes to server....",
			params: f,
			success: function(resp) {
				var json = Ext.util.JSON.decode(resp.responseText);
				Ext.MessageBox.show({
					title: 'Info',
					msg: json.msg,
					buttons: Ext.MessageBox.OK
				});
				if(json.success) {
					datachanged = false;
					myproj = f.projects_projectid;
					Ext.getCmp('uploadreport').enable();
					// Ext.getCmp('keywordbtn').enable();
					Ext.getCmp('deleteprojectbtn').enable();
					// test if record already in store - add if new
					updateProjectsStore(myproj);
					prepForm(myform.getForm());
				}
			},
			failure: function(resp) {
				Ext.MessageBox.show({
					title: 'Error',
					msg: 'Failure communicating with remote server.  Check your internet connection and/or your server status.',
					buttons: Ext.MessageBox.OK
				});
			}
		})
	}
	
	function clearProjForm(focus) {
		focus = focus || false;
		projectcompleted.removeListener('check', notifyLisa);
		function clearForm(setfocus){
			myform.getForm().reset();
			// Ext.getCmp('keywordbtn').disable();
			//Ext.getCmp('featurefieldset').hide();
			Ext.getCmp('savedata').disable();
			Ext.getCmp('deleteprojectbtn').disable();
			Ext.getCmp('resetprojsform').disable();
			Ext.getCmp('uploadreport').disable();
			Ext.getCmp('uploadimage').disable();
			Ext.getCmp('managecitationsbtn').disable();
			Ext.getCmp('attachmentmgr').disable();
			Ext.getCmp('featurepreview').disable();
			Ext.getCmp('uploadreport').disable();
			Ext.getCmp('deletereport').disable();
			Ext.getCmp('generalfields').hide();
			projectcompleted.hide();
			featureproject.hide();
			proprietary.hide();
			//Ext.getCmp('projects_isfeatured').hide();
			//Ext.getCmp('completed').hide();
			//Ext.getCmp('projects_proprietary').hide();
			Ext.getCmp('projects_projectid').enable();
			if(setfocus) {
				myform.getForm().findField('projects_projectid').focus(false, 50);
			}
		}
		var form = myform;
		if(datachanged) {
			Ext.MessageBox.show({
				title: 'Unsaved Data Notice',
				msg: 'You have unsaved changes to the current data record.  Discard changes?',
				buttons: Ext.MessageBox.YESNOCANCEL,
				icon: Ext.MessageBox.NOTICE,
				fn: function(btn){
					if(btn == "yes") {
						clearForm(focus);
					} 
				}
			});
		} else {
			clearForm(focus);
		}
		// mykeywordsStore.removeAll();
	}
	
	var addPIRecord = function(rec){
		var datarec = new Ext.data.Record.create([{name: 'users_name', type: 'string'}]);
		var r = new datarec({users_name: ''});
		r.set("users_name", rec.users_name + ' - ' + rec.organization);
		piStore.addSorted(r);
		// check if the organization is also new and add it if needed.
		j = instituteStore.getAt(instituteStore.find('organization',rec.organization));
		if(j == -1){
			alert("A new organization also entered...");
		}
	}
	
	var addPIForm = function(btn, t){
		if(btn != "yes") {
			myform.getForm().findField('projects_institution').focus(false, 50);
			return;
		}
		var savebtn = new Ext.Button({
			id: 'savepidata',
			icon: 'extjs/resources/images/icons/database_save.png',
			text: 'Save PI',
			scope: this,
			handler: function() {
				var params = piform.getForm().getValues();
				// set your form variables into an object named params
				Ext.Ajax.request({
					url: 'postuser.php',
					params: params,
					success: function(resp){
						var json = Ext.util.JSON.decode(resp.responseText);
						if(json.success){
							Ext.MessageBox.show({
								title: 'Task Confirmed',
								msg: json.msg,
								buttons: Ext.MessageBox.OK,
								icon: Ext.MessageBox.INFO
							});
							myform.getForm().findField('projects_institution').setValue(piform.getForm().findField('users_organization').getValue());
							addPIRecord(params);
							// piStore.load();
							instituteStore.load();
							win.close();
						} else {
							Ext.MessageBox.show({
								title: 'Error',
								msg: json.msg,
								buttons: Ext.MessageBox.OK,
								icon: Ext.MessageBox.ERROR
							});
						}
					},
					failure: function(resp){
						Ext.MessageBox.show({
							title: 'Communication Error',
							msg: 'Error communicating with remote server.  Please check your internet connection and/or server status.',
							buttons: Ext.MessageBox.OK,
							icon: Ext.MessageBox.ERROR
						});
					}
				})
			},
			disabled: true
		});

		var cancelbtn = new Ext.Button({
			id: 'abortsavepidata',
			icon: 'extjs/resources/images/icons/cancel.png',
			text: 'Cancel',
			scope: this,
			handler: function(){
				piwin.close();
			}
		});
		
		var buttons = [savebtn, cancelbtn];

		var passwdevents = {blur: function() {
			var p = Ext.getCmp('dup_passwd');
			p.enable();
			p.focus();
		}};
		
		var pwevents = {blur: function() {
			var p = Ext.getCmp('users_passwd');
			var pw = p.getValue();
			var cp = Ext.getCmp('dup_passwd').getValue();
			if(pw != cp) {
				Ext.MessageBox.show({
					title: 'Password Mismatch',
					msg: 'The passwords you entered do not match each other.  Try again.',
					buttons: Ext.MessageBox.OK,
					icon: Ext.MessageBox.INFO
				});
				p.focus(true);
			}
		}};

		var checkUserID = function(t) {
			var params = {userid: t.getValue()};
			// set your form variables into an object named params
			Ext.Ajax.request({
				url: 'checkUserID.php',
				scope: this,
				params: params,
				success: function(resp){
					var json = Ext.util.JSON.decode(resp.responseText);
					if(!json.success){
						win.fireEvent('idisnotgood');
					} else {
						checkPIForm();
					}
				},
				failure: function(resp){
					Ext.MessageBox.show({
						title: 'Communication Error',
						msg: 'Error communicating with remote server.  Please check your internet connection and/or server status.',
						buttons: Ext.MessageBox.OK,
						icon: Ext.MessageBox.ERROR
					});
				}
			})
		}
		
		var checkPIForm = function() {
			if(piform.getForm().isValid()){
				savebtn.enable();
			}
		}
		
		var piform = new Ext.form.FormPanel({
			id: 'addnewpi',
			layout: 'form',
			buttonAlign: 'right',
			collapsible: false,
			width: 375,
			height: 200,
			bodyStyle: 'padding: 5px 10px;',
			defaults: {
				layout: 'form'
			} ,
			items: [{
				xtype: 'panel',
				border: false,
				bodyStyle: 'padding: 5px 0;',
				html: '<font style="font-size: 13px;" color="green">Complete all fields below and click SavePI to complete the addition.  New organizations will be automatically added.  User IDs will be checked for uniqueness.</font>'
			},{
				xtype: 'textfield',
				fieldLabel: 'Name',
				id: 'users_name',
				width: 235,
				allowBlank: false,
				maxLength: 49,
				listeners: {blur: checkPIForm},
				value: t.getValue()
			},{
				xtype: 'hidden',
				id: 'users_id',
				value: ''
			},{
				xtype: 'combo',
				id: 'users_organization',
				mode: 'local',
				fieldLabel: 'Organization',
				width: 235,
				allowBlank: false,
				maxLength: 100,
				selectOnFocus: true,
				triggerAction: 'all',
				editable: true,
				forceSelection: false,
				displayField: 'organization',
				store: instituteStore,
				listeners: {select: checkPIForm, blur: checkPIForm}
			},{
				xtype: 'hidden',
				id: 'users_usertype',
				value: 'PI'
			},{
				xtype: 'textfield',
				fieldLabel: 'Email Address',
				id: 'users_email',
				width: 235,
				allowBlank: true,
				maxLength: 100,
				listeners: {blur: checkPIForm},
				value: typeof r != "undefined" ? r.data.users_email:''
			},{
				xtype: 'textfield',
				fieldLabel: 'User ID',
				id: 'users_userid',
				maxLength: 20,
				allowBlank: false,
				listeners: {blur: checkUserID}
			},{
				xtype: 'hidden',
				id: 'addnew',
				value: true
			}],
			bbar: buttons
		});

		var win = new Ext.Window({
			title: 'Add Principal Investigator Panel',
			autoHeight: true,
			width: 405,
			bodyStyle: 'padding: 5px 10px;',
			closeAction: 'close',
			modal: true,
			items: [piform]
		});
		win.on('idisnotgood', function() {
			alert("The User ID you have entered is already in use by another user.  Please select a different ID for this user.");
			piform.getForm().findField('users_userid').focus();
		});
		win.doLayout();
		win.show();
		piform.getForm().findField('users_organization').focus(false, 50);
		win.addEvents('idisnotgood');
	}

	function checkPI(t){
		checkForm();
		datachanged = true;
		var pieces = t.getValue().split(" - ");
		var i = piStore.find('users_name', pieces[0]);
		if(i != -1) {
			myform.getForm().findField('projects_institution').focus(false, 50);
			return;
		}
		Ext.MessageBox.show({
			title: 'New PI Entry',
			msg: 'You have entered a PI that is not in the database.  Add to database now?',
			buttons: Ext.MessageBox.YESNO,
			icon: Ext.MessageBox.QUESTION,
			fn: function(btn) {
				addPIForm(btn, t);
			}
		});
		
	}
	
	function processPISel(t, r, i){
		datachanged = true;
		var s = r.data.users_name;
		var t = s.split(" - ");
		this.setValue(t[0]);
		s = Ext.getCmp('project').getForm().findField('projects_institution');
		s.setValue(t[1]);
		s.focus(false, 50);
		checkForm();
	}
	
	function enableFeaturesManager(){
		datachanged = true;
		var ischecked = Ext.getCmp('projects_isfeatured').getValue();
		if(ischecked ) {
			Ext.getCmp('attachmentmgr').enable();
			Ext.getCmp('featurepreview').enable();
		} else {
			Ext.getCmp('attachmentmgr').disable();
			Ext.getCmp('featurepreview').disable();
		}
	}
	
	function fileUpload(conf) {
		function changeName() {
			alert("The file name you are uploading already exists on the server.  Please rename your source file and reattach.");
			uploadwin.close();
		}
		
		var checkFileName = function(name, filetype){
			// var name = Ext.getCmp('File_Name').getValue();
			if(name == "") return;
			var dir = (filetype == "I") ? 'images':'reports';
			Ext.Ajax.request({
				url: 'checkFileName.php',
				params: {name: name, dir: dir},
				scope: this,
				success: function(resp){
					var json = Ext.util.JSON.decode(resp.responseText);
					if(!json.success){
						uploadwin.fireEvent('filenameisinuse');
					} else {
						return true;
					}
				},
				failure: function(){
					Ext.MessageBox.show({
						title: 'Communications Error',
						msg: 'A communication error has occurred.  Check your internet connection and/or server status.',
						buttons: Ext.MessageBox.OK,
						icon: Ext.MessageBox.ERROR
					});
				}
			})
		}
		
		var filetype = conf.type;
		var uploadform = new Ext.form.FormPanel({
	        header: false,
	        id: 'projuploadform',
	        fileUpload: true,
	        title: "File Upload Panel",
			labelWidth: 70,
	        bodyStyle: 'padding: 5px 5px 0',
	        width: 535,
	        defaults: {
				layout: 'form'
			},
	        items: [{
	            xtype: 'hidden',
	            name: "MAX_FILE_SIZE",
	            value: 100*1024*1024
			},{
				xtype: 'hidden',
				name: 'Type'
	        },{
	        	xtype: 'hidden',
	        	name: 'projectid'
	        },{
		        xtype: 'textfield',
		        fieldLabel: 'Select file',
				name: 'File_Name',
				allowBlank: false,
				maxLength: 150,
				width: 440,
		        inputType: 'file'
			}],
			buttons: [{
				text: 'Upload',
				handler: function() {
					var f = uploadform.getForm();
					f.findField('projectid').setValue(myform.getForm().findField('projects_projectid').getValue());
					f.findField('Type').setValue(conf.type);
					var parms = f.getValues();
					if (f.isValid())
					  f.submit({
						url: conf.url,
						params: parms,
						// waitMsg: 'Uploading file.  Standby...',
						waitTitle: 'File Upload',
						success: function(form, resp) {
							var res = Ext.util.JSON.decode(resp.response.responseText);
							if (res.success === false) {
								Ext.MessageBox.show({
									title: 'Error Uploading',
									msg: res.msg,
									buttons: Ext.MessageBox.OK,
									icon: Ext.MessageBox.ERROR
								});
							} else {
								switch(res.type){
									case "I":
										Ext.getCmp('projects_featureimage').setValue(res.filename);
									break;
									case "R":
										Ext.getCmp('projects_reporttitle').setValue(res.filename);
									break;
								}
								Ext.MessageBox.show({
									title: "Upload Successful",
									msg: res.msg,
									buttons: Ext.MessageBox.OK
								});
							}
							uploadwin.close();
						},
						failure: function(form, resp) {
							var res = Ext.util.JSON.decode(resp.response.responseText);
							Ext.MessageBox.show({
								title: "Communication Error",
								msg: res.msg,
								buttons: Ext.MessageBox.OK,
								icon: Ext.MessageBox.ERROR
							});
						}
					});
				}
			},{
				text: 'Reset',
				handler: function() {
					uploadform.getForm().setValues({File_Name: ''})
				},
				value: 'reset'
			},{
				text: 'Cancel',
				handler: function() {
					uploadwin.close();
				}
			}]
		});
		
		var uploadwin = new Ext.Window({
			id: 'uploadwin',
	        title: conf.title,
	        modal: true,
	        height: 120,
	        closeAction: 'close',
	        border: true,
	        layout: 'form',
	        width: 560,
	        plain: false,
	        bodyStyle: 'padding-top: 10px; padding-left: 5px;',
	        closable: true,
	        items: uploadform
		});
		uploadwin.addEvents('filenameisinuse');
		uploadwin.on('filenameisinuse', changeName);
		uploadwin.show();
	};
	
	var cfgobj = {
		title: 'Project Management',
		//layout: 'anchor',
		// layout: 'fit',
		id: 'projectformwr',
		frame: true,
		border: true,
		bodyStyle: 'padding: 15px;',
		style: 'padding: 10px;',
		defaults: {
			//anchor: '100%'
		},
		items: [ myform ],
		buttonAlign: 'center',
		buttons: [{
			xtype: 'button',
			icon: 'extjs/resources/images/icons/database_save.png',
			id: 'savedata',
			disabled: true,
			text: 'Save Data',
			handler: saveProject
		},{
			xtype: 'button',
			icon: 'extjs/resources/images/icons/page_white.png',
			id: 'resetprojsform',
			disabled: true,
			text: 'Clear Form',
			handler: function() {
				clearProjForm(true);
			}
		},
			reportbtns
		,{
			id: 'attachmentmgr',
			text: 'Features Manager',
			icon: 'extjs/resources/images/icons/folder_table.png',
			disabled: true,
			handler: function() {
				Ext.getCmp('featurefieldset').show();
			}
		},{
			id: 'featurepreview',
			text: 'Preview Feature',
			icon: 'extjs/resources/images/icons/folder_link.png',
			disabled: true,
			handler: function() {
				var panel = new Ext.Panel({
					title: 'ICCI FEATURED PROJECT',
					cls: 'centerpanel',
					frame: false,
					border: false,
					width: 398,
					collapsible: false,
					autoLoad: 'getFeaturedProject.php?preview='+myproj
				});
		 
				var win = new Ext.Window({
					title: 'Featured Article Preview',
					width: 425,
					height: 550,
					autoScroll: true,
					closeAction: 'close',
					modal: true,
					items: panel
				});
		
				win.doLayout();
				win.show();
			}
		},
			managecitationsbtn,
			viewapplicationbtn,
		{
			xtype: 'button',
			id: 'deleteprojectbtn',
			icon: 'extjs/resources/images/icons/database_delete.png',
			disabled: true,
			text: 'Delete Project',
			handler: deleteProject
		}]
	}//); 
	Ext.apply(cfgobj, cfg);
	projectForm.superclass.constructor.call(this, cfgobj);
	
	this.on('activate', function(t){
		if(projectsStore.getCount() == 0) projectsStore.load();
		if(instituteStore.getCount() == 0) instituteStore.load();
		if(piStore.getCount() == 0) piStore.load();
		// if(managerStore.getCount() == 0) managerStore.load();
		datachanged = false;
	});
}
Ext.extend(projectForm, Ext.Panel);

