var elementTemplateFirst;

var ctrlKeyDown = false;
var currCaretPos = -1;
$(document).ready(function()
{
	// Load custom peptide form templates
	$.ajax(
	{
		url:      'customPeptides.asp', 
		type:     'POST', 
		dataType: 'html', 
		
		success:  function(html)
		{
			elementTemplateFirst = html;
		}
	});
	
	// Focus/blur for fields.
	$('#customPeptides :input').live('focus', function()
	{
		$(this).addClass('focus');
	});
	
	$('#customPeptides :input').live('blur', function()
	{
		$(this).removeClass('focus');
	});
	
	// Add x amount of custom peptides.
	$('#addCustomPeptides a').click(function(e)
	{
		e.preventDefault();
		
		// Unset last child.
		var oldElement = $('#customPeptides li:last-child').removeClass('last-child');
		
		// Disable all checkboxes.
		$('#customPeptides li input[type=checkbox]').attr('disabled', 'disabled');
		
		// Get count and validate.
		var count = $('input[name=CustomPeptideCount]').val();
		if(count.toString().search(/^[0-9]+$/) != 0)
			count = 1;
		count = parseInt(count);
		
		var ApplyDownNC = $('#customPeptides li:last-child input[name=ApplyDownNC]:checked').val();
		var ApplyDownMP = $('#customPeptides li:last-child input[name=ApplyDownMP]:checked').val();
		
		// Add x amount of items.
		var elementSet = Array();
		var exceeded = false;
		for(i = 0; i < count; i++)
		{
			if($('#customPeptides li').size() == 50)
			{
				exceeded = true;
				break;
			}
			
			elementSet[i] = $(elementTemplateFirst);
			var element = elementSet[i];
			//var element = $(elementTemplateFirst).appendTo('#customPeptides');
			
			// Add input focus.
			$('.focusTrigger', element).each(function()
			{
				$(this).data('init', getAttributeValue(this, 'value'));
				if($(this).val() != $(this).data('init'))
				{
					$(this).addClass('focused');
				}
			});
			
			// Ensure check boxes.
			$('#customPeptides li:last-child input[name=ApplyDownNC]').val([ApplyDownNC]);
			$('#customPeptides li:last-child input[name=ApplyDownMP]').val([ApplyDownMP]);
			
			// Populate common fields.
			if($('#customPeptides li:last-child input[name=ApplyDownNC]:checked').size() == 1)
			{
				var nTerm = $('select[name=NTerm]', oldElement).val();
				var cTerm = $('select[name=CTerm]', oldElement).val();
				
				$('select[name=NTerm]', element).val(nTerm);
				$('select[name=CTerm]', element).val(cTerm);
			}
			
			if($('#customPeptides li:last-child input[name=ApplyDownMP]:checked').size() == 1)
			{
				var mass   = $('select[name=Mass]', oldElement).val();
				var purity = $('select[name=Purity]', oldElement).val();
				
				$('select[name=Mass]', element).val(mass);
				$('select[name=Purity]', element).val(purity);
			}
		}
		
		$(elementSet).appendTo('#customPeptides');
		
		// Set last child and enable checkboxes.
		$('#customPeptides li:last-child').addClass('last-child');
		$('#customPeptides li:last-child input[type=checkbox]').removeAttr('disabled');
		
		// Alert user for exceeding the number of custom peptides.
		if(exceeded)
			alert('You can only add up to 50 custom peptides. The custom peptide list has been truncated to 50 items.');
	});
	
	// Remove target custom peptide.
	$('#customPeptides a.remove').live('click', function(e)
	{
		e.preventDefault();
		
		var ApplyDownNC = $('#customPeptides li:last-child input[name=ApplyDownNC]:checked').val();
		var ApplyDownMP = $('#customPeptides li:last-child input[name=ApplyDownMP]:checked').val();
		
		$(this).parents('#customPeptides li').remove();
		
		// Ensure check boxes.
		$('#customPeptides li:last-child input[name=ApplyDownNC]').val([ApplyDownNC]);
		$('#customPeptides li:last-child input[name=ApplyDownMP]').val([ApplyDownMP]);
		
		// Set last child and enable checkboxes.
		$('#customPeptides li:last-child').addClass('last-child');
		$('#customPeptides li:last-child input[type=checkbox]').removeAttr('disabled');
	});
	
	// Only show correct sequence letter.
	$('input[name=Sequence]').filter(function()
	{
		$(this).val($(this).attr('value'));
		$(this).data('current', $(this).val());
		
		// Pre-populate field.
		var initValue = $('input[name=SequenceInitValue]').val();
		
		var regex = /^[ACDEFGHIKLMNPQRSTVWY]+$/;
		if(regex.test(initValue.toUpperCase()) && initValue.length >= 2 && initValue.length <= 50)
			$(this).val(initValue).addClass('focused');
	});
	$('input[name=Sequence]').live('focus', function()
	{
		currCaretPos = getSelectionStart(this);
	});
	$('input[name=Sequence]').live('keydown', function(e)
	{
		// CTRL/command key.
		if(e.which != 17 && e.which != 224)
		{
			// Validation.
			var regex = 'ACDEFGHIKLMNPQRSTVWY';
			// Validate backspace/delete, caret moving characters (left, right, home, end).
			var valid = regex.indexOf(String.fromCharCode(e.which).toString().toUpperCase()) != -1 || e.which == 8 ||  e.which == 46 || e.which == 37 || e.which == 39 || e.which == 36 || e.which == 35;
			
			// Save current valid value.
			var regex = /^[ACDEFGHIKLMNPQRSTVWY]+$/;
			if(regex.test($(this).val().toUpperCase()) || $(this).val().toUpperCase() == '')
			{
				$(this).data('current', $(this).val());
				currCaretPos = getSelectionStart(this);
			}
			
			// Post validation.
			if(!valid && !ctrlKeyDown && e.which != 13)
			{
				//sequenceRevert = true;
				e.preventDefault();
			}
		}
		else
		{
			ctrlKeyDown = true;
		}
	});
	$('input[name=Sequence]').live('keyup', function(e)
	{
		// Get current location of caret.
		var pos = getSelectionStart(this);
		
		// CTRL/command key.
		if(e.which != 17 && e.which != 224)
		{
			// Validate for CTRL functions.
			var regex = /^[ACDEFGHIKLMNPQRSTVWY]+$/;
			
			// Post validation.
			if(((sequenceRevert && !ctrlKeyDown) || !regex.test($(this).val().toUpperCase())) && !$(this).val().toUpperCase() == '')
			{
				$(this).val($(this).data('current'));
				setSelectionStart(this, currCaretPos);
				
				sequenceRevert = false;
			}
			else
				$(this).data('current', $(this).val());
		}
		else
		{
			// Reset.
			ctrlKeyDown = false;
		}
	});
	
	// Peptide Name.
	$('input[name=PeptideName]').live('keydown', function(e)
	{
		if(e.which == 17 || e.which == 224)
			ctrlKeyDown = true;
		/*else
		{
			// Allow blanks and some command functions.
			if(',8,46,37,39,36,35,'.indexOf(',' + e.which + ',') == -1 && $(this).val().length == 10 && !(ctrlKeyDown && 'cxyz'.indexOf(String.fromCharCode(e.which).toString().toLowerCase()) != -1))
				e.preventDefault();
		}*/
	});
	$('input[name=PeptideName]').live('keyup', function(e)
	{
		if(e.which == 17 || e.which == 224)
			ctrlKeyDown = false;
		
		// Ensure length.
		$(this).val($(this).val().substr(0, 10));
	});
	
	// Form Validation on submit.
	$('#customPeptides').parents('.customPeptideForm').submit(function(e)
	{
		// Reset.
		$('#customPeptides .invalid').removeClass('invalid');
		
		// Validate every custom peptide field.
		$('#customPeptides select').filter(function()
		{
			return $(this).val() == '';
		}).addClass('invalid');
		$('#customPeptides input[name=Sequence]').filter(function()
		{
			var regex = /^[ACDEFGHIKLMNPQRSTVWY]+$/;
			return !regex.test($(this).val().toUpperCase()) || $(this).val() == $(this).data('init') || $(this).val().length < 2;
		}).addClass('invalid');
		
		// Stop submit.
		if($('#customPeptides .invalid').size() > 0)
		{
			alert('Some of the fields entered are invalid. Please check over your form and try again.');
			e.preventDefault();
		}
		else if($('#customPeptides li').size() == 0)
		{
			alert('Please add some custom peptides.');
			e.preventDefault();
		}
	});
	
	// Converter tool.
	$('.converter').live('click', function(e)
	{
		e.preventDefault();
	
		var nthItem = $(this).parents('#customPeptides li');
		var targetIndex;
		$('#customPeptides li').each(function(index)
			{
				if($(this).get(0) == $(nthItem).get(0))
					targetIndex = index;
			});
	
		GB_showCenter('', '/dialogs/converterTool.asp?target=' + targetIndex, 300, 649);
	});
});