// Number of taxa that can be added in the expandable taxon name table
var numtax = 5;

var tabindex = 0;
var initialfocus;;
var newfocus;

// Everything in this closure will happen after the DOM is loaded		
$(function(){
	var initialfocus = $('form input[tabindex=1]');

	// ON PAGE LOAD
	// force vertical scroll bar
	$('html').css({'height': '101%'});

	// replace submit button of type 'submit' for one of type 'button',
	// so we can do browser-side form validation; submit button in html source
	// needs to be of type 'submit', so form can be submitted if Javascript is disabled
	$('input[name=exquery_submit]').replaceWith('<input type="button" value="Submit" name="exquery_submit" tabindex="35" />');
	document.getElementsByTagName('form')[0].reset();
	
	// make help page open in different window;
	// otherwise form won't save state when you return to page
	$('.helplink, .partnerLink').attr('target', '_blank');

	// initialise expandable taxon name table
	$('#taxonname_table tbody tr:not(:first)').remove();
	$('#taxonname_table thead tr').each(function(i) {
		if (i==0) {
			$(this).children('th:first').attr('colspan', '7');
		}
		else {
			$(this).append('<td>&nbsp;<\/td>');
		}
	});
	$('#taxonname_table tbody tr').each(function(i) {
		$(this).append('<td><button type="button" class="addrowlink" title="Add row" tabindex="6"><img class="addrow" src="images/plus.png" alt="Add row" \/><\/button><\/td>');
	});
	
	// some formatting on page load
	noborder(); // table and cell borders
	lastcolumnwidth(); // width of last table column
	
	// set the focus to the first form element (genus.1)
	initialfocus.focus();

	// fix the borders
	$('#taxonname_table thead tr td:gt(0):not(:last)').css({
		'border-style': 'none',
		'border-width': '0px',
		'border-bottom-style': 'solid',
		'border-bottom-width': '1px'});
	$('#taxonname_table tbody tr td:gt(0):not(:last)').css({
		'border-style': 'none',
		'border-width': '0px'});
		


	// LISTENERS	

	// send the tabindex of the element which has the focus to the console;
	// for testing only
	/*$('input, select, button').livequery('focus', function() {
		var tindex = $(this).attr('tabindex');
		$('#console').html(tindex);
	})*/;

	// append a new row to the table
	// add a new row to the taxon name table
	$('#taxonname_table .addrowlink').livequery('click', function() {
		addrow();
	});

	// add the 'add row' link to the present row of the taxon name table if something has been typed in in the genus field,
	// or delete the row if the genus field is emptied (and it is not the last row)
	/*$('input[name^=genus]').livequery('change', function() {
		adddeladdrowlink(this);
	});*/
	
	$('input[name=exquery_submit]').click(function() {
		validateInput();
	});
	
	$('input[name=clearButton]').click(function() {
		window.location.reload();
	});
});

