$(function(){
	//$('#validaEmail').hide();
	$('#validaLogin').hide();
	
	$('#data').mask("99/99/9999");
	$('#telephone').mask("(99)9999-9999");
	$('#cpf').mask("999.999.999-99");
	
	$('#nome-remetente').click(function(){
		var val = $(this).val();
		if(val == 'Seu nome'){
			$(this).val('');
		}
	});
	$('#nome-remetente').blur(function(){
		var val  = $(this).val();
		if(val == ''){
			$(this).val('Seu nome');
		}	
	});
	
	$('#nome-destinatario').click(function(){
		var val = $(this).val();
		if(val == 'Nome do(a) amigo(a)'){
			$(this).val('');
		}
	});
	$('#nome-destinatario').blur(function(){
		var val  = $(this).val();
		if(val == ''){
			$(this).val('Nome do(a) amigo(a)');
		}	
	});
	
	$('#email-destinatario').click(function(){
		var val = $(this).val();
		if(val == 'Email do(a) amigo(a)'){
			$(this).val('');
		}
	});
	$('#email-destinatario').blur(function(){
		var val  = $(this).val();
		if(val == ''){
			$(this).val('Email do(a) amigo(a)');
		}	
	});	
	
	$('#botao-indique').click(function(){
		
		$.post('ajax/inviteFriends.php',{remetente         : $('#nome-remetente').val(),
										 destinatario      : $('#email-destinatario').val(),
										 destinatario_nome : $('#nome-destinatario').val(),
										 msg			   : 1
										 },
										 function(data){
											 	$('#msg-email').remove();
											 	$('<label class="error"></label>').attr({id : 'msg-email'}).text(data).fadeIn('slow').insertAfter('#botao-indique');
											 	return false;
										 });
		return false;
	});
	
	$('#botao-nopass').click(function(){
		$.post('ajax/esqueciSenha.php',{destinatario : $('#passEmail').val(),msg:2},function(data){
			$('#msg').remove();
			$('<label></label>').attr({id :'msg'}).text(data).insertAfter('#botao-nopass');
		});
		return false;
	});
	
	$('#botao-newPass').click(function(){
		$.post('ajax/updatePass.html',{senha : $('#novaSenha').val(),token:$('#token').val()},function(data){
			$('#msg').remove();
			$('<label></label>').attr({id :'msg'}).text('Senha alterada com sucesso!').insertAfter('#botao-newPass');
		});
		return false;
	});
	
	$('#botao-comentar').click(function(){
		var video_id   = $('#id_video').val();
		var nome       = $('#nome').val();
		var email      = $('#email').val();
		var comentario = $('#comentario').val();
		if(nome ==''){
			alert('O campo nome deve ser preenchido!');
			return false;
		}
		if(comentario !=""){
			$.post('ajax/adicionarComentario.php',{video_id:video_id,nome:nome,email:email,comentario:comentario},
					function(data){
							$('<div />').html(data).fadeIn('slow').prependTo('#listComents');
					});
			$('#nome').val('');
			$('#email').val('');
			$('#comentario').val('');
			alert("Comentário enviado com sucesso! Aguarde sua aprovação");
			/*
			$('html, body').animate({
				    scrollTop: $("#listComents").offset().top
				}, 2000);
				*/
		}else{
			alert('O campo comentário deve ser preenchido!');
			return false;
		}
		return false;
	});
	
});

var errors = 0 ; 
function verifyLogin(val){
	var str = val;
	var cont= str.length;
	var filter = /^[A-Za-z\d]{3,15}$/;
;
	if(!filter.test(str)){
		$("#valLogin").fadeOut('slow').remove();
		$('<label class="error"></label>').attr({id : "valLogin"}).fadeIn('slow').text("Não são permitidos espaços, números ou acentos!").insertAfter('#login');
		return false;
	}
	if(cont >=3){
		$.post('verifyUser.php',{login : val},function(data){
			$("#valLogin").fadeOut('slow').remove();
			var valido = parseInt(data);
			if(valido == 0 ){
				$('<label class="error"></label>').attr({id : "valLogin"}).fadeIn('slow').text("Este login esta sendo usado").insertAfter('#login');
				return false;
			}else{
				return true;
			}
			
			
		});
	}else{
		$("#valLogin").fadeOut('slow').remove();
		$('<label class="error"></label>').attr({id : "valLogin"}).fadeIn('slow').text("Sem caracteres suficientes").insertAfter('#login');
		return false;
	}	
}

function verifyEmail(val){
			if(val ==""){
		    	$('#valEmail').remove();
		    	$('<label class="error"></label>').attr({id : "valEmail"}).fadeIn('slow').text("O campo deve ser preenchido").insertAfter('#email');
				return false;
			}
		    var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
		    if(filter.test(val)){
		    	$('#valEmail').remove();
				$.post('verifyEmail.php',{email : val},function(data){
					$("#valEmail").fadeOut('slow').remove();
					var valido = parseInt(data);
					if(valido == 0 ){
						$('<label class="error"></label>').attr({id : "valEmail"}).fadeIn('slow').text("Este email já esta sendo usado!").insertAfter('#email');
						return false;
					}else{
						return true;
					}
				});		    	
		    }else{
		    	$('#valEmail').remove();
		    	$('<label class="error"></label>').attr({id : "valEmail"}).fadeIn('slow').text("Endereço de email invalido").insertAfter('#email');
		      return false;
		    }
}

