﻿// JavaScript Document

$(document).ready(function() {
	//Scroll Personalizado
	$('#content .scrollarea').jScrollPane({
	   scrollbarWidth:9,
	   scrollbarMargin:10,
	   showArrows:true,
	   animateTo:true,
	   wheelSpeed:20
	});
	$('input.pessoa').click(function(){
		if($('input.pessoa:checked').val() == "fisica"){
			$('#dados-juridica').hide();
			$('#dados-fisica').show();
		}else{
			$('#dados-fisica').hide();
			$('#dados-juridica').show();
		}
	});
	addListenerInTollTips();
});



var errorform = null;
function updateScroll(){
	
	setTimeout(function(){
		errorform = 'Os campos seguintes não foram preenchidos corretamente:\n\n';
		$('ul li','#win7Cadastro_vlsCadastro').each(function(x){
			if($(this).html()){
				errorform += '\t'+$(this).html()+'\n';
			}
		});
		if(errorform && errorform != 'Os campos seguintes não foram preenchidos corretamente:\n\n')
			alert(errorform);
	},100);	
		
	//$('#win7Cadastro_vlsCadastro').prependTo($('#content'));
	//$('#win7Cadastro_vlsCadastro').fadeOut();
	/*$('body').css('font-size','11.14564516584654646px');
	$('body').css('font-size','11.143653425px');
	setTimeout(function(){
		$('body').css('font-size','11px');
	},100);
	setTimeout(function(){
		$('body').css('font-size','11px');
	},200);*/
}

function addListenerInTollTips(){
	$('#autentico').prependTo($('body'),'top');

	$('a[href$=autentico]').click(function(e){

		ttop  = ( (e.clientY + $(window).scrollTop()) - $('#autentico').height() );
		lleft = (e.clientX-34);
		
		if((lleft+$('#autentico').width()) >= $(document.body).width()){
			lleft = ($(document.body).width() - $('#autentico').width()) - 10;
		}
		
		$('#autentico').css('top',ttop+'px');
		$('#autentico').css('left',lleft+'px');
		
		
		$('#autentico').css('display','block');
		$('.close','#autentico').click(function(){
			$('#autentico').css('display','none');
		});
		return false;
	}).hover(
		function(e){
			ttop  = ( (e.clientY + $(window).scrollTop()) - $('#autentico').height() );
			lleft = (e.clientX-34);
			
			if((lleft+$('#autentico').width()) >= $(document.body).width()){
				lleft = ($(document.body).width() - $('#autentico').width()) - 10;
			}
			
			$('#autentico').css('top',ttop+'px');
			$('#autentico').css('left',lleft+'px');
			
			
			$('#autentico').css('display','block');
			
			$('#autentico').click(
				function(){
					$('#autentico').css('display','none');
				}
			).hover(
				function(){
					//clearTimeout(document.tooltipAutentico);
				},
				function(){
					$('#autentico').css('display','none');
				}
			);
			return false;
		},
		function(){
			//document.tooltipAutentico = setTimeout(function(){
			//	$('#autentico').css('display','none');
			//},6000);
		}
	);
}

/**
* @author Márcio d'Ávila
* @version 1.03, 2004-2008
*
* Este script foi retirado de:
* http://www.mhavila.com.br/topicos/web/cpf_cnpj.html
*
* Licenciado sob os termos da licença Creative Commons,
* Atribuição - Compartilhamento pela mesma licença 2.5:
* http://creativecommons.org/licenses/by-sa/2.5/br/
* Qualquer outra forma de uso requer autorização expressa do autor.
*
* PROTÓTIPOS:
* método String.lpad(int pSize, char pCharPad)
* método String.trim()
*
* String unformatNumber(String pNum)
* String formatCpfCnpj(String pCpfCnpj, boolean pUseSepar, boolean pIsCnpj)
* String dvCpfCnpj(String pEfetivo, boolean pIsCnpj)
* boolean isCpf(String pCpf)
* boolean isCnpj(String pCnpj)
* boolean isCpfCnpj(String pCpfCnpj)
*/


NUM_DIGITOS_CPF = 11;
NUM_DIGITOS_CNPJ = 14;
NUM_DGT_CNPJ_BASE = 8;


/**
* Adiciona método lpad() à classe String.
* Preenche a String à esquerda com o caractere fornecido,
* até que ela atinja o tamanho especificado.
*/
String.prototype.lpad = function(pSize, pCharPad) {
    var str = this;
    var dif = pSize - str.length;
    var ch = String(pCharPad).charAt(0);
    for (; dif > 0; dif--) str = ch + str;
    return (str);
} //String.lpad


