var scrollCheckEnabled = true;
var positions = [];

$(function()
{
	// Nav menu highlight
	$('#menu > li').click(function(e)
	{
		var $this = $(this);
		var href = $this.find('a').attr('href').replace(/^#/, '');
		
		$this.addClass('active').siblings().removeClass('active');
		
		if (href)
		{
			var anchor = $('a[name="' + href + '"]');
			if (anchor.size())
			{
				scrollCheckEnabled = false;
				$('html, body').stop().animate({
					scrollTop: anchor.offset().top-140
				}, 1000,'easeInOutExpo', function()
				{
					scrollCheckEnabled = true;
					//location.hash = href;
				});
				
				e.preventDefault();
			}
		}
		else
		{
			e.preventDefault();
		}
	});
	
	// Nav menu highlight - unbind nav menu link as <li> is now the link
	$('#menu > li a').unbind().click(function(e)
	{
		e.preventDefault();
	
		$(this).parents('li').click();
	});
	
	// Request quote buttons
	$('.request-quote').unbind().click(function(e)
	{
		e.preventDefault();
	
		$('#menu a:eq(4)').click();
	});
	
	// Determine anchor positions for scroll event
	$('.container a[name]').reverse().each(function()
	{
		var $this = $(this);
		
		//if (console) console.log('position: ', $this.offset().top, 'anchor: ', $this.attr('name'));
		positions.push({ 'position': $this.offset().top, 'anchor': $this.attr('name') });
	});
	
	// Check scroll location on page load
	scrollCheck();
	
	// Hook document scroll to highlight menu item
	$(document).scroll(function()
	{
		scrollCheck();
	});
	
	// Contact Us Form
	$('form').submit(function(e)
	{
		// Prevent default submit action
		e.preventDefault();
	
		// Variables
		var $this = $(this);
		var $submitButton = $this.find('input[type="submit"]');
		var $formElements = $this.find('input, select, textarea').not($submitButton);
		var errors = [];
		var email = $this.find('input[name="Email"]');
		
		// Disable form
		$submitButton.attr('disabled', 'disabled').attr('value', 'Checking...');
		
		// Remove previous errors
		$formElements.removeClass('error');

		// All elements are required
		$formElements.each(function()
		{
			var $thisElement = $(this);
			
			if ($thisElement.val() == '')
			{
				errors[errors.length] = new Array($thisElement.attr('id'), 'is a required field');
			}
		});
		
		if (!email.is('*') || !email.val().match(/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]{2,})+$/))
		{
			errors[errors.length] = new Array(email.attr('id'), 'is not valid');
		}
		
		if (errors.length > 0)
		{
			var errorString = [];
			for (var i in errors)
			{
				$this.find('#' + errors[i][0]).addClass('error');
				
				errorString[errorString.length] = $this.find('label[for="' + errors[i][0] + '"]').html() + ' ' + errors[i][1];
			}
			
			alert("The following fields contained errors:\n\n* " + errorString.join("\n* ") + "\n\nPlease correct these errors and try again");
					
			$submitButton.removeAttr('disabled').attr('value', 'Send');
			
			return;
		}

		$submitButton.attr('value', 'Sending...');

		// Success - do AJAX
		$.ajax({
			'url'		: '/contact.php', // $this.attr('action'),
			'type'		: $this.attr('method'),
			'data'		: $formElements.serialize(),
			'dataType'	: 'json',
			'success'	: function(data)
			{
				if (data['error'])
				{
					var errorString = [];
					for (var i in data['error'])
					{
						$this.find('#' + data['error'][i][0]).addClass('error');
						
						errorString[errorString.length] = $this.find('label[for="' + data['error'][i][0] + '"]').html() + ' ' + data['error'][i][1];
					}
					
					alert("The following fields contained errors:\n\n* " + errorString.join("\n* ") + "\n\nPlease correct these errors and try again");
					
					$submitButton.removeAttr('disabled').attr('value', 'Send');
				}
				else if (data['success'] == 1)
				{
					alert('Contact successfully sent! Please allow up to 72 hours for a response');
					$submitButton.removeAttr('disabled').attr('value', 'Contact Sent! Send another?');
					$formElements.val('');
				}
				else
				{
					alert('Unexpected error, please try again');
					$submitButton.removeAttr('disabled').attr('value', 'Send');
				}
				
			},
			'error'		: function()
			{
				$submitButton.removeAttr('disabled').attr('value', 'Send');
				alert('Unexpected error, please try again');
			}
		});
	});
});

function scrollCheck()
{
	if (!scrollCheckEnabled)
	{
		return;
	}

	var scrollPosition = $(document).scrollTop();
	
	for (var i in positions)
	{
		//if (console) console.log('scrollPosition: ', scrollPosition, ', position: ' + positions[i]['position'] + ', anchor: ' + positions[i]['anchor']);
		if (scrollPosition >= (positions[i]['position'] - 300))
		{
			// Set menu item as active
			$('a[href="#' + positions[i]['anchor'] + '"]').parent().addClass('active').siblings().removeClass('active');
			return;
		}
	}
}

jQuery.fn.reverse = [].reverse;

