/** Class for attaching events to certain DOM objects. */
var Event = {

	/**
	 * GUI initialization events.
	 */
	init: function() {
		// Initialize
		Wndw.appletContainers = ['query'];
		var navigationWidth = document.getElementById('navigation').clientWidth;
		// Navigation pane minimize/maximize button
		$('#navigationMinMax').click(function() {
			View.animateNavigation(navigationWidth);
		});
		// Table selector drop-down list
		$('#tSelection').change(function() {
			Logic.slcted = $(this).val();
			Logic.setWritableFlag(Logic.getCurrentName());
			if (Logic.isWritable) {
				$('#navInsert').css('display', 'block');
			} else {
				if (Wndw.isOpen('insert')) {
					Wndw.close('insert');
				}
				$('#navInsert').css('display', 'none');
			}
			View.sketchOpened = [];
			Logic.molecules = [];
			Logic.molecules[View.marvin.insert.applet] = {ws: ''};
			Logic.queryOptions = 't:s';
			$('#chemTermsFilter').val('none');
			$('#chemTermsArea').val('');
			$('#chemTermsActive').css('visibility', 'hidden');
			Ajax.setQuery();
			View.displayQuery('generatedQuery');
			View.displayInsert('generatedInsert');
			View.setUrl();
			View.setSearchType('s');
			View.getExportFieldsHtml(Logic.getFieldsForSelected(true)).draw('fieldSelection');
			View.setSelectOptions('similarityType', Logic.getFingerprint());
			View.setSelectOptions('screeningConfig', Logic.getScreeningConfig()[$('#similarityType').val()], true);
			View.setQueryOptions(Logic.getStructureTableType());
			if (Logic.getStructureTableType() == 'markush') {
				$('#rgroupDefinitions').show();
			} else {
				$('#rgroupDefinitions').hide();
			}
			if (Logic.getStructureTableType() == 'reactions') {
				$('#outputType').hide();
				$('#reactionOutputType').show();
			} else {
				$('#reactionOutputType').hide();
				$('#outputType').show();
			}
			// Field conditions on Query pane
			$('.querySelect').unbind('change');
			$('.querySelect').change(function() {
				var number = $(this).attr('id').substr(View.prefix.columnCondition.length);
				View.getInputContent(number).draw(View.prefix.queryInput+number);
			});
			// Marvin applet container on Query pane
			$('#'+View.marvin.query.container).unbind('click');
			$('#'+View.marvin.query.container).click(function() {	
				View.loadSketch(View.marvin.query.applet, View.marvin.query.container, '');
			});
			// Marvin applet container on Insert pane
			$('#'+View.marvin.insert.container).unbind('click');
			$('#'+View.marvin.insert.container).click(function() {	
				View.loadSketch(View.marvin.insert.applet, View.marvin.insert.container, '');
			});
		});
		// Alignment drop-down list
		$('#alignment').change(function() {
			Logic.makeColoringData();
			Ajax.setQuery(true, Scrolling.elementId);
		});
		// R-group definition show / hide checkbox
		$('#rgroupDefinitions').click(function() {
			if (!View.inProgress) {
				View.isRGroupNeeded = !View.isRGroupNeeded;
				var borderWidth = 2;
				if (View.isRGroupNeeded) {
					$('#rgroupDefinitions').css('border-style', 'solid');
					$('#rgroupDefinitions').css('margin-top', (parseInt($('#rgroupDefinitions').css('margin-top'))-borderWidth)+'px');
					$('#rgroupDefinitions').css('left', (parseInt($('#rgroupDefinitions').css('left'))-borderWidth)+'px');
				} else {
					$('#rgroupDefinitions').css('border-style', 'none');
					$('#rgroupDefinitions').css('margin-top', (parseInt($('#rgroupDefinitions').css('margin-top'))+borderWidth)+'px');
					$('#rgroupDefinitions').css('left', (parseInt($('#rgroupDefinitions').css('left'))+borderWidth)+'px');
				}
				Ajax.setQuery(true, Scrolling.elementId);
			}
		});
		// Browser window resize
		$(window).resize(function() {
			var oldElemsPerPage = Scrolling.elemsPerPage;
			if (Event.resize(View.spreadsheetTop, parseInt(View.image.height)+2) == true) {
				if (Scrolling.elemsPerPage > oldElemsPerPage) {
					Scrolling.elementId = Math.max(0, Scrolling.elementId - Scrolling.elemsPerPage + oldElemsPerPage);
				}
				Scrolling.replaceScrollbar(Scrolling.elementId);
				Scrolling.setVisible(Scrolling.noElements > Scrolling.elemsPerPage);
				Ajax.getMolData(Scrolling.elementId, Scrolling.elemsPerPage);
    			View.setPreviewNumbers();
			}
		});
		// Apply molecule data changes in edit mode
		$('#spreadsheetResult').mouseup(function() {
			// Mouseup event used here so View.switchAllowed can be set to false on mousedown events, if needed
			if (View.edited.id != null && View.edited.row != null && View.switchAllowed == true) {
				View.switchToSpreadsheetMode(View.edited.id, View.edited.row);
			} else {
				View.switchAllowed = true;
			}
		});
		$(window).unload(function() {
			Ajax.closeConnection();
		});
	},

	/**
	 * Query pane events.
	 */
	query: function() {
		// Marvin applet container
		$('#'+View.marvin.query.container).click(function() {
			View.loadSketch(View.marvin.query.applet, View.marvin.query.container, '');
		});
		// Field conditions
		$('.querySelect').change(function() {
			DatePicker.hide();
			var number = $(this).attr('id').substr(View.prefix.columnCondition.length);
			View.getInputContent(number).draw(View.prefix.queryInput+number);
		});
		// Search type selector drop-down list
		$('#searchType').change(function() {
			View.setQueryOptions(Logic.getStructureTableType());
		});
		// Special handler for query window minimize event
		$('#query .windowMin').unbind('click');
		$('#query .windowMin').click(function() {
			View.closeSketch(View.marvin.query.applet);
			View.setUrl();
			Wndw.minimize('query');
		});
		// Special handler for query window maximize event
		$('#query .windowMax').unbind('click');
		$('#query .windowMax').click(function() {
			View.openSketch(View.marvin.query.applet, View.marvin.query.container);
			Wndw.maximize('query');
		});
		// Special handler for query window close event
		$('#query .windowClose').unbind('click');
		$('#query .windowClose').click(function() {
			View.closeSketch(View.marvin.query.applet);
			View.setUrl();
			Wndw.close('query');
		});
		// Submit button
		$('#submitButton').click(function() {
			if (Wndw.isOpen('options')) {
				$('#'+Wndw.prefix.close+'options').trigger('click');
			}
			$('#'+Wndw.prefix.close+'query').trigger('click');
			View.setUrl();
			Logic.makeQueryData();
			Ajax.setQuery();
		});
		// Clear button
		$('#clearButton').click(function() {
			DatePicker.hide();
			Logic.molecules = [];
			Logic.molecules[View.marvin.insert.applet] = {ws: ''};
			Logic.queryOptions = 't:s';
			if (document.getElementById(View.marvin.query.applet) != null && (navigator.appName == "Microsoft Internet Explorer" || 
				document.getElementById(View.marvin.query.applet).setMol != null)) {
				document.getElementById(View.marvin.query.applet).setMol('');
			}
			$('#searchType').val('s');
			$('.querySelect').val('none');
			$('.queryArg').val('');
			$('.queryInput').html('&nbsp;');
			View.setQueryOptions(Logic.getStructureTableType());
			View.setUrl();
		});
		// GenerateURL button
		$('#generateUrlButton').click(function() {
			Logic.storeQueryMolecule(View.marvin.query.applet);
			View.setUrl();
		});
	},

	/**
	 * Options pane events.
	 */
	options: function() {
		// Predefined Chemical Terms filter drop-down list
		$('#chemTermsFilter').change(function() {
	    	$('#chemTermsArea').val(View.getChemicalTermsExp($(this).val()));
	    	$('#chemTermsActive').css('visibility', $('#chemTermsArea').val() == '' ? 'hidden' : 'visible');
		});
		// Chemical Terms textarea
		$('#chemTermsArea').keyup(function() {
			$('#chemTermsActive').css('visibility', $('#chemTermsArea').val() == '' ? 'hidden' : 'visible');
		});
		$('#chemTermsArea').change(function() {
			$('#chemTermsActive').css('visibility', $('#chemTermsArea').val() == '' ? 'hidden' : 'visible');
		});
		// Chemical Terms Clear button
		$('#chemTermsClearButton').click(function() {
			$('#chemTermsFilter').val('none');
			$('#chemTermsArea').val('');
			$('#chemTermsActive').css('visibility', 'hidden');
		});
		// Similarity type selector drop-down-list
		$('#similarityType').change(function() {
			View.setSelectOptions('screeningConfig', Logic.getScreeningConfig()[$(this).val()]);
		});
		// Advanced and Chemical Terms tab (mouseover)
		$('#tab0advanced, #tab0chemicalTerms').mouseover(function(e) {
			Tip.show(Tip.prefix.content+$(this).attr('id'), 1, 30);
		});
		// Advanced and Chemical Terms tab (mouseout)
		$('#tab0advanced, #tab0chemicalTerms').mouseout(function(e) {
			Tip.hide(Tip.prefix.content+$(this).attr('id'));
		});
		// Labels on Advanced page (mouseover)
		$('#stereoTitle, #atomTitle, #tautomerTitle, #vaguebondTitle').mouseover(function(e) {
			var id = $(this).attr('id');
			var coordY;
			switch (id) {
				case 'stereoTitle':
					coordY = 50;
					break;
				case 'atomTitle':
					coordY = 145;
					break;
				case 'tautomerTitle':
					coordY = 270;
					break;
				case 'vaguebondTitle':
					coordY = 320;
					break;
			}
			Tip.show(Tip.prefix.content+id, 1, coordY);
		});
		// Labels on Advanced page (mouseout)
		$('#stereoTitle, #atomTitle, #tautomerTitle, #vaguebondTitle').mouseout(function(e) {
			Tip.hide(Tip.prefix.content+$(this).attr('id'));
		});
	},

	/**
	 * Insert pane events.
	 */
	insert: function() {
		// Marvin applet container 
		$('#'+View.marvin.insert.container).click(function() {
			View.loadSketch(View.marvin.insert.applet, View.marvin.insert.container, '');
		});
		// Special handler for insert window minimize event
		$('#insert .windowMin').unbind('click');
		$('#insert .windowMin').click(function() {
			View.closeSketch(View.marvin.insert.applet);
			Wndw.minimize('insert');
		});
		// Special handler for insert window maximize event
		$('#insert .windowMax').unbind('click');
		$('#insert .windowMax').click(function() {
			View.openSketch(View.marvin.insert.applet, View.marvin.insert.container);
			Wndw.maximize('insert');
		});
		// Special handler for insert window close event
		$('#insert .windowClose').unbind('click');
		$('#insert .windowClose').click(function() {
			View.closeSketch(View.marvin.insert.applet);
			Wndw.close('insert');
		});
		// Insert button
		$('#insertButton').click(function() {
			$('#'+Wndw.prefix.close+'insert').trigger('click');
			if (Logic.molecules[View.marvin.insert.applet] != null && Logic.molecules[View.marvin.insert.applet].ws != '') {
				Ajax.insertMolecule();
			}
			if (document.getElementById(View.marvin.insert.applet) != null && (navigator.appName == "Microsoft Internet Explorer" || 
				document.getElementById(View.marvin.insert.applet).setMol != null)) {
				document.getElementById(View.marvin.insert.applet).setMol('');
			}
			Logic.molecules[View.marvin.insert.applet] = {ws: ''};
			$('#insert input.insertInput').each(function(i, inputElement) {
				inputElement.value = '';
			});
			View.getSketchText().draw(View.marvin.insert.container);
			View.sketchOpened[View.marvin.insert.applet] = false;
		});
	},

	/**
	 * Export pane events.
	 */
	xport: function() {
		// Initialize
		var os = Util.detectOs();
		if (os == null || os == 'Windows') {
			$('#exportEol').val('rn');
		} else {
			$('#exportEol').val('n');
		}
		// Export button
		$('#exportButton').click(function() {
			$('#exportSearch').val(Ajax.searchId);
			$('#exportUrl').val(Cache.cfg['soapPath']['export'].val);
			$('#exportSsl').val(Cache.cfg['jspPath']['sslPort'].val);
			var fields = '';
			$('input.field').each(function() {
				if ($(this).attr('checked') == true) {
					fields += $(this).val()+' ';
				}
			});
			if (fields.length > 0) {
				fields = fields.slice(0, fields.length-1);
			}
			$('#exportFields').val(fields);
			if (Logic.getStructureTableType() == 'reactions') {
				$('#exportFormat').val($('#reactionOutputType').val());
			} else {
				$('#exportFormat').val($('#outputType').val());
			}
			$('#exportForm').attr('action', Cache.cfg['jspPath']['export'].val);
			$('#'+Wndw.prefix.close+'export').trigger('click');
			$('#exportForm').submit();
		});
	},

	/**
	 * Markush pane events.
	 */
	markush: function() {
		// Enumerate button
		$('#markushButton').click(function() {
			Logic.markush.filter = ($('#markushValenceFilter').attr('checked') == true ? 'valence' : '');
			Logic.markush.homology = ($('#markushHomology').attr('checked') == true ? true : false);
			Logic.markush.code = ($('#markushCode').attr('checked') == true ? true : false);
			Logic.markush.alignScaffold = ($('#markushScaffoldAlign').attr('checked') == true ? true : false);
			if ($('#markushScaffoldColoring').attr('checked') == true) {
				Logic.markush.coloring = ($('#markushRgroupColoring').attr('checked') == true ? 'all' : 'scaffold');
			} else {
				Logic.markush.coloring = ($('#markushRgroupColoring').attr('checked') == true ? 'rgroups' : '');
			}
			if ($('#markushLibrarySize').attr('checked') == true) {
				Logic.markush.mode = 'library';
			} else if ($('#markushSequential').attr('checked') == true) {
				Logic.markush.mode = 'sequential';
			} else if ($('#markushRandom').attr('checked') == true) {
				Logic.markush.mode = 'random';
			}
			$('#'+Wndw.prefix.close+'markush').trigger('click');
			if (Logic.markush.mode == 'library') {
				var molecule = Ajax.getMolecule(View.selectedMarkushStructure, 'mrv');
				alert('Library size: '+Ajax.getMarkushLibrarySize(molecule));
			} else if (Logic.markush.mode != null) {
				View.displayEnumeration(View.selectedMarkushStructure, this);
			}
		});
	},

	/**
	 * Preview pane events.
	 */
	preview: function() {
		// Preview button
		$('#previewButton').click(function() {
			var from = parseInt($('#previewInputFrom').val())-1;
			var to = parseInt($('#previewInputTo').val());
			if (from < 0) {
				from = 0;
			}
			if (to > Scrolling.noElements) {
				to = Scrolling.noElements;
			}
			$('#previewFrom').val(from);
			limit = to - from;
			if (limit > 1) {
				$('#previewLimit').val(limit);
			} else {
				$('#previewLimit').val(1);
			}
			$('#previewTable').val(Logic.slcted);
			$('#previewSearch').val(Ajax.searchId);
			$('#previewAlignment').val($('#alignment').val());
			$('#previewForm').submit();
		});
	},

	/**
	 * About pane events.
	 */
	about: function() {
		// Initialize
		Ajax.getInfo();
	},

	/**
	 * Scrolling events.
	 */
	scrolling: function() {
		// Initialize
		$('#prev, #next').disableTextSelect();
		// Up/previous arrow
		$('#prev').click(function() {
			if (!View.inProgress && Scrolling.elementId >= 1) {
   				Scrolling.elementId--;
   				Scrolling.replaceScrollbar(Scrolling.elementId);
   				Ajax.getMolData(Scrolling.elementId, Scrolling.elemsPerPage);
   				View.setPreviewNumbers();
			}
		});
		// Down/next arrow
		$('#next').click(function() {
			if (!View.inProgress && Scrolling.elementId < Scrolling.noElements - Scrolling.elemsPerPage) {
				Scrolling.elementId++;
    			Scrolling.replaceScrollbar(Scrolling.elementId);
    			Ajax.getMolData(Scrolling.elementId, Scrolling.elemsPerPage);
    			View.setPreviewNumbers();
			}
		});
		// Scrollbar area
		$('div.dummy, #scroll').click(function(e) {
			if (!View.inProgress) {
				if (Scrolling.moveBar == false) {
    				Scrolling.pageUpDown(Scrolling.scrollPos < e.pageY - Scrolling.scrollY);
    				if (Scrolling.elementId < 0) {
						Scrolling.elementId = 0;
					} else {
						Scrolling.replaceScrollbar(Scrolling.elementId);
	    				Ajax.getMolData(Scrolling.elementId, Scrolling.elemsPerPage, false);
	    				View.setPreviewNumbers();
					}
				} else {
					Scrolling.moveBar = false;
				}
			}
		});
		// Keyboard scrolling
		$(document).keydown(function(e) {
			if (!View.inProgress) {
				var code;
				if (e.keyCode != null) {
					code = e.keyCode;
				} else if (e.which != null) {
					code = e.which;
				}
				var id = Scrolling.elementId;
				if (code == 33) {
			    	Scrolling.pageUpDown(false);
				} else if (code == 34) {
			    	Scrolling.pageUpDown(true);
				}
				if (Scrolling.elementId != id) {
					if (Scrolling.elementId < 0) {
						Scrolling.elementId = 0;
					} else {
						Scrolling.replaceScrollbar(Scrolling.elementId);
						Ajax.getMolData(Scrolling.elementId, Scrolling.elemsPerPage, false);
						View.setPreviewNumbers();
					}
				}
			}
		});
		// Mousewheel scrolling
		$('#resultContent').mousewheel(function(e, delta) {
			if (!View.inProgress) {
				var d = new Date();
				d = d.getTime();
				if (d > Scrolling.date + 200) {
					Scrolling.date = d;
						if (Scrolling.noElements > Scrolling.elemsPerPage) {
						var id = Scrolling.elementId;
						if (delta > 0){
							Scrolling.pageUpDown(false);
						} else if (delta < 0){
							Scrolling.pageUpDown(true);
						}
						if (Scrolling.elementId != id) {
							Scrolling.replaceScrollbar(Scrolling.elementId);
							Ajax.getMolData(Scrolling.elementId, Scrolling.elemsPerPage, false);
							View.setPreviewNumbers();
						}
					}
				}
			}
		});
		// Cursor scrolling (mousedown)
		$('#bar').mousedown(function(e) {
			if (!View.inProgress && Scrolling.noElements > Scrolling.elemsPerPage) {
				Scrolling.mouse = true;
				$('body').disableTextSelect();
			}
		});
		// Cursor scrolling (mousemove)
		$(document).mousemove(function(e) {
			if (Scrolling.mouse == true) {
    			Scrolling.mouseMoveScrollbar(e);
			}
		});
		// Cursor scrolling (mouseup)
		$(document).mouseup(function(e) {
			if (Scrolling.mouse == true) {
				Scrolling.mouse = false;
				Scrolling.moveBar = true;
			    Scrolling.mouseMoveScrollbar(e);
    			Scrolling.replaceScrollbar(Scrolling.elementId);
    			Ajax.getMolData(Scrolling.elementId, Scrolling.elemsPerPage);
    			View.setPreviewNumbers();
    			$('body').enableTextSelect();
			}
		});
	},

	/**
	 * Replace window size dependent elements.
	 *
	 * @param topPos   Y-coordinate that defines the top pixel of the spreadsheet content.
	 * @param ySize    Height of one row in the spreadsheet.
	 * @return boolean that indicates whether the Scrolling properties have been changed or not.
	 */
	resize: function(topPos, ySize) {
		var win = Util.getWindowSize();
		if (win.x < View.minWinWidth) {
			win.x = View.minWinWidth;
		}
		var navigationWidth = document.getElementById('navigation').clientWidth;
		$('#result').css('width', (win.x-parseInt(navigationWidth)-60)+'px');
		$('#scrollbarResult').css('left', (win.x-57)+'px');
		$('#loading').css('left', Math.floor((win.x - 80)/2)+'px');
		$('#loading').css('top', Math.floor((win.y - 100)*0.46)+'px');
		var moleculeNumber = Math.floor((win.y-topPos-65) / ySize);
		if (moleculeNumber > 0 && moleculeNumber != Scrolling.elemsPerPage) {
			Scrolling.elemsPerPage = moleculeNumber;
			Scrolling.scrollSize = Scrolling.elemsPerPage * ySize - 10;
			$('#scroll').css('height', Scrolling.scrollSize+'px');
			return true;
		}
		return false;
	},

	/**
	 * Column sorting events.
	 */
	sorting: function() {
		$('.sort').click(function() {
			if (!View.inProgress) {
				$('.sort').unbind('click');
				Logic.orderByColumn($(this).attr('title'));
				Logic.makeQueryData();
				Ajax.setQuery(true, Scrolling.elementId);
			}
		});
	}
};
