
var validate = false;

function Validacao(form) {

	var $this = this;
	$this.form = $(form);
	
	$this.element = function(name) {
		return $this.form.find('input[name="'+name+'"], select[name="'+name+'"], textarea[name="'+name+'"]');
	}

	$this.require = function(element) {
		if ((element.val() == '') || (element.val() == element.attr('lang'))) {
			return false;
		}

		return true;
	}
}

function valida_comentario() {
	jQuery('#frm_comentario').submit(function() {
		var val = new Validacao('#frm_comentario');
		clear(jQuery('#frm_comentario'));
		var comentario = val.element('comentario');

		if (comentario.val() == 'Digite o Texto Aqui!' || comentario.val() == '') {
			error(comentario);
		}

		if (validate) {

			RedesConnect.getLoginStatus(function(logado) {
				if (logado) {
					if (jQuery('.hands_box a.desabilitado').length == 0) {
						jQuery.facebox('Você precisa escolher se aprova ou desaprova este post antes de deixar um comentário.');
					} else {
						jQuery('#frm_comentario').unbind().submit();
					}
				} else {
					jQuery.facebox('Faça login no site ou use o seu login do Twitter ou Facebook para deixar o seu comentário.');
				}
			});
		}

		return false;
	});
}

function valida_cadastro(mod) {
	var val = new Validacao('#frm_cadastro_' + mod);
	clear(jQuery('#frm_cadastro_' + mod));
	
	var email = val.element('email');
	var senha = val.element('senha');
	var conf_email = val.element('conf_email');
	var conf_senha = val.element('conf_senha');

	// Primeiro Form
	if (checkMail(email.val()) == false) {
		error(email);
	}

	if (checkMail(conf_email.val()) == false) {
		error(conf_email);
	}

	if (email.val() != conf_email.val()) {
		error(conf_email);
	}

	if (mod == 'insere' || mod == 'insere_promo') {
		if (val.require(senha) == false)
			error(senha);

		if (val.require(conf_senha) == false)
			error(conf_senha);

		if (senha.val() != conf_senha.val()) {
			error(conf_senha);
		}
	}
	else {
		if (val.require(senha)) {
			if (val.require(conf_senha) == false)
				error(conf_senha);

			if (senha.val() != conf_senha.val()) {
				error(conf_senha);
			}
		}
	}
	
	

	// Segundo Form
	var nome = val.element('nome');
	var resposta = val.element('resposta');
	var cpf = val.element('cpf');
	var ddd_tel = val.element('telefone_ddd');
	var tel = val.element('telefone');
	var ddd_cel = val.element('celular_ddd');
	var cel = val.element('celular');
	var cidade = val.element('cidade');
	var estado = val.element('estado');
	//console.info(val);
	if (val.require(nome) == false)
		error(nome);

	if ( ! valCPF(cpf.val())) {
		error(cpf);
	}

	if ( ! ddd_tel.val().match(/^\d\d$/)) {
		error(ddd_tel);
	}

	if ( ! tel.val().match(/^\d{4}-\d{4}$/)) {
		error(tel);
	}
	if ( ! ddd_cel.val().match(/^\d\d$/)) {
		error(ddd_cel);
	}

	if ( ! cel.val().match(/^\d{4}-\d{4}$/)) {
		error(cel);
	}

	if (val.require(cidade) == false)
		error(cidade.parent().find('.select_fake'));
	if (val.require(estado) == false)
		error(estado.parent().find('.select_fake'));

	if (jQuery('#frm_cadastro input[name="sexo"]:checked').length == 0) {
		jQuery('#frm_cadastro input[name="sexo"]').each(function() {
			jQuery(this).parent().addClass('error');
		});
	}
	
	if (mod == 'insere_promo') {
		
		if (val.require(resposta) == false)
			error(resposta);

	}

	return validate;
}

function valida_cadastro_completo(mod) {
	var result = valida_cadastro(mod);

	var val = new Validacao('#frm_cadastro_' + mod);

	var login_twitter = val.element('login_twitter');
	var senha_twitter = val.element('senha_twitter');

	var login_foursquare = val.element('login_foursquare');
	var senha_foursquare = val.element('senha_foursquare');

	var login_facebook = val.element('login_facebook');
	var senha_facebook = val.element('senha_facebook');

	if ((login_twitter.val() != '' && login_twitter.val() != 'Login') || senha_twitter.val() != '') {
		if (val.require(login_twitter) == false) {
			error(login_twitter);
		}

		if (senha_twitter.val() == '') {
			error(senha_twitter);
		}
	}

	if ((login_foursquare.val() != '' && login_foursquare.val() != 'Login') || senha_foursquare.val() != '') {
		if (val.require(login_foursquare) == false)
			error(login_foursquare);

		if (senha_foursquare.val() == '') {
			error(senha_foursquare);
		}
	}

	if ((login_facebook.val() != '' && login_facebook.val() != 'Login') || senha_facebook.val() != '') {
		if (val.require(login_facebook) == false)
			error(login_facebook);

		if (senha_facebook.val() == '') {
			error(senha_facebook);
		}
	}

	result = result && validate;

	return result;
}

