// ***************************************************************
// ***************************************************************
// ***************************************************************
// Forms Javascript


//Listen for forms that require validation
$(document).ready(function(){
	$('form').each(function(i){					
		if($(this).find(':input[name="_val"]').length == 1){
			validate_init($(this));	
		}
	});
	
});

// ***************************************************************
// ***************************************************************
// Validatation Init
// Registers a form as an ajax validated form

function validate_init( form )
{
	if( form && form != null )
	{
		$(form).submit(function(){
			setTimeout( function(){ validate_send(form) }, 500 );
			return false;												  
		});
	}
}

// ***************************************************************
// ***************************************************************
// validate send
// build and send the validation request

function validate_send( form )
{
	val = $(form).find(':input[name="_val"]').val();
	//create the request
	var request = {
		val:val,
		name:$(form).attr('name'),
		fields:form.serialize()
	};
	$.post( '/validate', request, function(data){
		if(data){
			if( data.error==false ){
				//submit the form
				form.attr('onsubmit', 'return true;');
				form.unbind('submit');
				form.submit();
				form.find(':submit').click();
				
			} else {
				//show the errors
				//clear all the old imput errors
				$('.form-input-error').remove();
				
				$.each( data.items, function(field_name, error_message){
											 
					field_id = field_name.replace('_','-')+'-error';
					
					//check if the error exists
					if($('span#'+field_id).length > 0){
						$('span#'+field_id).remove();
					}
					//add the error message to the field
					form.find('#'+field_name).parent().append('<span id="'+field_id+'" class="form-input-error">'+error_message+'</span>');
				});
			}
		}
	},'json');
}


// ***************************************************************
// ***************************************************************
//Move tab on last key entry
function move_on_max( field, next_field_id ) {	
	if( $(field).val().length >= $(field).attr('maxLength') ){
		$('#'+next_field_id).focus();
	}
}