(function($) {

$.fn.contact = function( options )
{
	var defaults = {
		scrolltoerrors		: false,
		scrolloffset		: -30,
		confirmation		: false,
		confirmation_class	: 'confirmation',
		label_mod_class		: 'contact-modified',
		callback			: function(){
			console.log('[ERROR] Callback not found.');
		}
	};

	var o = $.extend( defaults, options );

	return this.each(function(){
		
		var form 	= $(this);
		var submit	= form.find('.submit');
		var fields	= form.find(':input[requires]');
		
		form.data('working', false);
		
		// Add Confirmation
		
		if ( false != o.confirmation )
		{
			form.prepend('<div class="' + o.confirmation_class + '">' + o.confirmation + '</div>');
		}
		
		// Mark required fields
		
		fields.each(function(){
			var field 	= $(this);
			var label 	= $(this).prev();
			
			if ( !label.hasClass(o.label_mod_class) )
			{
				label.addClass(o.label_mod_class);
				label.html( label.html() + '*' );
			}
			
			field.bind( 'focus blur keyup change click paste', function(){
				validate_input( $(this) );
			});
		});
		
		submit
		.hover(function(){
			submit.animate({ opacity: .8}, 100);
		}, function(){
			submit.animate({ opacity: 1}, 100);
		})
		.click(function(e){
			
			if ( form.data('working') == false )
			{
				form.data('working', true);
				var errors = 0;
				
				fields.each(function(){
					if ( !validate_input( $(this) ) ){
						errors++;
					}
				});
				
				if ( errors == 0 )
				{
					if (typeof o.callback == 'function')
					{
						o.callback.call(this, form);
					}
					else
					{
						alert('ERROR: Callback is not valid.');
						form.data('working', false);
					}
				}
				else
				{
					form.data('working', false);
					
					if ( true == o.scrolltoerrors )
					{
						var first_error = form.find('p.error').filter(':first');

						if ( first_error.size() )
						{
							$.scrollTo( first_error, 300, {
								axis		: 'y',
								offset		: o.scrolloffset
							});
						}
					}
				}
			}
						
			e.preventDefault();
		});
		
	});

};

$.fn.contact.test = function( form )
{
	return form;
};

function validate_input( el )
{
	var container 	= el.closest('p');
	var required 	= el.attr('requires');
	
	switch ( required )
	{
		case 'text':
			if( el.val() == '' ){
				container.addClass('error');
				return false;
			} else {
				container.removeClass('error');
			}
		break;
		case 'email':
			if( !el.val().match( /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+\_]+\.[\w\-\+_]{2,4}(\.[\w\-\+_]+)?$/ ) ){
				container.addClass('error');
				return false;
			} else {
				container.removeClass('error');
			}
		break;
		default:
			var match = required.match( /^([\!|\=])([0-9a-z\-\_]+)/ );
			if ( null != match )
			{
				if ( match[1] == '!' )
				{
					if ( match[2] == el.val() ){
						container.addClass('error');
						return false;
					} else {
						container.removeClass('error');
					}
				}
			}
		break;
	}
	
	return true;
}

})(jQuery);
