/**
 * DHTML date validation script for dd/mm/yyyy. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
function mascara(o,f){
	v_obj=o
	v_fun=f
	setTimeout("execmascara()",1)
}

function execmascara(){
	v_obj.value=v_fun(v_obj.value)
}

function leech(v){
	v=v.replace(/o/gi,"0")
	v=v.replace(/i/gi,"1")
	v=v.replace(/z/gi,"2")
	v=v.replace(/e/gi,"3")
	v=v.replace(/a/gi,"4")
	v=v.replace(/s/gi,"5")
	v=v.replace(/t/gi,"7")
	return v
}

function soNumeros(v){
	return v.replace(/\D/g,"")
}

function soAlfaNum(v){
	return v.replace(/\W/g,"")
}

function telefone(v){
	v=v.replace(/\D/g,"")                 //Remove tudo o que não é dígito
//   v=v.replace(/^(\d\d)(\d)/g,"($1) $2") //Coloca parênteses em volta dos dois primeiros dígitos
//   v=v.replace(/(\d{4})(\d)/,"$1-$2")    //Coloca hífen entre o quarto e o quinto dígitos
	v=v.replace(/(\d{2})(\d)/,"$1-$2")    //Coloca hífen entre o quarto e o quinto dígitos
	return v
}

function cpf(v){
	v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
	v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
	v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
											//de novo (para o segundo bloco de números)
	v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2") //Coloca um hífen entre o terceiro e o quarto dígitos
	return v
}

function Hm(v){
	v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
	v=v.replace(/(\d{2})(\d)/,"$1:$2")       //Coloca dois pontos entre o segundo e terceiro dígitos
	return v
}

function soCep(v){
	v=v.replace(/\D/g,"")                //Remove tudo o que não é dígito
	v=v.replace(/(\d{5})(\d)/,"$1-$2") //Esse é tão fácil que não merece explicações
	return v
}

function decimal(v){
	v=v.replace(".","")

	v=v.replace(/\D/g,"")                //Remove tudo o que não é dígito

	len=v.length

	if (len == 1)
	{
		v='00'+v
	}
	else if (len == 2)
	{
		v='0'+v
	}
	else if (len == 0)
	{
		return v
	}
	else if ((len > 2) && (v.charAt(0) == '0'))
	{
		v=v.substr(1)
	}

	v=v.replace(/(\d)(\d{2}$)/,"$1.$2")
	return v
}

function cnpj(v){
	v=v.replace(/\D/g,"")                           //Remove tudo o que não é dígito
	v=v.replace(/^(\d{2})(\d)/,"$1.$2")             //Coloca ponto entre o segundo e o terceiro dígitos
	v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3") //Coloca ponto entre o quinto e o sexto dígitos
	v=v.replace(/\.(\d{3})(\d)/,".$1/$2")           //Coloca uma barra entre o oitavo e o nono dígitos
	v=v.replace(/(\d{4})(\d)/,"$1-$2")              //Coloca um hífen depois do bloco de quatro dígitos
	return v
}


function romanos(v){
	v=v.toUpperCase()             //Maísculas
	v=v.replace(/[^IVXLCDM]/g,"") //Remove tudo o que nao for I, V, X, L, C, D ou M
	//Essa é complicada! Copiei daqui: http://www.diveintopython.org/refactoring/refactoring.html
	while(v.replace(/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/,"")!="")
		v=v.replace(/.$/,"")
	return v
}

function maiusculas(v){
	v=v.toUpperCase()
	return v
}

function minusculas(v){
	v=v.toLowerCase()
	return v
}

function site(v){
	//Esse sem comentarios para que voce entenda sozinho ;-)
	v=v.replace(/^http:\/\/?/,"")
	dominio=v
	caminho=""
	if(v.indexOf("/")>-1)
		dominio=v.split("/")[0]
		caminho=v.replace(/[^\/]*/,"")
	dominio=dominio.replace(/[^\w\.\+-:@]/g,"")
	caminho=caminho.replace(/[^\w\d\+-@:\?&=%\(\)\.]/g,"")
	caminho=caminho.replace(/([\?&])=/,"$1")
	if(caminho!="")dominio=dominio.replace(/\.+$/,"")
	v="http://"+dominio+caminho
	return v
}

