$.fn.submitForm = function(){
	return $(this).find('.submit').live('click', function(){
		submitForm($(this).parent('form'));
	});
}

$.fn.validateInput = function(){
	return $(this).live('focus keyup', function(){
	
		img_check		= '<img src="/static/image/check.png">';
		img_pen			= '<img src="/static/image/potlood.png">';
		img_warning		= '<img src="/static/image/letop.png">';
		
		$(this).removeClass('redBorder');
		
		if($(this).hasClass('validate_local')){
			if($(this).val() != ''){
				$(this).next('.exception').html(img_check);
			}else{
				$(this).next('.exception').html(img_pen);
			}
		}
		
		if($(this).hasClass('validate_server')){
			exception 	= $(this).siblings('.exception');
			$.ajax({
				dataType: 	'json',
				url: 		'/ajax/validate/',
				data:		$(this).serialize(),
				success:	function(json){
					if(json.image && json.exception){
						exception.html('<img src="'+json.image+'" /><p>'+json.exception+'</p>');
					}else if(json.image){
						exception.html('<img src="'+json.image+'" />');
					}
					else {
						exception.html('<p>'+json.exception+'</p>');
					}
				}
			});
		}
		
	});
}


function submitForm(element){
	img_check		= '<img src="/static/image/check.png">';
	img_pen			= '<img src="/static/image/pen.png">';
	img_warning		= '<img src="/static/image/letop.png">';

	form 			= element;
	total 			= form.find('.validate_server, .validate_local').length;
	count 			= new Array();
	count.length 	= 0;
	
	$('.validate_local').each(function(){
		if($(this).val() != ''){
			$(this).next('.exception').html(img_check);
			count++;
			if(total == count){
				form.submit();
			}
		}else{
			$(this).addClass('redBorder');
			$(this).next('.exception').html(img_pen);
		}
	});
	
	$('.validate_server').each(function(){

		input		= $(this);
		exception 	= $(this).next('.exception');
		$.ajax({
			dataType: 	'json',
			async:		false,
			url: 		'/ajax/validate/',
			data:		$(this).serialize(),
			success:	processJson
		});
	});
	
	function processJson(json){
		if(json.image && json.exception){
			exception.html('<img src="'+json.image+'" /><p>'+json.exception+'</p>');
		}else if(json.image){
			exception.html('<img src="'+json.image+'" />');
		}
		else {
			exception.html('<p>'+json.exception+'</p>');
		}
		if(json.status == true){
			count++;
			if(total == count){
				form.submit();
			}
		}else{
			input.addClass('redBorder');
		}
	}
}