/**
* Adiciona método trim() à classe String.
* Elimina brancos no início e fim da String.
*/
String.prototype.trim = function() {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
} //String.trim


/**
* Elimina caracteres de formatação e zeros à esquerda da string
* de número fornecida.
* @param String pNum
* 	String de número fornecida para ser desformatada.
* @return String de número desformatada.
*/
function unformatNumber(pNum) {
    return String(pNum).replace(/\D/g, "").replace(/^0+/, "");
} //unformatNumber


/**
* Formata a string fornecida como CNPJ ou CPF, adicionando zeros
* à esquerda se necessário e caracteres separadores, conforme solicitado.
* @param String pCpfCnpj
* 	String fornecida para ser formatada.
* @param boolean pUseSepar
* 	Indica se devem ser usados caracteres separadores (. - /).
* @param boolean pIsCnpj
* 	Indica se a string fornecida é um CNPJ.
* 	Caso contrário, é CPF. Default = false (CPF).
* @return String de CPF ou CNPJ devidamente formatada.
*/
function formatCpfCnpj(pCpfCnpj, pUseSepar, pIsCnpj) {
    if (pIsCnpj == null) pIsCnpj = false;
    if (pUseSepar == null) pUseSepar = true;
    var maxDigitos = pIsCnpj ? NUM_DIGITOS_CNPJ : NUM_DIGITOS_CPF;
    var numero = unformatNumber(pCpfCnpj);

    numero = numero.lpad(maxDigitos, '0');

    if (!pUseSepar) return numero;

    if (pIsCnpj) {
        reCnpj = /(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/;
        numero = numero.replace(reCnpj, "$1.$2.$3/$4-$5");
    }
    else {
        reCpf = /(\d{3})(\d{3})(\d{3})(\d{2})$/;
        numero = numero.replace(reCpf, "$1.$2.$3-$4");
    }
    return numero;
} //formatCpfCnpj


/**
* Calcula os 2 dígitos verificadores para o número-efetivo pEfetivo de
* CNPJ (12 dígitos) ou CPF (9 dígitos) fornecido. pIsCnpj é booleano e
* informa se o número-efetivo fornecido é CNPJ (default = false).
* @param String pEfetivo
* 	String do número-efetivo (SEM dígitos verificadores) de CNPJ ou CPF.
* @param boolean pIsCnpj
* 	Indica se a string fornecida é de um CNPJ.
* 	Caso contrário, é CPF. Default = false (CPF).
* @return String com os dois dígitos verificadores.
*/
function dvCpfCnpj(pEfetivo, pIsCnpj) {
    if (pIsCnpj == null) pIsCnpj = false;
    var i, j, k, soma, dv;
    var cicloPeso = pIsCnpj ? NUM_DGT_CNPJ_BASE : NUM_DIGITOS_CPF;
    var maxDigitos = pIsCnpj ? NUM_DIGITOS_CNPJ : NUM_DIGITOS_CPF;
    var calculado = formatCpfCnpj(pEfetivo + "00", false, pIsCnpj);
    calculado = calculado.substring(0, maxDigitos - 2);
    var result = "";

    for (j = 1; j <= 2; j++) {
        k = 2;
        soma = 0;
        for (i = calculado.length - 1; i >= 0; i--) {
            soma += (calculado.charAt(i) - '0') * k;
            k = (k - 1) % cicloPeso + 2;
        }
        dv = 11 - soma % 11;
        if (dv > 9) dv = 0;
        calculado += dv;
        result += dv
    }

    return result;
} //dvCpfCnpj


/**
* Testa se a String pCpf fornecida é um CPF válido.
* Qualquer formatação que não seja algarismos é desconsiderada.
* @param String pCpf
* 	String fornecida para ser testada.
* @return <code>true</code> se a String fornecida for um CPF válido.
*/
function isCpf(pCpf) {
    var numero = formatCpfCnpj(pCpf, false, false);
    if (numero.length > NUM_DIGITOS_CPF) return false;

    var base = numero.substring(0, numero.length - 2);
    var digitos = dvCpfCnpj(base, false);
    var algUnico, i;

    // Valida dígitos verificadores
    if (numero != "" + base + digitos) return false;

    /* Não serão considerados válidos os seguintes CPF:
    * 000.000.000-00, 111.111.111-11, 222.222.222-22, 333.333.333-33, 444.444.444-44,
    * 555.555.555-55, 666.666.666-66, 777.777.777-77, 888.888.888-88, 999.999.999-99.
    */
    algUnico = true;
    for (i = 1; algUnico && i < NUM_DIGITOS_CPF; i++) {
        algUnico = (numero.charAt(i - 1) == numero.charAt(i));
    }
    return (!algUnico);
} //isCpf


/**
* Testa se a String pCnpj fornecida é um CNPJ válido.
* Qualquer formatação que não seja algarismos é desconsiderada.
* @param String pCnpj
* 	String fornecida para ser testada.
* @return <code>true</code> se a String fornecida for um CNPJ válido.
*/
function isCnpj(pCnpj) {
    var numero = formatCpfCnpj(pCnpj, false, true);
    if (numero.length > NUM_DIGITOS_CNPJ) return false;

    var base = numero.substring(0, NUM_DGT_CNPJ_BASE);
    var ordem = numero.substring(NUM_DGT_CNPJ_BASE, 12);
    var digitos = dvCpfCnpj(base + ordem, true);
    var algUnico;

    // Valida dígitos verificadores
    if (numero != "" + base + ordem + digitos) return false;

    /* Não serão considerados válidos os CNPJ com os seguintes números BÁSICOS:
    * 11.111.111, 22.222.222, 33.333.333, 44.444.444, 55.555.555,
    * 66.666.666, 77.777.777, 88.888.888, 99.999.999.
    */
    algUnico = numero.charAt(0) != '0';
    for (i = 1; algUnico && i < NUM_DGT_CNPJ_BASE; i++) {
        algUnico = (numero.charAt(i - 1) == numero.charAt(i));
    }
    if (algUnico) return false;

    /* Não será considerado válido CNPJ com número de ORDEM igual a 0000.
    * Não será considerado válido CNPJ com número de ORDEM maior do que 0300
    * e com as três primeiras posições do número BÁSICO com 000 (zeros).
    * Esta crítica não será feita quando o no BÁSICO do CNPJ for igual a 00.000.000.
    */
    if (ordem == "0000") return false;
    return (base == "00000000"
		|| parseInt(ordem, 10) <= 300 || base.substring(0, 3) != "000");
} //isCnpj


/**
* Testa se a String pCpfCnpj fornecida é um CPF ou CNPJ válido.
* Se a String tiver uma quantidade de dígitos igual ou inferior
* a 11, valida como CPF. Se for maior que 11, valida como CNPJ.
* Qualquer formatação que não seja algarismos é desconsiderada.
* @param String pCpfCnpj
* 	String fornecida para ser testada.
* @return <code>true</code> se a String fornecida for um CPF ou CNPJ válido.
*/
function isCpfCnpj(sender, args) {
    var numero = args.Value.replace(/\D/g, "");
    if (numero.length > NUM_DIGITOS_CPF)
        args.IsValid = isCnpj(args.Value)
    else
        args.IsValid = isCpf(args.Value);
} //isCpfCnpj

function validarCpf(sender, args) {
    args.IsValid = isCpf(args.Value);
}

function validarCnpj(sender, args) {
    args.IsValid = isCnpj(args.Value)
}

/** Funções Gerais **/
//exemplo de uso do noLetters: onKeyDown="return noLetters(event);"
function noLetters(e)
{
	var tecla;
	if(!e)
		e = window.event;
	
	// verificação cross-browser
	if(e.which)
		tecla = e.which;
	else if(e.keyCode)
		tecla = e.keyCode;

	if( (tecla >= 48 && tecla <= 57) || (tecla >= 96 && tecla <= 105) || tecla == 8 || tecla == 37 || tecla == 39 || tecla == 46 || tecla == 9 )
	{
		/*9: tab; 8 = backspace; 37 = seta pra esquerda; 39 = seta pra direita; 46 = delete*/
		return true;
	}
	else
	{
		return false;
	}
}

//exemplo de uso do noNumbers: onKeyDown="return noNumbers(event);"
function noNumbers(e)
{
	var tecla;
	if(!e)
		e = window.event;
	
	// verificação cross-browser
	if(e.which)
		tecla = e.which;
	else if(e.keyCode)
		tecla = e.keyCode;

	if( (tecla >= 48 && tecla <= 57) || (tecla >= 96 && tecla <= 105) )
	{
		/*9: tab; 8 = backspace; 37 = seta pra esquerda; 39 = seta pra direita; 46 = delete*/
		return false;
	}
	else
	{
		return true;
	}
}

//formata uma data corretamente
function formataData( obj )
{
	if( parseInt(obj.value.length) == 2 )
		obj.value += "/";
	if( parseInt(obj.value.length) == 5 )
		obj.value += "/";
}

//formata CPF
function formataCPF( obj )
{		
	if( obj.value.charAt(3) != "." && obj.value.charAt(3) != "" )
		obj.value = obj.value.substring(0,3) + "." + obj.value.substring(3);
	if( obj.value.charAt(7) != "." && obj.value.charAt(7) != "" )
	    obj.value = obj.value.substring(0,7) + "." + obj.value.substring(7);   
	if( obj.value.charAt(11) != "-" && obj.value.charAt(11) != "" )
	    obj.value = obj.value.substring(0,11) + "-" + obj.value.substring(11);
}

//formata CNPJ
function formataCNPJ( obj )
{

	if( obj.value.charAt(2) != "." && obj.value.charAt(2) != "" )
		obj.value = obj.value.substring(0,2) + "." + obj.value.substring(2);
	if( obj.value.charAt(6) != "." && obj.value.charAt(6) != "" )
	    obj.value = obj.value.substring(0,6) + "." + obj.value.substring(6);   
	if( obj.value.charAt(10) != "/" && obj.value.charAt(10) != "" )
	    obj.value = obj.value.substring(0,10) + "/" + obj.value.substring(10);
	if( obj.value.charAt(15) != "-" && obj.value.charAt(15) != "" )
	    obj.value = obj.value.substring(0,15) + "-" + obj.value.substring(15);
}

/****/
// Formatações de campos
$(document).ready(function() {
    $('#win7Cadastro_txtTelefonePrimario').mask('(999) 9999-9999');
    $('#win7Cadastro_txtTelefoneSecundario').mask('(999) 9999-9999');
    $('#win7Cadastro_txtCEP').mask('99999-999');
});



//consiste uma data passada
function consisteData( txtData )
{
		var arrData = txtData.split("/");
		// se não vierem 3 células, ou a primeira e a segunda célula não tiverem 2 caracteres ou a última não tiver 4, já dá erro
		if( arrData[0].length != 2 || arrData[1].length != 2 || arrData[2].length != 4 )
		{
			alert('Formato de data inválido.');
			return false;
		}	
		else
		{
			//verificando se não digitou tudo zero
			if( arrData[0] == "00" || arrData[1] == "00" || arrData[2] == "0000" )
			{
				alert("Formato de data inválido.");
				return false;				
			}

			if( arrData[0] < 10 )//tirando o zero que o cara digitou
				arrData[0] = arrData[0].substr(1,1);
			if( arrData[1] < 10 )//tirando o zero que o cara digitou
				arrData[1] = arrData[1].substr(1,1);

			//verificando se não digitou um mês maior que 12 ou menor que 1
			if( parseInt(arrData[1]) < 1 || parseInt(arrData[1]) > 12 )
			{
				alert("O mês digitado deve ir de 01 até 12 apenas.");
				return false;
			} 
			//verificando mês de fevereiro
			if( ( (parseInt(arrData[2]) - 1900) % 4 ) == 0 ) //ano bissexto
				finalDiaFev = 29;
			else
				finalDiaFev = 28;
			
			if( arrData[1] == "02" && parseInt(arrData[0]) > finalDiaFev )
			{
				alert("Este mês de fevereiro possui " + finalDiaFev + " dias.");
				return false;
			}
			else
			{
				if( arrData[1] % 2 == 0 )
				    if( parseInt(arrData[1],10) > 7 )
					    finalDia = 31;
				    else
				        finalDia = 30;
				else
				    if( parseInt(arrData[1],10) > 7 )
					    finalDia = 30;
					else
					    finalDia = 31;
					
				if( arrData[0] > finalDia )
				{
					alert("Este mês não pode ter mais que " + finalDia + " dias.");
					return false; 
				}
				
			} 
		}
		return true;
}

// Verifica se a data de compra do produto é válida e se está no range determinado. 
function consisteDataCompraProduto( objTxtDia, objTxtMes, objTxtAno )
{
    if( objTxtDia.value.length == 2 && objTxtMes.value.length == 2 & objTxtAno.value.length == 4 )
    {
        if( consisteData(objTxtDia.value + "/" + objTxtMes.value + "/" + objTxtAno.value) )
        {
            var dataCompraProduto = new Date(objTxtMes.value + '/' + objTxtDia.value + "/" + objTxtAno.value + ' 00:00:00');
            var dataUpgradeInicio = new Date('06/26/2009 00:00:00');
            var dataUpgradeFim = new Date('01/31/2010 00:00:00');
            
            if((dataCompraProduto.getTime() < dataUpgradeInicio.getTime()) || (dataCompraProduto.getTime() > dataUpgradeFim.getTime()))
                alert('Infelizmente seu computador não está apto ao upgrade para o Windows 7. Obrigada!');
            
            return;
        }
    }
}