// John's form handling ajaxy validating super script
// 
// - right now the form has to be id='form'
// - if you want to change that you can figure it out below in the first set of functions


$(document).ready(function(){
	$('#form').ajaxSubmit('#form');
});
	
/**
 * Clear Value function
 * If you want a field to clear when focused on just give it a class of 'clearvalue'
 */
 
$(document).ready(function(){
						   
	$(".clearvalue").each(function(){
		var intValue = $(this).val();
		$( this ).bind('focus',
			function(){
				$(this).val('');
			}
		);
		$(this).bind('blur',
			function(){
				if ($(this).val() == ''){
					$(this).val(intValue);
				}
			}
		);
	});
});


// I'm not going to say don't edit below, there's lots of ways to tweak this, just be careful


/**
 * Submit this with Ajax
 */
jQuery.fn.ajaxSubmit = function(foo, conf) {
        var config = {
                method: false,  // request method (get/post) defaults to form's
                action: false,  // action (url) defaults to form's
                loading: 'Sending'
        };
        config = jQuery.extend(config, conf);

        var callback = (typeof(foo) === 'string') ? function(data) {jQuery(foo).html(data);} : (typeof(foo) === 'function') ? foo : false;

        return this.each(function() {
                var form = jQuery(this);

                if(form.is('form')) {
									
                        var method = config.method || form.attr('method');
                        var action = config.action || form.attr('action');
                        var submit = jQuery('input[type="submit"]', form);
                        var data = {};

                        form.submit(function() {
											 		
								if ($("#form").valid() == true) {
													
										jQuery('*[name]', form).each(function() {
												var t = jQuery(this);
												var val = (t.attr('type') == 'checkbox') ? (t.attr('checked') == true) ? 1 : 0 : t.val();
												data[t.attr('name')] = val;
										});
										submit.val(config.loading);
										jQuery[method](action, data, function(data) {
												callback(data);
										});
										$('#form').addClass('success');
										
								};

                                return false;
                        });
                }
        });
};