$(document).ready(function()
{
	//ad the scroll to anchor fuctionality
	$('.anchorToPos').click(function(event)
	{ 
		event.preventDefault(); 
		scrollWin($(this).attr('href'), 500);
	});
	
	//contact form stuff:
	//impose maxlength on textarea
	$('textarea[maxlength]').keyup(function()
	{
		//get the limit from maxlength attribute
		var limit = parseInt($(this).attr('maxlength'));
		//get the current text inside the textarea
		var text = $(this).val();
		//count the number of characters in the text
		var chars = text.length;
		
		//check if there are more characters then allowed
		if(chars > limit)
		{
			//and if there are use substr to get the text before the limit
			var new_text = text.substr(0, limit);
		
			//and change the current text with the new text
			$(this).val(new_text);
		}
	});
	
	//clear the form if text matches attr rel
	$('input, textarea').focus(function()
	{
		var inputVal = $(this).val().toLowerCase();
		var promptTxt = $(this).attr('rel').toLowerCase();
		if(inputVal == promptTxt)
		{
			$(this).val('');	
		}
	});
	
	$('input, textarea').blur(function()
	{
		var inputVal = $(this).val().toLowerCase();
		var promptTxt = $(this).attr('rel').toLowerCase();
		
		if(inputVal == '' || inputVal == promptTxt)
		{
			$(this).val($(this).attr('rel'));	
		}
	});
	
	//click handler for submit button
	$('#form_submit').click(function(event)
	{
		event.preventDefault();
		
		var errorMessage = '<span class="errorTitle">Ohh Snap!</span><ul class="errorList">';
		var numErrors = 0;
		
		//validate the form 
		$('#contactForm input, #contactForm textarea').each(function()
		{
			if($(this).attr('id') == 'spam_check') 
			{
				return true;
			}
			
			//make sure each text input text is not equal to '' or it's prompt
			var inputVal = $(this).val().toLowerCase();
			var promptTxt = $(this).attr('rel').toLowerCase();
			
			if(inputVal == promptTxt || inputVal == '')
			{
				//write error message
				errorMessage += '<li>The input field ' + promptTxt + ' is required.</li>';
				numErrors++;
				
				//add error class to input
			}
			else
			{
				//remove error class from input	
			}
		});
		
		//validate email
		if(!isValidEmailAddress($('#form_email').val()))
		{
			errorMessage += '<li>The email is invalid</li>';
			numErrors++;
		}
		
		//close error p
		errorMessage += '</ul>';
		
		if(numErrors > 0)
		{
			//shrink the message box to fit error notes
			var minusHeight = 25 * numErrors;
			minusHeight = Math.max(minusHeight, 75);
			
			$('#form_message').animate({height: 150 - minusHeight + 'px'}, 500);
			
			//hide any current errors
			hideErrors(numErrors);
			
			//show the errors
			$('#contactFormErrorCntr').css('display', 'block');
			$('#contactFormErrorCntr').addClass('errorCntr');
			$('#contactFormErrorCntr').removeClass('successContact');
			$('#contactFormErrorCntr').animate({height: minusHeight + 'px'}, 500, function(){$('#contactFormErrorCntr').append(errorMessage);});
			$('#contactFormErrorCntr').animate({opacity: 1}, 500);
			
			return false;
		}
		else
		{
			hideErrors(0);
			
			//form is valid, but append spamto subject if spam_check has text
			var isSpam = false;
			if($('#spam_check').val() != '')
			{
				//could be spam
				isSpam = true;
			}
			
			var subjectTxt = (isSpam == true) ? 'Spam: ' + $('#form_subject').val() : $('#form_subject').val();
			var dataString = 'n='+ $('#form_name').val() + '&e=' + $('#form_email').val() + '&s=' + subjectTxt + '&m=' + $('#form_message').val();
			
			//alert (dataString);return false;
			$.ajax(
			{
				type: "POST",
				url: "bin/contactFormSubmit.php",
				data: dataString,
				success: function() 
				{
					$('#contactFormErrorCntr').html('');
					$('#contactFormErrorCntr').html('<span class="successTitle">Good Stuff!</span>')
					.append("<p>We will be in touch soon.</p>")
					.hide()
					.fadeIn(500, function() 
					{
						//$('#message').append("<img id='checkmark' src='images/check.png' />");
					});
					
					$('#form_message').animate({height: 75 + 'px'}, 100);
					$('#contactFormErrorCntr').css('display', 'block');
					$('#contactFormErrorCntr').animate({height: '50px'}, 100);
					$('#contactFormErrorCntr').animate({opacity: 1}, 100);
					
					resetForm();
				},
				statusCode: 
				{
					404: function() 
					{
						doFourOhhFourError();
					}
				},
				error:(function(){ doFourOhhFourError(); })
			});
			
			return false;
		}
	});
	
});

function doFourOhhFourError()
{
	$('#contactFormErrorCntr').html('');
	$('#contactFormErrorCntr').html('<span class="errorTitle">What in blazes?</span>')
	.append("<p>This should never have happened! But it did... Your data was valid but it still failed. Weird! Can you check your connection and try again - please. Thanks!</p>")
	.hide()
	.fadeIn(500, function() 
	{
		//$('#message').append("<img id='checkmark' src='images/check.png' />");
	});
	
	$('#form_message').animate({height: 75 + 'px'}, 100);
	$('#contactFormErrorCntr').css('display', 'block');
	$('#contactFormErrorCntr').animate({height: '50px'}, 100, function()
	{
		$('#contactFormErrorCntr').addClass('errorCntr');
		$('#contactFormErrorCntr').removeClass('successContact');	
	});
	
	$('#contactFormErrorCntr').animate({opacity: 1}, 100);
}

function hideErrors(errorsRemaining)
{
	var minusHeight = 25 * errorsRemaining;
	minusHeight = Math.max(minusHeight, 75);
			
	$('#form_message').animate({height: 150 - minusHeight + 'px'}, 100);
	
	//show the errors
	$('#contactFormErrorCntr').html('');
	$('#contactFormErrorCntr').animate({height: minusHeight + 'px'}, 100);
	$('#contactFormErrorCntr').animate({opacity: 0}, 100, function()
	{
		if(errorsRemaining == 0)
		{
			$('#contactFormErrorCntr').css('display', 'none');
			$('#contactFormErrorCntr').removeClass('errorCntr');
			$('#contactFormErrorCntr').addClass('successContact');	
		}
	});
}

function resetForm()
{
	$('#contactForm input, #contactForm textarea').each(function()
	{
		$(this).val($(this).attr('rel'));
	});
}

function scrollWin(scrollToItemID, speed)
{
	$('html,body').animate(
	{
		scrollTop: $("#" + scrollToItemID).offset().top
	}, speed);
}

function isValidEmailAddress(emailAddress) 
{
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
};