function addrow() {
	var rowspan = parseInt($('#taxonname_table tbody tr').length);
	var newrowspan = rowspan+1;
	var inittab = 6*rowspan;
	
	var genusinput = $('#taxonname_table input[name^=genus]:last').val();
	
	if(genusinput.length > 0) {
		// We will be adding five form elements and a link with tabindices,
		// so we have to raise the tabindices of all elements that come after by six.
		/*$('form').find('input, select, a[tabindex]').each(function() {
			tabindex = Number($(this).attr('tabindex'));
			if(tabindex > inittab) {
				var newtabindex = tabindex + 6;
				$(this).attr('tabindex', newtabindex);
			}
		});*/

		// hide the 'add row' link in all but the last rows
		$('#taxonname_table .addrowlink').hide();
		
		$('#taxonname_table tbody').append('<tr><td>&nbsp;<\/td>'
			+ '<td><input type="text" name="genus.' + newrowspan + '" tabindex="' + Number(inittab+1) + '" \/><span class="super">*<\/span><\/td>'
				+ '<td><input type="text" name="species.' + newrowspan + '" tabindex="' + Number(inittab+2) + '" \/><span class="super">*<\/span><\/td>'
				+ '<td>'
					+ '<select name="infraspecificRank.' + newrowspan + '" tabindex="' + Number(inittab+3) + '">'
						+ '<option value="">&nbsp;<\/option>'
						+ '<option value="ssp., subps., subsp., Supsp.">subsp.<\/option>'
						+ '<option value="var, var., variant">var.<\/option>'
						+ '<option value="subvar.">subvar.<\/option>'
						+ '<option value="f., form, form taxon, forma">f.<\/option>'
						+ '<option value="subf.">subf.<\/option>'
					+ '<\/select>'
				+ '<\/td>'
				+ '<td><input type="text" name="infraspecificName.' + newrowspan + '" tabindex="' + Number(inittab+4) + '" \/><span class="super">*<\/span><\/td>'
				+ '<td>'
				+ '<input type="checkbox" checked name="identificationQualifierFilter.' + newrowspan + '" value="all" tabindex="' + Number(inittab+5) + '" />'
				+ '<\/td>'
				+ '<td><button type="button" class="addrowlink" tabindex="' + Number(inittab+6) + '"><img class="addrow" src="images/plus.png" alt="add row" \/><\/button><\/td>'
			+ '<\/tr>'

		);

                // do not display add row link in fifth row
                if ($('#taxonname_table tbody tr').length == numtax) {
                        $('#taxonname_table .addrowlink').hide();
                }
		
		// set focus to genus input in new row
		var focustab = inittab+1;
		var focusinput = $('input[tabindex=' + focustab +']').length>0 ? $('input[tabindex=' + focustab +']') : $('select[tabindex=' + focustab +']') ;
		focusinput.focus();
		
		// table and cell borders
		$('#taxonname_table tbody tr td').css({
			'border-style-bottom': 'none',
			'border-width': '0px'
		});
		
		$('#taxonname_table tbody tr').each(function() {
			$(this).children('td:first').css({
				'border-right-style': 'solid', 
				'border-width': '1px', 
				'border-bottom-style': 'none'
			});
		});
	}
 	else {
		alert('Please enter at least a genus name in the current row before adding a new row');
		var focusOn = $(that).parent().parent().find('input[name^=genus]');
		focusOn.focus();
	}

}

/*function adddeladdrowlink(that) {
	var genusinput = $(that).val();
	tabindex = Number($(that).attr('tabindex'));
	if($('input[name^=genus]').index(that) == $('input[name^=genus]').length-1 && $('#taxonname_table tbody tr').length < numtax) {
		if(genusinput.length > 0 && $(that).parent().parent().find('.addrow').length < 1 ) {
			tabindex = Number($(that).attr('tabindex'));
			$(that).parent().parent().children('td:last').html(
				'<button type="button" class="addrowlink" tabindex="' + Number(tabindex+5) + '"><img class="addrow" src="images/plus.png" alt="add row" \/><\/button>'
			);
		}
		else {
			$(that).parent().parent().children('td:last').html('&nbsp;');
		}
	}
	else { // delete row if genus field is emptied
		if(genusinput.length < 1) {
			var c = confirm('Do you want to delete this row?');
			if (c == true) {
				$('form').find('input, select, a[tabindex]').each(function() {
					if(Number($(this).attr('tabindex')) > tabindex) {
						$(this).attr('tabindex', Number($(this).attr('tabindex'))-6);
					}
				});
				$(that).parent().parent().remove();
				$('#taxonname_table tbody td:first').html(
					'Taxon<a href="public_query_help.jsp#Plant_name" target="_blank"><img src="images\/question-mark.png" alt="info" class="help"\/><\/a>'
				);
				
				// set focus to next row; no need to change tabindexes
				newfocus = $('input[tabindex=' + tabindex + ']');
				newfocus.focus();
				
				// renumber form element names, in case they need to be numbered from 1 to 5
				$('#taxonname_table input[name^=genus]').each(function(i) {
					$(this).attr('name', 'genus.' + i);
				});
				$('#taxonname_table input[name^=species]').each(function(i) {
					$(this).attr('name', 'species.' + i);
				});
				$('#taxonname_table select[name^=infraspecificRank]').each(function(i) {
					$(this).attr('name', 'infraspecificRank.' + i);
				});
				$('#taxonname_table input[name^=infraspecificName]').each(function(i) {
					$(this).attr('name', 'infraspecificName.' + i);
				});
				$('#taxonname_table select[name^=identificationQualifier]').each(function(i) {
					$(this).attr('name', 'identificationQualifier.' + i);
				});
			}
		}
	}
};*/

function noborder() {
	$('#extended_query tbody tr').each(function() {
		$(this).children('td:gt(0):lt(1)').css({'border-left-style': 'none', 'border-right-style': 'none'});
	});
};

function lastcolumnwidth() {
	$('#extended_query tr, #taxonname_table tr').each(function() {
		$(this).children('td:last').css('width', '30px');
	});
};

