$(document).ready(function() {        
	function sprawdz() {
		//$("#formularzRejestracji p.blad").remove();
		$.ajax({
				type: "POST",
					dataType: 'json',
					url:  '/profil/ajaxValidate',
					data: $("#formularzRejestracji").serialize(),
					success: function(json) {
					if (json.status=='ok') {
						
					}
					else {
						for (var key in json.errors) {
							pokazBlad(json.errors[key], $("#"+key));
						}
					}
				}});
	};
	
	function pokazBlad(text,gdzie) {
		var html="<span>x</span>"+text;
		var p = $("<p></p>").addClass('blad').html(html).hide();
		p.insertAfter(gdzie).fadeIn(500);;
	}
	
	$("input#nick").blur(function() {
			if (!$(this).val()) {
				pokazBlad("Musisz coś wprowadzić", $(this));
			}
			else {
				sprawdz();
			}
		});

	$("input#email").blur(function() {
			if (!$(this).val()) {
				pokazBlad("Musisz coś wprowadzić", $(this));
			}
			else {
				sprawdz();
			}
		});

	$("input#haslo").blur(function() {
			if (!$(this).val()) {
				pokazBlad("Musisz coś wprowadzić", $(this));
			}
			else {
				sprawdz();
			}
		});

	$("input#powtorzHaslo").blur(function() {
			if (!$(this).val()) {
				pokazBlad("Musisz coś wprowadzić", $(this));
			}
			else if ($("#haslo").val()) {
				if ($(this).val()!=$("#haslo").val()) {
					pokazBlad("Hasła się nie zgadzają", $(this));
				}
			}
		});
	
	$("input").focus(function() {
			$(this).siblings('p.blad').fadeOut(500,function () {$(this).remove();});
		});

	$("#formularzRejestracji").submit(function() {
			$("#formularzRejestracji p.blad").fadeOut(500, function() {$(this).remove();});
			//ostateczna walidacja:
			var error = false;
			$("#formularzRejestracji input").each(function() {
					if (!$(this).val()) {
						error = true;
						pokazBlad("Musisz coś wprowadzić", $(this));
					}                        
				});
			//regulamin:
			if (!$("#akceptujeRegulamin").is(":checked")) {
				error = true;
				pokazBlad('Musisz zaakceptować regulamin', $("#akceptujeRegulamin").parent('label'));
			}
			if (!error) {
				sprawdz();
				if ($('#formularzRejestracji p.blad').length)
					error = true;
				if ($("#powtorzHaslo").val()!=$("#haslo").val()) {
					error = true;
					pokazBlad("Hasła się nie zgadzają", $("#powtorzHaslo"));
				}                    
			}
			if (!error)
				return true;
			return false;
		});
	
	$('.modalUp[title=regulamin]').click(function() {
		if(!$('#modalRegulamin').length) {
			newModal(this, '/strony/regulamin', function() {
				var modal = $('#modalRegulamin');
				modal.find('button').click(function(e) {
					$('#akceptujeRegulamin').attr('checked', true);
					$('#modal > div').hideModal();
					e.preventDefault();
				});
			}, 'true');
		}
	});
});
