tinyMCE.init({
	mode : "none",
	theme : "advanced",
	button_tile_map:true,
	width : "355",
	theme_advanced_buttons1 : "bold,italic,underline,separator,forecolor,separator,bullist,numlist,undo,redo,link,unlink,separator,code",
	theme_advanced_buttons2 : "",
	theme_advanced_buttons3 : "",
	theme_advanced_toolbar_location : "top",
	theme_advanced_toolbar_align : "left",
	extended_valid_elements : "a[name|href|target|title|onclick|class],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],span[class|align|style]"
});

var site={
	ajaxPath: '/Biotech/utilities/ajax.asp?action=',
	
	init: function () {
		site.cookie = new Hash.Cookie('user', {duration:365});
		site.menu.init();
		site.search.init();
		site.feedbackTab.init();
		site.feedbackRadios.init();
		site.recommendation.init();
		site.page.init();
		},
	menu: {
		ul: $('adminMenu') ? $('adminMenu') : new Element('ul', {id:'adminMenu'}),
		init: function () {
			// if account exists
			if ($('loggedin').value > 0) {
				site.menu.draw('loggedIn');
				// if a reviewer
				if ($('loggedin').value == '1') {
					if ($('approveBtn')) {
						$('approveBtn').addEvent('click', function () {
							new Ajax(site.ajaxPath + 'UpdateReviewerApprovalStatus', {
								postBody:{
									paperID:$('paperID').value,
									approval: 1
								},
								onComplete: function(response) {
									$('approveBtn').setStyle('display', 'none');
									$('disapproveBtn').setStyle('display', 'block');
								},
								onFailure: function (request) {
									alert("An error has occurred");
								}
							}).request();
						});
					}
					if ($('disapproveBtn')) {
						$('disapproveBtn').addEvent('click', function () {
							new Ajax(site.ajaxPath + 'UpdateReviewerApprovalStatus', {
								postBody:{
									paperID:$('paperID').value,
									approval: 0
								},
								onComplete: function(response) {
									$('disapproveBtn').setStyle('display', 'none');
									$('approveBtn').setStyle('display', 'block');
								},
								onFailure: function (request) {
									alert("An error has occurred");
								}
							}).request();
						});
					}
				} else {
					if ($('approveBtn'))	$('approveBtn').remove();
					if ($('disapproveBtn'))	$('disapproveBtn').remove();
				}
				// if more privileged than a reviewer
				if ($('loggedin').value > 1) {
					$$('.paperList li').each(function (paper) {
						paper.adopt(new Element('a').setText('Edit').addClass('editBtn').addEvent('click', function() {
							site.paperManagement.init(paper.id);
						}));
					});
					$$('.paperTitle').adopt(new Element('a').setText('Edit').addClass('editBtn').addEvent('click', function () {
						site.paperManagement.init($$('.paperTitle')[0].id);
					}));
				} else {
					$$('.editBtn').each(function (button) {
						button.remove();
					});
				}
			} else {
				if ($('approveBtn'))	$('approveBtn').remove();
				if ($('disapproveBtn'))	$('disapproveBtn').remove();
				$$('.editBtn').each(function (button) {
					button.remove();
				});
				site.menu.draw('login');
			}
		},
		draw: function (state) {
			if (state == 'login') {
				site.menu.ul.empty();
				site.menu.ul.adopt(new Element('li').adopt(new Element('a', {id:'initLogin'}).setText('Admin Login'	)));
				site.menu.activate();
			} else {
				site.menu.ul.empty();
				site.menu.ul.adopt(new Element('li').adopt(new Element('a', {id:'initLogout'}).setText('Logout')));
				site.menu.ul.adopt(new Element('li').adopt(new Element('a', {id:'initViewAllPapers'}).setText('View All Papers')));
				if ($('loggedin').value > 1) {
					site.menu.ul.adopt(new Element('li').adopt(new Element('a', {id:'initAddPaper'}).setText('Add Paper')));
//					site.menu.ul.adopt(new Element('li').adopt(new Element('a', {id:'initAddCategory'}).setText('Add Category')));
				}
				site.menu.activate();
			}
		},
		activate: function () {
			if ($('initLogin')) 			$('initLogin').addEvent('click', site.user.login);
			if ($('initLogout'))			$('initLogout').addEvent('click', site.user.logout);
			if ($('initViewAllPapers')) 	$('initViewAllPapers').addEvent('click', site.paperListing.init);
			if ($('initAddPaper')) 			$('initAddPaper').addEvent('click', site.paperManagement.init);
		}
	},
	user: {
		login: function () {
			var popup = new Popup({
				width:270,
				overlay:true,
				onLoading: function () {
					var form = new Form('loginForm', {
						submit:'Login',
						onSubmit: function (e) {
							new Event(e).stop();
							new Ajax(site.ajaxPath + 'SelectUserLogin', {
								postBody: {
									username: this.fields.Username.value,
									password: this.fields.Password.value
								},
								onComplete: function(response) {
									if (!response) {
										new Fx.Style(popup, 'height', {
											onComplete: function () {
												form.adopt(new Element('p', {'class':'error'}).setText('Not recognised'));
											}
										}).start(parseInt(popup.getStyle('height')) + 24);
									} else {
										if ($('loggedin'))	$('loggedin').value = response;
										site.cookie.extend(this.options.postBody);
										site.menu.init();
										popup.deactivate();
									}
								},
								onFailure: function(request) {
									alert(request.responseText);
								}
							}).request();
						}
					});
						form.appendFieldset(new Fieldset('Login')).appendFields([
							new Field('Username'),
							new Field('Password')
						]);
					
					if (site.cookie.get('username')) 	form.fields['Username'].setValue(site.cookie.get('username'));
					if (site.cookie.get('password')) 	form.fields['Password'].setValue(site.cookie.get('password'));
					
					popup.adopt(form).setStyle('paddingTop', 25);
					popup.removeLoader();
				}
			}).activate();
		},
		logout: function () {
			new Ajax(site.ajaxPath + 'Logout', {
				postBody:{},
				onComplete: function(response) {
					if (!response) {
						alert('Error: not logged out');
					} else {
						if ($('loggedin'))	$('loggedin').value = '0'
						site.menu.init();
					}
				},
				onFailure: function(request) {
					alert(request.responseText);
				}
			}).request();
		},
		register: function() {}
	},
	paperManagement: {
		data:{},
		init: function (id) {
			var popup = site.paperManagement.popup = new Popup({
				width:680,
				overlay:true,
				onLoading: function () {
					popup.consume(site.paperManagement.build(id), {
						onComplete: site.paperManagement.activate
					});
				}
			}).activate();
		},
		build: function (id) {
			// get data
			[	{name:'Crops', procedure:'SelectSearchCriteria'},
				{name:'Traits', procedure:'SelectSearchCriteria'},
				{name:'Countries', procedure:'SelectSearchCriteria'},
				{name:'Regions', procedure:'SelectSearchCriteria'},
				{name:'Categories', procedure:'SelectKeyMessages'},
				{name:'Reviewers', procedure:'SelectReviewers'}
			].each(function (dataType) {
				site.paperManagement.data[dataType.name] = Json.evaluate(new Ajax(site.ajaxPath + dataType.procedure, {
					postBody: {type:dataType.name},
					async:false
				}).request().transport.responseText).records;
				site.paperManagement.data[dataType.name].each(function (option) {
					option.value = option.id;
					option.text = unescape($pick(option.name, option.category));
				});
			});
			
			site.paperManagement.data.Categories.push({
				value:'13',
				text:'Yield'
			});
			
			var form = site.paperManagement.form = new Form('paperManagement', {
				submit:'Save',
				onSubmit: site.paperManagement.submit
			}).setProperties({enctype:'multipart/form-data', method:'post'});		
				form.appendFieldset(new Fieldset('Stage One')).appendFields([
					new Field({label:false, id:'id', type:'hidden'}),
					new Field({label:'Title', maxLength:255}),
					new Field({label:'Author(s)', maxLength:255}),
					new Field({label:'Source', maxLength:255}),
					new Field({label:'Publish Year', maxLength:4})
						.control.setStyle('width', '50px').getParent()
						.adopt(new Element('span').setText(' (YYYY)').setStyles({position:'relative', top:'-2px', color:'#999'})),
					new Field ({label:'Supporting Document', type:'checkbox'})
						.control.setStyle('width', 16).getParent()
						.label.setStyles({width:150, top:2}).getParent()
						.setStyles({position:'relative', top:-26, float:'right'}),
					new Field({label:'Abstract', type:'textarea'})
						.label.setStyles({position:'relative', top:'20px'}).getParent(),
					new Field({label:'Key Facts', type:'textarea'})
						.label.setStyles({position:'relative', top:'20px'}).getParent(),
									new Field({label:'Categories/ Impact Areas', ref:'Categories', type:'select', multiple:'true'})
										.control.setStyles({width:'360px', height:'120px'}).getParent()
										.pushOptions(site.paperManagement.data.Categories),
					new Field({label:'Tags'}),
					new Field({label:'Web Link', maxLength:500})
//						.control.setText('http://www.').getParent()
				]);
				form.appendFieldset(new Fieldset('Stage Two')).appendFields([
					new Field({label:'Owner', maxLength:50}).addClass('owner'),
					new Field({label:false, id:'date1', maxLength:10}).addClass('date').setStyle('width', 94).control.addClass('date').getParent(),
					new Field({label:false, id:'date2', maxLength:10}).addClass('date').control.addClass('date').getParent(),
					new Field({label:'Status', type:'select'}).addClass('status')
						.pushOptions([
							{value:0, text:'Not Granted'},
							{value:1, text:'Granted'},
							{value:2, text:'Rejected'}
						]),
					new Field({label:false, id:'deletePDF', type:'button'}),
					new Field({label:false, id:'upload', name:'upload', type:'file'})
						.addClass('upload'),
					new Field({label:false, id:'filename', type:'hidden'}),
					new Field({label:'Priority', type:'select'})
						.pushOptions([
							{value:'', text:'None'},
							{value:0, text:'High'},
							{value:1, text:'Medium'},
							{value:2, text:'Low'}
						]),
					new Field({label:'Reviewers', type:'select', multiple:'true'})
						.control.setStyle('height', '120px').getParent()
						.pushOptions(site.paperManagement.data.Reviewers)
						.addEvents({
							'contextmenu': function(e) {
								e = new Event(e).stop();
								var option = $(e.target);
								if (option.selected) {
									new Element('ul', {'class':'contextMenu'})
										.adopt(new Element('li').setHTML('<a>Approve</a>'))
										.adopt(new Element('li').setHTML('<a>Disapprove</a>'))
										.adopt(new Element('li').setHTML('<a>Remove Status</a>'))
										.addEvent('click', function (e) {
											e = new Event(e).stop();
											var approval = $(e.target).getText();
											var approvalCode;
											switch (approval) {
												case 'Approve': approvalCode = 1; break;
												case 'Disapprove': approvalCode = 0; break;
												case 'Remove Status': approvalCode = null; break;
											}
											var reviewerID = option.value;
											new Ajax(site.ajaxPath + 'UpdateReviewerApprovalStatus', {
												postBody:{
													paperID: form.fields["id"].getValue(),
													approval: approvalCode,
													reviewerID: reviewerID
												},
												onComplete: function(response) {
													e.target.getParent().getParent().remove();
													var text = option.getText();
													if (text.contains('('))	text = text.substring(0, text.indexOf('(')-1);
													switch (approval) {
														case 'Approve': action = ' (Approved)'; break;
														case 'Disapprove': action = ' (Disapproved)'; break;
														case 'Remove Status': action = ''; break;
													}
													option.setText(text + action);
												}
											}).request();
										})
										.setStyles({
											left: e.page.x,
											top: e.page.y
										})
										.moveToTop()
										.injectInside(document.body);

									return false;
								}
							}
						}),
					new Field({label:'Comments', type:'textarea'}),
					new Field({label:false, id:'PublishState', type:'hidden'}),
					new Field({label:false, type:'button', text:'Disapprove'})
						.control.setStyles({marginTop: '10px', display:'none'})
						.addEvent('click', function() {
							var approved = (!(String(this.getStyle('backgroundImage')).indexOf('re') == -1));
							var state = approved? 0 : 1;
							
							new Ajax(site.ajaxPath + 'UpdatePaperPublishState', {
								postBody: {
									id: form.fields["id"].getValue(),
									publishState: state
								},
								onComplete: function (response) {
									this.setStyle('backgroundImage', 'url(/Biotech/images/' + (approved? 'dis' : 're') + 'approve.gif)');
									form.fields["Publish"].setStyle('backgroundImage', 'url(/Biotech/images/publish.gif)');
									form.fields["PublishState"].setValue(state)
								}.bind(this)
							}).request();
						})
						.getParent(),
					new Field({label:false, type:'button', text:'Publish'})
						.control.setStyle('display', 'none')
						.addEvent('click', function() {
							var published = (!(String(this.getStyle('backgroundImage')).indexOf('un') == -1));
							var state = published? 0 : 2;
							
							new Ajax(site.ajaxPath + 'UpdatePaperPublishState', {
								postBody: {
									id: form.fields["id"].getValue(),
									publishState: state
								},
								onComplete: function (response) {
									this.setStyle('backgroundImage', 'url(/Biotech/images/' + (published? '' : 'un') + 'publish.gif)');
									form.fields["PublishState"].setValue(state)
								}.bind(this)
							}).request();
						})
						.getParent()
				]);
				new Element('a', {id:'archiveBtn'}).setText('Archive')
					.setStyles({width:'180px', textAlign:'center', display:'block', margin:'2px,0px,0px,7px'})
					.addEvent('click', function () {
						// an archived paper will have 'De-' in the string, thus returning false for the inner clause, thus returning true for the entire clause
						var archived = (!(String(this.getText()).indexOf('De-') == -1));
						var state = archived? 2 : 3
							
						new Ajax(site.ajaxPath + 'UpdatePaperPublishState', {
							postBody: {
								id: form.fields["id"].getValue(),
								publishState: state
							},
							onComplete: function (response) {
								this.setText(archived? 'Archive' : 'De-Archive');
								form.fields["PublishState"].setValue(state)
							}.bind(this)
						}).request();
					})
					.injectAfter(form.fields.Publish);
				
				form.appendFieldset(new Fieldset('Stage Three')).appendFields([
					new Field({label:'Crops', type:'select', multiple:'true'}).pushOptions(site.paperManagement.data.Crops),
					new Field({label:'Traits', type:'select', multiple:'true'}).pushOptions(site.paperManagement.data.Traits),
					new Field({label:'Countries', type:'select', multiple:'true'}).pushOptions(site.paperManagement.data.Countries),
					new Field({label:'Regions', type:'select', multiple:'true'}).pushOptions(site.paperManagement.data.Regions)
				]);
			
			return site.paperManagement.populate(form, id);
		},
		populate: function (form, id) {
			if (typeof(id) != "string") return form;
			
			var paper = Json.evaluate(new Ajax(site.ajaxPath + 'SelectPaper', {
				postBody: {id:id},
				async:false
			}).request().transport.responseText).records[0];
			
			if (paper.Filename.nonNull() != '')	{
				form.fileExists = true;
				form.fields.upload.getParent().setStyle('display', 'none');
				form.fields.deletePDF.setStyle('display', 'block');
			}
			
			form.fields["id"].setValue(id);
			form.fields["filename"].setValue(paper.Filename);
			form.fields["Title"].setValue(paper.Title);
			form.fields["Author(s)"].setValue(paper.Author);
			form.fields["Source"].setValue(paper.Source);
			form.fields["Publish Year"].setValue(paper.PublishDate);
			form.fields["Supporting Document"].checked = (paper.supporting_only == "true");
			form.fields["Abstract"].setValue(paper.Abstract);
			form.fields["Key Facts"].setValue(paper.Summary);
			form.fields["Tags"].setValue(paper.Tags.map(function (tag) {return tag.name;}).join(', '));
			form.fields["Web Link"].setValue(paper.URL);
			form.fields["Comments"].setValue(paper.Comments);
			form.fields["Owner"].setValue(paper.Owner);
			form.fields["date1"].setValue(new Date(paper.date1).prettify());
			form.fields["date2"].setValue(new Date(paper.date2).prettify());
			form.fields["PublishState"].setValue(paper.PublishedState);
			
			paper.Impactareas.each(function (impactArea) {
				if (impactArea.name == 'Yield')	paper.Categories.push({id:'13', category:'Yield'});
			});
			
			['Categories', 'Crops','Traits','Countries','Regions'].each(function (dataType) {
				paper[dataType].each(function (dataObj) {
					$A(form.fields[dataType].options).each(function (option) {
						if (dataObj.id == option.value) {
							option.selected = true;
						}
					});
				});
			});
			
			$A(form.fields.Reviewers.options).each(function (option) {
				if ( (paper.Reviewer1 == option.value) || (paper.Reviewer2 == option.value) ) {
					form.fields.Reviewers.multiple = true;
					option.selected = true;
					form.fields.Reviewers.multiple = true;
					if ( (paper.Reviewer1 == option.value) && (paper.Reviewer1Approval == 'true') ) {
						option.appendText(' (Approved)');
					}
					if ( (paper.Reviewer1 == option.value) && (paper.Reviewer1Approval == 'false') ) {
						option.appendText(' (Disapproved)');
					}
					if ( (paper.Reviewer2 == option.value) && (paper.Reviewer2Approval == 'true') ) {
						option.appendText(' (Approved)');
					}
					if ( (paper.Reviewer2 == option.value) && (paper.Reviewer2Approval == 'false') ) {
						option.appendText(' (Disapproved)');
					}
				}
			});
			
			if (paper.URL != 'null') {
				form.fields["Web Link"].setStyle('display', 'none');
				var text = paper.URL.length > 47 ? paper.URL.substring(0, 47) + '...' : paper.URL;
				var link = new Element('a')
					.setProperty('href', paper.URL)
					.setText(text)
					.setStyles({
						position:'relative',
						top:1,
						marginRight:3
					})
					.addEvent('click', function (e) {
						new Event(e).stop();
						var newWindow = window.open(paper.URL, '_blank');
							newWindow.focus();
					})
					.injectAfter(form.fields["Web Link"]);
				new Element('button')
					.setText('Edit')
					.addEvent('click', function () {
						link.remove();
						this.remove();
						form.fields["Web Link"].setStyle('display', '');
					})
					.injectAfter(link);
			}
			
			$A(form.fields.Status.options).each(function (option) {
				if (paper.PermissionStatus == option.value) {
					option.selected = true;
				}
			});
			$A(form.fields.Priority.options).each(function (option) {
				if (paper.Priority == option.value) {
					option.selected = true;
				}
			});
			
			if (paper.PublishedState == '1') form.fields["Disapprove"].setStyle('backgroundImage', 'url(/Biotech/images/reapprove.gif)');
			form.fields["Disapprove"].setStyle('display', 'block');
			
			if (paper.PublishedState == '2') form.fields["Publish"].setStyle('backgroundImage', 'url(/Biotech/images/unpublish.gif)');
			form.fields["Publish"].setStyle('display', 'block');

//				if (paper.PublishedState == '3') $('archiveBtn').setText('De-Archive');
//				$('archiveBtn').setStyle('display', 'block');

			return form;
		},
		activate: function () {
			$$('input.date').each(function (input) {
				new DatePicker(input);
			});
			
			tinyMCE.execCommand('mceAddControl', false, 'abstract');
			tinyMCE.execCommand('mceAddControl', false, 'keyFacts');
/*			
			if (!site.paperManagement.form.fileExists) {
				new FancyUpload($('upload'), {
					url:'http://croplife.intraspin.com/BioTech/utilities/plugins/FancyUpload/upload.asp',
					swf:'/BioTech/utilities/plugins/FancyUpload/Swiff.Uploader.swf',
					types: {'PDFs (*.pdf)': '*.pdf'},
					cssStyles:{
						background:'url(utilities/plugins/FancyUpload/images/browse.gif) no-repeat',
						width:'81px',
						height:'28px',
						border:'none',
						paddingTop:'26px',
						margin:'3px 0px 10px 0px'
					},	
					multiple:false,
					instantStart:true,
					queueList:'queue',
					onComplete: function () {},
					onAllComplete: function () {
						$('filename').setValue(this.fileList[0].name);
					},
					onError: function () {
						alert("An error has occurred, and your file has not been uploaded.");
					}
				});
				var pos = site.paperManagement.popup.getPositionedOffset();
				// error in IE, but hidden and not required (only for FF)
				$('Swiff1').setStyles({
					position:'absolute', 
					top:pos.y, 
					left:pos.x
				});
//				$('upload').getParent().adopt($('Swiff1'));
//				$('Swiff1').injectAfter('upload');
			}
*/
			$('deletePDF').addEvent('click', function (e) {
				new Event(e).stop();
				new Ajax(site.ajaxPath + 'DeletePDF', {
					postBody:{
						filename: $('filename').getValue()
					},
					onComplete: function(response) {
						$('filename').setValue('');
						$$('li.upload').setStyle('display', '');
						this.setStyle('display', 'none');
					}.bind(this),
					onFailure: function(request) {
						alert(request.responseText);
					}
				}).request();
			});
			new Element('iframe', {id:'PDFiFrame', name:'PDFiFrame'})
				.setStyle('display', 'none')
				.addEvent('load', function () {
					var body = $((this.contentDocument || this.contentWindow.document).activeElement);
					var response = body.getText();
					if (response.toLowerCase().contains('.pdf')) {
						$('filename').setValue(response);
						$('upload').getParent().setStyle('display', 'none');
						$('deletePDF').setStyle('display', 'block');
/*						new Element('button').addClass('deletePDF').setText('Delete')
							.addEvent('click', function (e) {
								new Event(e).stop();
								new Ajax(site.ajaxPath + 'DeletePDF', {
									postBody:{
										filename: $('filename').getValue()
									},
									onComplete: function(response) {
										$('filename').setValue('');
										$('upload').getParent().setStyle('display', '');
										this.remove();
									}.bind(this),
									onFailure: function(request) {
										alert(request.responseText);
									}
								}).request();
							})
							.injectAfter($('upload').getParent());
*/
					}
					site.paperManagement.form.removeProperty('target');
				})
				.injectInside(document.body);
			$('upload').setProperty('name', 'upload');
			new Element('div').setStyles({height:32, marginLeft:35, background:'url(/Biotech/images/browse.gif) no-repeat'}).injectBefore('upload').adopt('upload');
			$('upload').setOpacity(0).setStyle('visibility', 'visible');
			$('upload').addEvent('change', function () {
				site.paperManagement.form.setProperties({target:'PDFiFrame', action:'/Biotech/utilities/upload.asp'}).submit();
			});
		},
		submit: function (e) {
			if (site.paperManagement.form.getProperty('target') == 'PDFiFrame')	return;
			new Event(e).stop();
			
//			alert(tinyMCE.getContent("abstract"));
			
			tinyMCE.triggerSave(true,true);
			tinyMCE.execCommand('mceRemoveControl', false, 'abstract');
			tinyMCE.execCommand('mceRemoveControl', false, 'keyFacts');
			

			
			// Gather Parameters
			var params={
				id: this.fields["id"].getValue(),
				filename: this.fields["filename"].getValue(),
				title: this.fields["Title"].getValue(),
				author: this.fields["Author(s)"].getValue(),
				source: this.fields["Source"].getValue(),
				publishdate: this.fields["Publish Year"].getValue(),
				supporting_only: this.fields["Supporting Document"].checked ? 1 : 0,
				abstract: this.fields["Abstract"].getValue(),
				keyfacts: this.fields["Key Facts"].getValue(),
				tags: this.fields["Tags"].getValue().split(',').map(function (tag) {return tag.trim();}),
				url: this.fields["Web Link"].getValue(),
				owner: this.fields["Owner"].getValue(),
				date1: this.fields["date1"].getValue().sqlDate(),
				date2: this.fields["date2"].getValue().sqlDate(),
				status: this.fields["Status"].getValue(),
				priority: this.fields["Priority"].getValue(),
				comments: escape(this.fields["Comments"].getValue()),
				publishstate: this.fields["PublishState"].getValue()
			}

			if ( (!( (params.publishdate > 1900) && (params.publishdate < 2020) )) && (params.publishdate != '') ) {
				this.fields["Publish Year"].setStyle('border', '1px solid red');
				this.fields["Publish Year"].getNext().setText('Please format this year correctly.').setStyles({color:'red', marginLeft:'10px'}).injectAfter(this.fields["Publish Year"]);
				new Fx.Scroll(window, {
					duration: 200
				}).toElement(this.fields["Publish Year"]);
				return false;
			}
			
			var complexFields = ["Categories", "Crops", "Traits", "Countries", "Regions", "Reviewers"];
			complexFields.each(function (name) {
				params[name]=[];
				$A(this.fields[name].options).each(function (option) {
					params[name].push({id:option.value, name:option.text, selected:option.selected});
				});
			}.bind(this));
			

//			var utf = new RegExp('([\09\0A\0D\x20-\x7E]|[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|\xED[\x80-\x9F][\x80-\xBF]|\xF0[\x90-\xBF][\x80-\xBF]{2}| [\xF1-\xF3][\x80-\xBF]{3}|\xF4[\x80-\x8F][\x80-\xBF]{2})*$');
//			if (Json.toString(params).match(utf)) {
//				alert(true);
//			} else {
//				alert(false);
//			}
			
			new Ajax(site.ajaxPath + 'ManagePaper', {
				postBody:{
					paperJSON: Json.toString(params)
				},
				onComplete: function(response) {
					if (!response) {
						this.adopt(new Element('p', {'class':'error'}).setText('An error has occurred.'));
					} else {
						// Update Paper Listing if it's open
						if ($('paperListing')) {
							var paper = Json.evaluate(new Ajax(site.ajaxPath + 'SelectPaper', {
								postBody: {id:params.id},
								async:false
							}).request().transport.responseText).records[0];
							
							var reviewers = '';
							// get the names
							$A($('reviewers').options).each(function (option) {
								var test = 'test';
								if (paper.Reviewer1 == option.value)	paper.Reviewer1 = option.text;
								if (paper.Reviewer2 == option.value)	paper.Reviewer2 = option.text;
							});
							// remove the approval note
							if (paper.Reviewer1.contains('('))	paper.Reviewer1 = paper.Reviewer1.substring(0, paper.Reviewer1.indexOf('(')-2);
							if (paper.Reviewer2.contains('('))	paper.Reviewer2 = paper.Reviewer2.substring(0, paper.Reviewer2.indexOf('(')-2);
							// prepare the text for the cell
							if (paper.PublishedState == 0 && paper.PermissionStatus != 2) {
								reviewers = [];
								if (paper.Reviewer1Approval == 'false')	{reviewers.push(paper.Reviewer1);}
								if (paper.Reviewer2Approval == 'false')	{reviewers.push(paper.Reviewer2);}
								reviewers = (reviewers.length == 0) ? '' : 'Awaiting ' + reviewers.length + ': ' + reviewers;
							}
							// prepare the filename/url link
							var href = '';
							var text = '';
							if (paper.Filename != '' && paper.Filename != 'null') {
								href = paper.Filename;
								text = paper.Filename;
							} else if (params.URL != '' && params.URL != 'null') {
								href = params.url;
								text = params.url;
							}
							if (text.length > 20) text = text.substring(0, 20) + '...';
							var link = text.length == 0 ? '' : '<a href="' + href + '">' + text + '</a>';
							
							// update the appropriate row
							$A($('paperListing').body.childNodes).each(function (tr) {
								if (tr.childNodes[0].innerHTML == params.id) {
/* supporting */							$(tr).getFirst().getNext().setText(paper.supporting_only == "true" ? 'Yes' : 'No').getNext()
/* title */									.getFirst().setText(paper.Title).getParent().getNext()
/* date */									.setText(paper.PublishDate).getNext()
/* author */								.setText(paper.Author).getNext()
/* priority */								.setText((paper.PublishedState != 0) ? '' : ((paper.Priority != '') ? ['High', 'Medium', 'Low'][paper.Priority] : '')).getNext()
/* status */								.setText(['Not Granted', 'Granted', 'Rejected'][paper.PermissionStatus]).getNext()
/* reviewers */								.setText(reviewers).getNext()
/* state */									.setText(['In Review', 'Disapproved', 'Published', 'Archived'][paper.PublishedState]).getNext()
/* filename */								.setHTML(link);
								}
							});
						}
						site.paperManagement.popup.deactivate();
/*						Alert
						var alert = site.paperManagement.popup = new Popup({
							width:300,
							onLoading: function () {
								alert.consume(new Element('p').setText(unescape(response)));
							}
						}).activate();
*/
					}
				}.bind(this),
				onFailure: function(request) {
					alert(request.responseText);
				}
			}).request();
		}
	},
	paperListing: {
		init: function () {
			var popup = new Popup({
				width:980,
				draggable:false,
				onLoading: function () {
					site.paperListing.draw(popup);
				}
			}).activate();
		},
		draw: function (popup) {
			new Ajax(site.ajaxPath + 'SelectAdminPaperTable', {
				postBody:{
					includeDisapprovedArchived: true
				},
				onComplete: function(response) {
					if (!response) {
						alert('error');
					} else {
						var start = new Date().getTime();
						var response = Json.evaluate(response);
/*						(minorly here) Faster String Concatenation
						var t=[]
							t[0] = '<table id="paperListing">'
							t[1] = '<thead><tr><th>CLI</th><th>Title</th><th>Year</th><th>Author</th><th>Priority</th><th>Permission</th><th>Awaiting...</th><th style="width:110px">Publish State</th><th>Filename</th></tr></thead>';
							t[2] = '<tbody>';
							t[3] = Json.evaluate(response).html;
							t[4] = '</tbody></table>';
						popup.consume(new Element('div').setHTML(t.join('')));
*/
						var header = '<thead><tr><th>CLI<div class="filterBtn"></div></th><th>Supporting?<div class="filterBtn"></div></th><th>Title</th><th>Year<div class="filterBtn"></div></th><th>Author<div class="filterBtn"></div></th><th>Priority<div class="filterBtn"></div></th><th>Permission<div class="filterBtn"></div></th><th>Awaiting...<div class="filterBtn"></div></th><th style="width:110px">Publish State<div class="filterBtn"></div></th><th>Filename</th></tr></thead>';
						
						var div = new Element('div');
						popup.consume(div.setHTML('<table id="paperListing">' + header + '<tbody>' + response.html + '</tbody></table>'));
						
						var data = Json.evaluate(response.data);
						var paperListing = new Table('paperListing', {filters:data}).activate();
						
						$$('#paperListing tbody').addEvent('mousedown', function (e) {
							var e = new Event(e);
							var el = e.target;
							var tag = $(el).getTag();
							while (tag != 'td')	{el = el.getParent(); tag = el.getTag();}
							if (el.hasClass('title')) {
								var id = el.getParent().id;
								if ($('loggedin').value > 1 && !e.control) {
									site.paperManagement.init(id);
								} else {
									window.location = '/paper.asp?id=' + id;
								}
							}
							if (el.hasClass('filename')) {
								var el = el.getFirst();
								var iframe = new Element('iframe', {src:el.href}).injectInside(document.body);
//								var newWindow = window.open(el.href, '_blank');
//									newWindow.focus();
//								return false;
//								window.location = el.href;							
							}
						});
//						new Element('a').setText('Load Filters').injectBefore('paperListing').addEvent('click', function () {$('paperListing').makeFilterable()});
//						alert("Total duration: " + ((new Date().getTime() - start) / 1000) + " seconds");
					}
				},
				onFailure: function (request) {
					alert(request.responseText);
				}
			}).request();
		}
	},
	search: {
		init: function() {
			this.elements = $$('#advancedSearch input, #advancedSearch select');
			this.elements.addEvent('change', this.execute.bind(this));
			$$('#advancedSearch input').addEvent('keyup', this.execute.bind(this));
		},
		collectParameters: function () {
			var params = {};
			this.elements.each(function (element) {
				params[element.id] = element.getValue();
			});
			return Json.toString(params);
		},
		execute: function () {
			new Ajax(site.ajaxPath + 'returnSearchResults', {
				postBody: {
					JSON: this.collectParameters()
				},
				update: $('results')
			}).request();
		}
	},
	feedbackTab: {
		init: function () {
			new Element('img', {src:'/Biotech/images/feedback.gif', alt:'Give Feedback'})
				.addClass('feedbackBtn')
				.addEvents({
					mouseover: function () {
						this.addClass('on');
					},
					mouseout: function () {
						this.removeClass('on');
					},
					click: function () {
//						pageTracker._trackPageview('/feedback-tab/');
						var comments = new Element('textarea');
						var name = new Element('input', {type:'text', value:'(optional)'}).addClass('temp').addEvent('focus', function () {if (this.value == '(optional)') this.removeClass('temp').value = '';});
						var email = new Element('input', {type:'text', value:'(optional)'}).addClass('temp').addEvent('focus', function () {if (this.value == '(optional)') this.removeClass('temp').value = '';});
						
						var buttons = new Element('ul', {id:'feedbackStates'})
							.adopt(new Element('li').addClass('question').setText('You have a question'))
							.adopt(new Element('li').addClass('problem').setText('You have a problem'))
							.adopt(new Element('li').addClass('idea').addClass('on').setText('You have an idea'))
							.adopt(new Element('li').addClass('praise').setText('Give praise'));
						var fields = new Element('ul').addClass('fields')
							.adopt(new Element('li')
								.adopt(new Element('label', {htmlFor:'comments'}).setText('Your Comments:'))
								.adopt(comments)
							)
							.adopt(new Element('li')
								.adopt(new Element('label', {htmlFor:'name'}).setText('Name:'))
								.adopt(name)
							)
							.adopt(new Element('li')
								.adopt(new Element('label', {htmlFor:'email'}).setText('Email:'))
								.adopt(email)
							);
						var popup;
						var button = new Element('input', {type:'submit', value:'Send'}).addClass('send')
							.addEvent('click', function () {
								pageTracker._trackPageview('/feedback-tab-submitted/');
								new Ajax(site.ajaxPath + 'SendTabFeedback', {
									postBody:{
										state: $$('#feedbackStates li.on')[0].getText(),
										message: comments.getValue(),
										name: name.getValue(),
										email: email.getValue()
									},
									onComplete: function () {
										buttons.remove();
										fields.remove();
										decline.remove();
										button.remove();
										popup.adopt(new Element('h2').setText('Thank you').setStyle('text-align', 'center')).center();
										pageTracker._trackPageview('/feedback-tab-thanks/');
									}
								}).request();
							});	
						var decline = new Element('a').setText('Cancel');
						
						popup = new Element('div', {id:'feedbackTabPopup'}).addClass('feedbackPopup').adopt(buttons).adopt(fields).adopt(decline).adopt(button).injectInside(document.body).center();
						var overlay = new feedbackOverlay(popup);
						decline.addEvent('click', overlay.remove.bind(overlay));
						$$('#feedbackStates li').addEvent('click', function (e) {
							$$('#feedbackStates li').removeClass('on');
							new Event(e).target.addClass('on');
						});
					}
				})
				.injectInside('Container');
		}
	},
	feedbackRadios: {
		init: function () {
			$$('input[name=footerFeedback]').addEvent('click', function(e) {
				pageTracker._trackPageview('/feedback-radio/');
				var label = new Event(e).target.getParent().getText();
				var header = new Element('h2').setText('Thank you');
				var message = new Element('p').setText('Would you like to tell us how the site ' + (label.toLowerCase().contains('not') ? 'could be improved?' : 'has helped you?'));
				var field = new Element('textarea');
				var button = new Element('input', {type:'submit', value:'Send'}).addClass('send')
					.addEvent('click', function () {
						pageTracker._trackPageview('/feedback-radio-note-submitted/');
						new Ajax(site.ajaxPath + 'SendRadioFeedback', {
							postBody:{
								state: label,
								message: field.getValue()
							},
							onComplete: function () {
								message.remove();
								field.remove();
								decline.remove();
								button.remove();
								pageTracker._trackPageview('/feedback-radio-complete/');
							}
						}).request();
					});
				var decline = new Element('a').setText('No thanks');
				
				
				var popup = new Element('div', {id:'radioPopup'}).addClass('feedbackPopup').adopt(header).adopt(message).adopt(field).adopt(decline).adopt(button).injectInside(document.body).center();
				var overlay = new feedbackOverlay(popup);
				decline.addEvent('click', overlay.remove.bind(overlay));
			});
			
		}
	},
	recommendation: {
		init: function () {
			$$('.recommend').addEvent('click', function (e) {
				new Event(e).stop();
				var header = new Element('h2').setText('Your recommendation');
				var message1 = new Element('p').setText('Please provide source details:');
				var field1 = new Element('textarea');
				var message2 = new Element('p').setText('and any further notes:');
				var field2 = new Element('textarea');
				var button = new Element('input', {type:'submit', value:'Send'}).addClass('send')
					.addEvent('click', function () {
						new Ajax(site.ajaxPath + 'SendRecommendation', {
							postBody:{
								message: field1.getValue() + ' - ' + field2.getValue()
							},
							onComplete: function () {
								message1.remove();
								field1.remove();
								message2.remove();
								field2.remove();
								decline.remove();
								button.remove();
								header.setText('Thank you');
							}
						}).request();
					});
				var decline = new Element('a').setText('Cancel');
				
				var popup = new Element('div', {id:'recommendationPopup'}).addClass('feedbackPopup').adopt(header).adopt(message1).adopt(field1).adopt(message2).adopt(field2).adopt(decline).adopt(button).injectInside(document.body).center();
				var overlay = new feedbackOverlay(popup);
				decline.addEvent('click', overlay.remove.bind(overlay));
			});
		}
	},
	page: {
		init: function () {
			if (site.page.isActive()) {
				new Element('a', {id:'wysiwygEdit'}).setText('Edit Page').injectBefore('editable').addEvent('click', site.page.load);
			}
		},
		isActive: function () {
			if ($('loggedin').value > 0 && $('editable')) return true;
		},
		load: function () {
			new Element('textarea', {id:'wysiwyg'}).setHTML($('editable').innerHTML).injectBefore('editable');
			tinyMCE.execCommand('mceAddControl', false, 'wysiwyg');
			$('editable').setStyle('display', 'none'); $('wysiwygEdit').setStyle('display', 'none');
			$$('.mceEditor').setStyle('width', '100%');
			$$('.mceEditorIframe').setStyles({width:'100%', height:'400px'});
			new Element('a', {id:'wysiwygSave'}).setText('Save').injectBefore('editable').addEvent('click', site.page.save).setStyles({padding:'1em', lineHeight:'3em'});
			new Element('a', {id:'wysiwygCancel'}).setText('Cancel').injectBefore('editable').addEvent('click', site.page.unload);
		},
		unload: function () {
			tinyMCE.execCommand('mceRemoveControl', false, 'wysiwyg');
			$('wysiwyg').remove(); $('wysiwygSave').remove(); $('wysiwygCancel').remove();
			$('editable').setStyle('display', '');
			$('wysiwygEdit').setStyle('display', '');
		},
		save: function () {
			tinyMCE.triggerSave(true,true);
			var content = $('wysiwyg').getValue()
			$('editable').setHTML(content);
			
			new Ajax(site.ajaxPath + 'EditPage', {
				postBody:{
					page: $('editable').getProperty('class'),
					content: escape(content)
				},
				onComplete: function(response) {
					if (!response) {
						site.page.unload();
					} else {
						this.adopt(new Element('p', {'class':'error'}).setText('An error has occurred.'));
					}
				}.bind(this),
				onFailure: function(request) {
					alert(request.responseText);
				}
			}).request();
		}
	}
}

window.addEvent('domready', site.init);


var feedbackOverlay = new Class({
	initialize: function (popup) {
		this.popup = popup;
		this.control = new Element('div', {id:'overlay'}).addClass('overlay').setOpacity(0.2).injectBefore(this.popup).addEvent('click', this.remove.bind(this));
		this.fitToWindow()
		window.addEvent('resize', this.fitToWindow);
	},
	remove: function () {
		this.popup.remove();
		this.control.remove();
		window.removeEvent('resize', this.fitToWindow);
	},
	fitToWindow: function () {
		this.control.setStyles({
			height: window.getScrollHeight(),
			width:  window.getWidth()
		});
	}
});	