function validateInput() {
	var invalid = false;
	var message = '';
	var invalidValue = false;
	
	// check if anything has been entered
	invalidValue = true;
	$('input[type=text], select').each(function() {
		if($(this).attr('value').length > 0) {
			invalidValue = false;
		}
	});
	if (invalidValue == true) {
		invalid = true;
		message += '<li>no query values have been entered</li>';
		invalidValue = false;
	}
	
	// taxon names
	$('input[name^=species], input[name^=genus], input[name^=infraspecificName]').each(function() {
		if ($(this).attr('value').length > 0) {
			var txtStr = $(this).attr('value');
			var txtArr = txtStr.split('');
			for(i in txtArr) {
				var lower = new RegExp('[a-z]', 'i');
				if(lower.test(txtArr[i]) == false && txtArr[i] != '%' && txtArr[i] != '-') {
					invalidValue = true;
				}
			}
			
			if (invalidValue == true) {
				$(this).addClass('invalid');
			}
		}
	});
	
	if (invalidValue == true) {
		message += '<li>invalid characters in taxon name field</li>';
		invalidValue = false;
		invalid = true
	}
	
	
	$('input[name^=species]').each(function(i) {
		var num = i + 1;
		if($(this).attr('value').length > 0 && $('input[name="genus.' + num + '"]').attr('value') < 1) {
			$('input[name="genus.' + num + '"]').addClass('invalid');
			invalidValue = true; 
			invalid = true;
		}
	});
	if (invalidValue == true) {
		message += '<li>species epithet without genus name</li>';
		invalidValue = false;
	}
	
	$('select[name^=infraspecificRank]').each(function(i) {
		var num = i + 1;
		if($(this).attr('value').length > 0 && $('input[name="infraspecificName.' + num + '"]').attr('value') < 1) {
			$('input[name="infraspecificName.' + num + '"]').addClass('invalid');
			$(this).addClass('invalid');
			invalidValue = true; 
			invalid = true;
		}
	});
	
	if (invalidValue == true) {
		message += '<li>infraspecific rank without infraspecific name</li>';
		invalidValue = false;
	}
	
	$('input[name^=infraspecificName]').each(function(i) {
		var num = i + 1;
		if($(this).attr('value').length > 0 && $('input[name="genus.' + num + '"]').attr('value') < 1) {
			$('input[name="genus.' + num + '"]').addClass('invalid');
			invalidValue = true; 
			invalid = true;
		}
		if($(this).attr('value').length > 0 && $('input[name="species.' + num + '"]').attr('value') < 1) {
			$('input[name="species.' + num + '"]').addClass('invalid');
			invalidValue = true; 
			invalid = true;
		}
	});
	$('select[name^=infraspecificRank]').each(function(i) {
		var num = i + 1;
		if($(this).attr('value').length > 0 && $('input[name="genus.' + num + '"]').attr('value') < 1) {
			$('input[name="genus.' + num + '"]').addClass('invalid');
			invalidValue = true; 
			invalid = true;
		}
		if($(this).attr('value').length > 0 && $('input[name="species.' + num + '"]').attr('value') < 1) {
			$('input[name="species.' + num + '"]').addClass('invalid');
			invalidValue = true; 
			invalid = true;
		}
	});
	
	if (invalidValue == true) {
		message += '<li>infraspecific name without genus name or species epithet</li>';
		invalidValue = false;
	}

	// replace unchecked checkboxes with hidden inputs; this is
	// not the most elegant but it lets us get around the fact that
	// unchecked checkboxes are not deemed 'successful controls'.
	$('input[name^=identificationQualifierFilter]').each(function(i) {
		var num = i + 1;
		if(!$(this).attr('checked')) {
			$(this).remove();
			var hidden = '<input type="hidden" name="identificationQualifierFilter.' + num + '" value="none">';
			$('form').append(hidden);
		}
	});
	
	if (invalid == true) {
		$('#taxonname_table').before('<p style="color: #ff0000; font-weight: bold; margin-bottom: 0px; padding-bottom: 0px;">The following input errors were discovered:</p>'+
			'<ul style="color: #ff0000; margin-top: 0px; padding-top: 0px;">' + message + '</ul>');
		$('.invalid').css({'border-color': '#ff0000'})
		return false;
	}
	else {
	if (document.getElementById("agreement")!=null&&(!$('#agreement').attr('checked'))) {
			alert("Please read and accept the data use agreement.");
			return;
		}
		$('form').submit();
	}
}