function datas(v){

	v=v.replace(/\D/g,"")                           //Remove tudo o que não é dígito

	v=v.replace(/^(\d{2})(\d)/,"$1/$2")             //Coloca / entre o segundo e o terceiro dígitos

	v=v.replace(/^(\d{2})\/(\d{2})(\d)/,"$1/$2/$3") //Coloca / entre o quarto e o quinto dígitos

	return v

}
function monetario(v){

	aux =v.length
	if (aux == 4)
	{
		v=v.replace("0,","");
	}
	v=v.replace(",","");
	v=v.replace(".","");
	v=v.replace(/\D/g,"")                //Remove tudo o que não é dígito

	len =v.length

	if (len == 1)
	{
		v='00'+v
	}
	else if (len == 2)
	{
		v='0'+v
	}
	else if (len == 0)
	{
		return v
	}
	else if ((len > 2) && (v.charAt(0) == '0'))
	{
		v=v.substr(1)
	}
	v=v.replace(/(\d)(\d{2}$)/,"$1.$2");


	return v
}

//Retira a mascara de CNPJ, CPF e telefone
function retiraMacara(v)
{
	v=v.replace("/","");
	v=v.replace(".","");
	v=v.replace("-","");
	v=v.replace("(","");
	v=v.replace(")","");
	return v;
}

function validaSenha()
{
	if($('senha').value.length == 0)
		return;
	
	$('indicaSenha').style.display = '';
	if ($('senha').value.length > 5)
	{
		$('indicaSenha').className = 'certo';
	}
	else
	{
		$('indicaSenha').className = 'errado';
	}
	return;
}

function validaConfirmaSenha()
{
	if($('confirmacao').value.length == 0)
		return;
	
	$('indicaConfirmaSenha').style.display = '';
	if ($('confirmacao').value.length > 5)
	{
		if ($('senha').value == $('confirmacao').value)
			$('indicaConfirmaSenha').className = 'certo';
		else
			$('indicaConfirmaSenha').className = 'errado';
	}
	else
	{
		$('indicaConfirmaSenha').className = 'errado';
	}
	return;
}

function verificaLogin(msg,usuario)
{
	// Chamada em ajax para verificar o login
	if (usuario === undefined)
	{
		usuario = null;
	}
	
	// Faz a chamada AJAX
	$('msgCadastro').style.display = 'none';
	var url = 'validaLogin.php';
	var container = 'indicaLogin';
	var login = $('login').value;
	
	if ($('login').value.length < 6)
	{
		if (msg != 'false')
		{
			$('msgCadastro').innerHTML = 'Mínimo de 6 caracteres.';
			$('msgCadastro').style.display = '';
		}
		$(container).className = 'errado';
		$('login').value = '';
		$(container).style.display = '';
		return;
	}
	
	new Ajax.Request(url,
	{
		method:'get',
		parameters: {usr_login: login, usuario: usuario},
		onSuccess:function(transport)
		{
			// Minha ação de sucesso
			if(transport.responseText == 'true')
			{
				$(container).className = 'certo';
				$(container).style.display = '';
			}
			else
			{
				if (msg != 'false')
				{
					$('msgCadastro').innerHTML = '<strong>'+$('login').value+'</strong> já existe.';
					$('msgCadastro').style.display = '';
				}
				$(container).className = 'errado';
				$('login').value = '';
				$(container).style.display = '';
			}
		},
		onFailure:function(transport)
		{
			// Meu Erro
			//alert(transport.responseText);
		}
	});
}