function verifyDate(val){
	if(val ==""){
		$('#valData').remove();
		$('<label class="error"></label>').attr({id : 'valData'}).fadeIn('slow').text("O campo deve ser preenchido").insertAfter("#data");
		return false;
	}
	var filter = /^\d{1,2}\/\d{1,2}\/\d{1,4}$/;
	if(filter.test(val)){
		$('#valData').remove();
		return true;
	}else{
		$('#valData').remove();
		$('<label class="error"></label>').attr({id : 'valData'}).fadeIn('slow').text("Formato de data invalido").insertAfter("#data");
		return false;
	}
	
}


function verifyCpf(val){
	  var blank = val.replace(".","");
	  blank = blank.replace(".","");
	  blank = blank.replace("-","");
	  cpf = blank;
      erro = new String;
      if (cpf.length < 11) erro += "O campo deve ser preenchido!";
      var nonNumbers = /\D/;
      if (nonNumbers.test(cpf)) erro += "A verificacao de CPF suporta apenas numeros!";
      if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || 
          cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "" ||
          cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
                erro += "<br />Numero de CPF invalido!"
      }
      var a = [];
      var b = new Number;
      var c = 11;
      for (i=0; i<11; i++){
              a[i] = cpf.charAt(i);
              if (i < 9) b += (a[i] * --c);
     }
      if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
      b = 0;
      c = 11;
      for (y=0; y<10; y++) b += (a[y] * c--);
      if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
      if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
              erro +="CPF Invalido";
      }
      if (erro.length > 0){
    	  	  $("#valCpf").fadeOut('slow').remove();	
              $('<label class="error"></label>').attr({id : "valCpf"}).fadeIn('slow').html(erro).insertAfter('#cpf');
              return false;
      }else{
    	  $("#valCpf").fadeOut('slow').remove();
    	  return true; 
      }
      
		          	
}

function verifyPwd(val){
	var senha = $('#senha').val();
	
	if(senha =='' ){
		$('#valSenha2').fadeOut('slow').remove();
		$('<label class="error"></label>').attr({id : "valSenha2"}).fadeIn('slow').text('O campo senha deve ser preenchido').insertAfter('#senha2');
		return false;
	}else if(val !="" && senha !=""){
		if(senha != val){
			$('#valSenha2').fadeOut('slow').remove();
			$('<label class="error"></label>').attr({id : "valSenha2"}).fadeIn('slow').text('Senha Invalida').insertAfter('#senha2');
			return false;
		}else{
			$('#valSenha2').fadeOut('slow').remove();
			return true;
		}
	}else{
		$('#valSenha2').fadeOut('slow').remove();
		return true;
	}
}

function checkIsBlank(val,after){
	if(val == ""){
		$('#val'+after).fadeOut('slow').remove();
		$('<label class="error"></label>').attr({id : 'val'+after}).fadeIn('slow').text('O campo deve ser preenchido').insertAfter('#'+after);
		return false;
	}else{
		$('#val'+after).fadeOut('slow').remove();
		return true;
	}
}

function verifySex(){
	var tipo = $("input[@name='sexo']:checked").val();
	if(tipo == undefined){
		$("#valSex").remove();
		$('<label class="error"></label>').attr({id : 'valSex'}).fadeIn('slow').text('O campo deve ser preenchido').insertBefore('label[for=foto]');
		return false;
	}else{
		$("#valSex").remove();
		return true;
	}
}

function verifyAcceptance(){
	var tipo = $("#aceito:checked").val();
	if(tipo == undefined){
		$("#valAceito").remove();
		$('<label class="error"></label>').attr({id : 'valAceito'}).fadeIn('slow').text('Você precisa aceitar o regulamento para participar').insertAfter('label[for=aceito]');
		return false;
	}else{
		$("#valAceito").remove();
		return true;
	}
}

function submitForm(){
	//verifyAcceptance();
	//verifySex();
	var key = new Array();
	key.push(verifyAcceptance() );
	key.push(verifySex() );
	key.push(verifyEmail($('#email').val()) );
	key.push(verifyLogin($('#login').val()) );
	key.push(verifyDate($('#data').val()));
	key.push(checkIsBlank($('#senha').val(),'senha'));
	key.push(verifyPwd($('#senha2').val()));
	key.push(verifyCpf($('#cpf').val()));	
	var validacoes = ['nome','responsavel','endereco','bairro','city','telephone','escEstado','EscCidade','ListEscola','professor'];
	var cont = validacoes.length;
	
	for(var i = 0; i < cont ; i++){
		key.push(checkIsBlank($('#'+validacoes[i]).val(), validacoes[i]));
	}
	for(var k in key ){
		if(key[k] ==false ){
			return false;
		}
	}
	if ($("#facebook").val() == document.getElementById('facebook').defaultValue) $("#facebook").val('');
	if ($("#formspring").val() == document.getElementById('formspring').defaultValue) $("#formspring").val('');
	if ($("#orkut").val() == document.getElementById('orkut').defaultValue) $("#orkut").val('');
	if ($("#twitter").val() == document.getElementById('twitter').defaultValue) $("#twitter").val('');
	return true;
	
}



