var errorTooltipOverrides = {
	'cc_month'		: { 'gravity': 'e' },
	'cc_security_number'	: { 'gravity': 'n' }	
}
var errorTooltipDefaults = {
	'trigger'	: 'manual',
	'fade'		: true,
	'tipsyClass'	: 'red',
	'opacity'	: 1,
	'gravity'	: 'w'
}
var ignoreFields = ['shipping_address2', 'company', 'address2'];

$(function()
{
	$('#top-slider').nivoSlider();
	$('#bottom-slider').nivoSlider();
	
	$('#shipping_form').unbind().submit(function()
	{
		// Variables
		var $form = $(this);
		var $inputs = $form.find('input, select, textarea').not('[type="hidden"]').not('[type="submit"]');
		var $email = $('#email_address');
		
		// Reset
		$('.tipsy').remove();	
		$inputs.removeClass('error');
		
		// General check
		$inputs.each(function()
		{
			var $input = $(this);
			var id = $input.attr('id');
			
			// $.inArray returns -1 on no match, int index element on match
			if (id && $.inArray(id, ignoreFields) === -1)
			{
				var labelTitle = $('label[for="' + id + '"]');
				
				if (labelTitle.size())
				{
					labelTitle = labelTitle.html().replace(/:[ ]{0,}/, '');

					if ($input.val() == '')
					{
						$input.addClass('error').attr('title', labelTitle + ' is a required field').tipsy($.extend({}, errorTooltipDefaults, errorTooltipOverrides[id] || {})).tipsy('show');
					}
					else if (!$input.is('select') && $input.val().length < 2)
					{
						$input.addClass('error').attr('title', labelTitle + ' is too short').tipsy($.extend({}, errorTooltipDefaults, errorTooltipOverrides[id] || {})).tipsy('show');
					}
				}
			}
		});
		
		// Email
		if (!$email.val().match(/.*@.*\..*/))
		{
			var $input = $email;
			var id = $input.attr('id');
			var labelTitle = $('label[for="' + id + '"]').html().replace(/:[ ]{0,}/, '') + ' is not a valid';
				
			$input.addClass('error').attr('title', labelTitle).tipsy($.extend({}, errorTooltipDefaults, errorTooltipOverrides[id] || {})).tipsy('show');
		}
		
		return ($('.error').size() ? false : true);
	});
	
	$('#billing').after('<p><input type="checkbox" id="copy_info" value="1" /> Same as billing information</p>');
	$('#copy_info').live('click', function()
	{
		var $this = $(this);
		var checked = $this.attr('checked');
		var variables = ['shipping_first_name', 'shipping_last_name', 'shipping_address', 'shipping_address2', 'shipping_city', 'shipping_state', 'shipping_zip'];
		
		for (var i in variables)
		{
			$('#' + variables[i]).val( (checked ? $('#' + variables[i].replace(/shipping_/, '')).val() : '') );
		}
	});
});