jQuery(document).ready(function(){
	$('#frm_cadastro_insere').submit(function(event, tipo) {
		var result = false;

		if (tipo == 'simples') {
			result = valida_cadastro('insere');
		}
		else {
			result = valida_cadastro_completo('insere');
		}

		if (result) {
			$.ajax({
				type: "POST",
				url: base_url + "cadastro/ajax_existe_email_principal",
				data: {
					email: $('#frm_cadastro_insere input[name="email"]').val()
				},
				success: function(msg){
					if (msg == '1') {
						jQuery.facebox('O e-mail já está sendo usado por outro usuário');
						error('#frm_cadastro_insere input[name="email"]');
					} else {
						$("#frm_cadastro_insere").unbind();
						$("#frm_cadastro_insere").submit();
					}
				}
			});
		}

		return false;
	});
	$('#frm_cadastro_insere_promo').submit(function(event, tipo) {
		var result = false;

		if (tipo == 'simples') {
			result = valida_cadastro('insere_promo');
		}
		else {
			result = valida_cadastro_completo('insere_promo');
		}

		if (result) {
			$.ajax({
				type: "POST",
				url: base_url + "cadastro/ajax_existe_email_principal",
				data: {
					email: $('#frm_cadastro_insere_promo input[name="email"]').val()
				},
				success: function(msg){
					if (msg == '1') {
						jQuery.facebox('O e-mail já está sendo usado por outro usuário');
						error('#frm_cadastro_insere_promo input[name="email"]');
					} else {
						$("#frm_cadastro_insere_promo").unbind();
						$("#frm_cadastro_insere_promo").submit();
					}
				}
			});
		}

		return false;
	});
	
	$('#frm_cadastro_insere_promo_logado').submit(function(event, tipo) {
		var val = new Validacao('#frm_cadastro_insere_promo_logado');
		clear(jQuery('#frm_cadastro_insere_promo_logado'));

		var resposta = val.element('resposta');

		if (val.require(resposta) == false){
			error(resposta);
			return false;
		}
	});
	

	$('#frm_cadastro_edita').submit(function(event, tipo) {
		var result = false;

		if (tipo == 'simples') {
			result = valida_cadastro('edita');
		}
		else {
			result = valida_cadastro_completo('edita');
		}

		if (result) {
			$.ajax({
				type: "POST",
				url: base_url + "cadastro/ajax_existe_email_principal_edita",
				data: {
					email: $('#frm_cadastro_edita input[name="email"]').val()
				},
				success: function(msg){
					if (msg == '1') {
						jQuery.facebox('O e-mail já está sendo usado por outro usuário');
						error('#frm_cadastro_edita input[name="email"]');
					} else {
						$("#frm_cadastro_edita").unbind();
						$("#frm_cadastro_edita").submit();
					}
				}
			});
		}

		return false;
	});

	valida_comentario();

	$('#frm_postar_hands').submit(function() {
		var forma = $('#forma_envio');
		var sou_responsavel = ($(this).find('input[name="sou_responsavel"]:checked').length > 0) ? true : false;
		var embed = $(this).find('input[name="embed"]');
		var imagem = $(this).find('input[name="imagem"]');
		var msg = '';

		if ( ! sou_responsavel) {
			msg += 'Você precisa concordar que é responsável pelo conteúdo do post antes de continuar.';
		}else {

			if((embed.val() == '' || embed.val() == embed.attr('lang')) && (!checkExtension(new Array('png', 'jpg', 'jpeg', 'gif'), imagem.val())))
				msg += 'Cole o embed do youtube ou selecione uma imagem para continuar.';

			if((embed.val() != '' && embed.val() != embed.attr('lang')) && (checkExtension(new Array('png', 'jpg', 'jpeg', 'gif'), imagem.val())))
				msg += 'Você não pode inserir um embed e uma imagem no mesmo post.';

			if(embed.val() != embed.attr('lang'))
				forma.val('embed');
			else
				forma.val('imagem');
//			if (forma.val() == 'embed') {
//				if (embed.val() == '' || embed.val() == embed.attr('lang')) {
//					msg += 'Cole o embed do youtube na caixa primeiro.';
//				}
//			}
//			else {
//				if (!checkExtension(new Array('png', 'jpg', 'jpeg', 'gif'), imagem.val())) {
//					msg += 'Selecione um arquivo com as extensões .jpg, .png ou .gif.';
//				}
//			}
		}

		if (msg.length != 0) {
			jQuery.facebox(msg);
			return false;
		}

		return true;
	});


	
});

function error(input) {
	$(input).addClass('error');
	validate = false;
}

function clear(obj){
	$(obj).find('.error').removeClass('error');
	validate = true;
}

function checkMail(mail){
    var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);

    if(typeof(mail) == "string"){
        if(er.test(mail)){return true;
    }
    }else if(typeof(mail) == "object"){
        if(er.test(mail.value)){
            return true;
        }
    }

	return false;
}

function valCPF(value) {
	value = value.replace('.','');
	value = value.replace('.','');
	cpf = value.replace('-','');
	while(cpf.length < 11) cpf = "0"+ cpf;
	var expReg = /^0+$|^1+$|^2+$|^3+$|^4+$|^5+$|^6+$|^7+$|^8+$|^9+$/;
	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]) || cpf.match(expReg)) return false;
	return true;
}

function checkExtension(types, value) {
	var retorno = false;

	for (i = 0; i < types.length; i++) {
		if (Right(value, types[i].length + 1).toLowerCase() == "." + types[i])
			retorno = true;
	}

	return retorno;
}

function Right(str, n)
{
	if (n <= 0) // Invalid bound, return blank string
		return "";
	else if (n > String(str).length) // Invalid bound, return
		return str; // entire string
	else { // Valid bound, return appropriate substring
		var iLen = String(str).length;
		return String(str).substring(iLen, iLen - n);
	}
}