function validaFormCadastro()
{
	if ($('login').value == "")
	{
		alert("Por favor preencha o Login!");
		$('login').focus();
		return false;
	}
	
	if ($('login').value.length < 6)
	{
		alert("O Login deve ter entre 6 e 15 caracteres");
		$('login').value = "";
		$('login').focus();
		return false;
	}
	
	if ($('login').value.length > 15)
	{
		alert("O Login deve ter entre 6 e 15 caracteres");
		$('login').value = "";
		$('login').focus();
		return false;
	}
	
	if ($('senha').value == "")
	{
		alert("Por favor preencha a Senha!");
		$('senha').focus();
		return false;
	}
	
	if ($('senha').value.length < 6)
	{
		alert("A senha deve ter entre 6 e 30 caracteres");
		$('senha').value = "";
		$('senha').focus();
		return false;
	}
	
	if ($('senha').value.length > 30)
	{
		alert("A senha deve ter entre 6 e 30 caracteres");
		$('senha').value = "";
		$('senha').focus();
		return false;
	}
	
	if ($('confirmacao').value == "")
	{
		alert("Por favor confirme a Senha!");
		$('confirmacao').focus();
		return false;
	}
	
	if ($('senha').value != $('confirmacao').value)
	{
		alert("As senhas não conferem!");
		$('confirmacao').value = "";
		$('confirmacao').focus();
		return false;
	}
	
	if ($('mail').value == "")
	{
		alert("Por favor preencha o Email!");
		$('mail').focus();
		return false;
	}
	
	if ($('confirmacaoMail').value == "")
	{
		alert("Por favor confirme o Email!");
		$('confirmacaoMail').focus();
		return false;
	}
	
	if ($('mail').value != $('confirmacaoMail').value)
	{
		alert("Os emails não conferem!");
		$('confirmacaoMail').value = "";
		$('confirmacaoMail').focus();
		return false;
	}
	
	if (($('mail').value.indexOf('@zipmail') != -1) || ($('mail').value.indexOf('@bol') != -1) || ($('mail').value.indexOf('@uol') != -1))
	{
		var resposta = confirm('Atenção! Usuários do BOL, UOL e ZIPMAIL estão tendo problemas em receber a confirmação de cadastro. Clique Ok para continuar ou Cancelar para alterar o e-mail!');
		if (resposta == true)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	return true;
}

function validaLoginUsuario()
{
	if ($('usr_login').value == "")
	{
		alert("Por favor preencha o Login!");
		$('usr_login').focus();
		return false;
	}
	
	if ($('usr_senha').value == "")
	{
		alert("Por favor preencha a Senha!");
		$('usr_senha').focus();
		return false;
	}
	
	return true;
}

function validaFormConfirma()
{
	if ($('login').value == "")
	{
		alert("Por favor preencha o Login!");
		$('login').focus();
		return false;
	}
	
	if ($('login').value.length < 6)
	{
		alert("O Login deve ter entre 6 e 15 caracteres");
		$('login').value = "";
		$('login').focus();
		return false;
	}
	
	if ($('login').value.length > 15)
	{
		alert("O Login deve ter entre 6 e 15 caracteres");
		$('login').value = "";
		$('login').focus();
		return false;
	}
	
	// Verifica o sexo
	if ($('usr_sexo').selectedIndex == 0)
	{
		alert("O seu Sexo deve ser informado!");
		$('usr_sexo').focus();
		return false;
	}
	
	// Verifica a data de nascimento
	if ($('dat_nascimento').value == "")
	{
		alert("A data de nascimento deve ser informada!");
		$('dat_nascimento').focus();
		return false;
	}
	
	if (!isDate($('dat_nascimento').value))
	{
		alert("Digite uma data válida!");
		$('dat_nascimento').value = "";
		$('dat_nascimento').focus();
		return false;
	}
	
	// Verifica a data de nascimento B
	if (($('dat_nascimento_b').value == "") && (($('usr_sexo').value == 'C') || ($('usr_sexo').value == 'CM') || ($('usr_sexo').value == 'CF')))
	{
		alert("A segunda data de nascimento deve ser informada!");
		$('dat_nascimento_b').focus();
		return false;
	}
	
	if ($('dat_nascimento_b').value != "")
	{
		if ((!isDate($('dat_nascimento_b').value)) && (($('usr_sexo').value == 'C') || ($('usr_sexo').value == 'CM') || ($('usr_sexo').value == 'CF')))
		{
			alert("Digite uma data válida!");
			$('dat_nascimento_b').value = "";
			$('dat_nascimento_b').focus();
			return false;
		}
	}
	
	// Verifica o estado
	if ($('usr_estado').selectedIndex == 0)
	{
		alert("O Estado deve ser informado!");
		$('usr_estado').focus();
		return false;
	}
	
	// Verifica a cidade
	if ($('cidade').selectedIndex == 0)
	{
		alert("A cidade deve ser informada!");
		$('cidade').focus();
		return false;
	}
	
	return true;
}

function verificaSexo()
{
	if($('usr_sexo').selectedIndex == 0)
	{
		$('certoSexo').style.display = 'none';
		$('nascimento_b').style.display = 'none';
	}
	else
	{
		// A escolha de sexo esta correta
		$('certoSexo').style.display = '';
		if (($('usr_sexo').value == 'C') || ($('usr_sexo').value == 'CM') || ($('usr_sexo').value == 'CF'))
		{
			// Ativa a segunda data de nascimento
			$('nascimento_b').style.display = '';
		}
		else
		{
			$('nascimento_b').style.display = 'none';
		}
	}
	return;
}

function verificaCidade()
{
	if($('cidade').selectedIndex == 0)
	{
		$('certoCidade').style.display = 'none';
	}
	else
	{
		$('certoCidade').style.display = '';
	}
	return;
}

function validaFormContato()
{
	// Verifica se o assunto foi preenchido
	if ($('mailContato').value == "")
	{
		alert("O e-mail deve ser preenchido!");
		$('mailContato').focus();
		return false;
	}
	
	// Verifica se a mensagem foi preenchida
	if ($('assuntoContato').value == "")
	{
		alert("O assunto deve ser preenchida!");
		$('assuntoContato').focus();
		return false;
	}
	
	// Verifica se a mensagem foi preenchida
	if ($('mensagemContato').value == "")
	{
		alert("A mensagem deve ser preenchida!");
		$('mensagemContato').focus();
		return false;
	}
	
	var marcado = false;
	for (i=0;i<document.formContato.captcha.length;i++)
	{
		if (document.formContato.captcha[i].checked==true)
		marcado = true;
	}
	if (!marcado)
	{
		alert("Por favor marque a resposta correta");
		return false;
	}
	
	return false;
}

var dtCh= "/";
var minYear=1900;
var maxYear=2100;

// Declarando variaveis globais

function isInteger(s){
	var i;
	for (i = 0; i < s.length; i++){
		// Check that current character is number.
		var c = s.charAt(i);
		if (((c < "0") || (c > "9"))) return false;
	}
	// All characters are numbers.
	return true;
}

function stripCharsInBag(s, bag){
	var i;
	var returnString = "";
	// Search through string's characters one by one.
	// If character is not in bag, append to returnString.
	for (i = 0; i < s.length; i++){
		var c = s.charAt(i);
		if (bag.indexOf(c) == -1) returnString += c;
	}
	return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
	// EXCEPT for centurial years which are not also divisible by 400.
	return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
}
return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	// Posicao da primeira barra
	var pos1=dtStr.indexOf(dtCh)
	// Posicao da segunda barra
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("O formato da data deve ser: dd/mm/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Por favor entre um mês válido")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Por favor entre um dia válido")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Por favor digite o ano com 4 dígitos, com valor entre "+minYear+" e "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Por favor entre uma data válida")
		return false
	}
	return true
}