/*
 * Localized default methods for the jQuery validation plugin.
 * Locale: PT_BR
 */
jQuery.extend(jQuery.validator.methods, {
    date: function(value, element) {
        return this.optional(element) || checkDate(value);
    }
});

/*
 * Translated default messages for the jQuery validation plugin.
 * Locale: PT_BR
 */
jQuery.extend(jQuery.validator.messages, {
    required: "Este campo &eacute; requerido.",
    remote: "Por favor, corrija este campo.",
    email: "Por favor, forne&ccedil;a um endere&ccedil;o eletr&ocirc;nico v&aacute;lido.",
    url: "Por favor, forne&ccedil;a uma URL v&aacute;lida.",
    date: "Por favor, forne&ccedil;a uma data v&aacute;lida.",
    dateISO: "Por favor, forne&ccedil;a uma data v&aacute;lida (ISO).",
    number: "Por favor, forne&ccedil;a um n&uacute;mero v&aacute;lida.",
    digits: "Por favor, forne&ccedil;a somente d&iacute;gitos.",
    creditcard: "Por favor, forne&ccedil;a um cart&atilde;o de cr&eacute;dito v&aacute;lido.",
    equalTo: "Por favor, forne&ccedil;a o mesmo valor novamente.",
    accept: "Por favor, forne&ccedil;a um valor com uma extens&atilde;o v&aacute;lida.",
    maxlength: jQuery.validator.format("Por favor, forne&ccedil;a n&atilde;o mais que {0} caracteres."),
    minlength: jQuery.validator.format("Por favor, forne&ccedil;a ao menos {0} caracteres."),
    rangelength: jQuery.validator.format("Por favor, forne&ccedil;a um valor entre {0} e {1} caracteres de comprimento."),
    range: jQuery.validator.format("Por favor, forne&ccedil;a um valor entre {0} e {1}."),
    max: jQuery.validator.format("Por favor, forne&ccedil;a um valor menor ou igual a {0}."),
    min: jQuery.validator.format("Por favor, forne&ccedil;a um valor maior ou igual a {0}.")
});

function checkDate(date)
{
    if(date == undefined){
        return false;
    }

    if(date == '__/__/____' || date == ''){
        return true;
    }

    var expReg = /^((0[1-9]|[12]\d)\/(0[1-9]|1[0-2])|30\/(0[13-9]|1[0-2])|31\/(0[13578]|1[02]))\/(19|20)?\d{2}$/;

    if (date.match(expReg) && date != '') {

        var dia = parseInt(date.substring(0,2),10);
        var mes = parseInt(date.substring(3,5),10);
        var ano = parseInt(date.substring(6,10),10);

        if ( (mes == 4 || mes == 6 || mes == 9 || mes == 11) && dia > 30){
            return false;
        }
        else if ((ano % 4) != 0 && mes == 2 && dia > 28){
            return false;
        }else{
            if ((ano%4) == 0 && mes == 2 && dia > 29){
                return false;
            }
        }
    } else{
        return false;
    }
    return  true;
}

var countAviso = 1;

$(function(){    
    $('.date').mask('99/99/9999');
    $('.phone').mask('(99)9999-9999');
    $('.cep').mask('99.999-999')
    $('.cpf').mask('999.999.999-99')
    
    //abre os videos em uma modal
    $(".fancyboxIframe").fancybox({
        'width'				: '55%',
        'height'			: '65%',
        'autoScale'			: false,
        'transitionIn'                  : 'none',
        'transitionOut'                 : 'none',
        'type'				: 'iframe'
    });
    
    //convÃªnios rotativos
    window.setInterval(function(){
        $.getJSON(ROOT_PATH + 'ajax/json-convenios.php', function(data){
            var html = '';
            for (var v in data) {
                if(data[v].tx_link){
                    html += '<a href="' + data[v].tx_link + '" target="_blank">';
                }
                html += '<img src="' + ROOT_PATH + 'base/m2brimagem/redimencionar.php?arquivo=' + data[v].tx_banner + '&altura=67&largura=240"'
                + ' alt="' + data[v].tx_convenio + '" title="' + data[v].tx_convenio + '" />'
                if(data[v].tx_link){
                    html += '</a>';
                }
                html += '<br/><br/>';
            }
            $('#divConveniosRand').html(html);
        });
    }, 1000 * 10);


    /* avisos rotativos */
    window.setInterval(function(){
        
        if(countAviso >= totalAvisos) countAviso = 0;

        $('.news_updates').hide();
        $('.avisos_' + countAviso).show();
        countAviso++;

    }, 1000 * 5);
    
    
    //validaÃ§Ã£o do formulario de newslatters
    
    $('#formNewsletter').validate({
        submitHandler: function(form) {
            $.post($(form).attr('action'), $(form).serialize(), function(r){
                showMessage(r.msg);
                if(r.type == 'success'){
                    $(form).clearForm();
                }
            }, 'json');
        }
    });
    
    //validaÃ§Ã£o do formulario de fale conosco
    $('#formFale').validate({
        submitHandler: function(form) {
            $.post($(form).attr('action'), $(form).serialize(), function(r){
                showMessage(r.msg);
                if(r.type == 'success'){
                    $(form).clearForm();
                }
            }, 'json');
        }
    });
    
    
    //combo de categorias
    $('#formCentralDownload #id_categoria').change(function(){
        if($(this).val()){
            $('#formCentralDownload').submit();
        }
    });
    
    //combo de galeria de imagens
    $('#formGaleriaImagens #id_album').change(function(){
        if($(this).val()){
            $('#formGaleriaImagens').submit();
        }
    })
    
    //combo de galeria de videos
    $('#formGaleriaVideos #id_acervo').change(function(){
        if($(this).val()){
            $('#formGaleriaVideos').submit();
        }
    });
    
    /* Tela de Ficha de AtualizaÃ§Ã£o */
    
    
    $('.btJqueryUI').button();
    
    $('#tabs2').tabs();
    
    var tabs = $("#tabs").tabs();


    if($('#formFicha #socio-st_civil').val() == 'C'){
        $('.divsConjuge').show();
        $('.divsConjuge input').addClass('required');
    }
    
    $('#formFicha #socio-st_civil').change(function(){
        if($(this).val() == 'C'){
            $('.divsConjuge').show();
            $('.divsConjuge input').addClass('required');
        }else{
            $('.divsConjuge').hide();
            $('.divsConjuge input').removeClass('required');
        }
    });
	
	var validator = $('#formFicha').validate({
		focusInvalid: true,
        submitHandler: function(form) {
            $.post($(form).attr('action'), $(form).serialize(), function(r){
                showMessage(r.msg);
                if(r.type == 'success'){
                    $(form).clearForm();
                    /** posiciona na primeira aba */
                    $('#a-tabs-1').click();
                }
            }, 'json');
        }
    });    
    
//
});

function formFichaSubmit(){	   
   if(!$('#formFicha').valid()){	   
		/** captura a primeira aba que estÃ¡ com campos invalidos */
		primeira_aba = '';
		$('#tabs .error').each(function(){
			if(primeira_aba == ''){
				if($.trim($(this).css('display')) != 'none'){
					primeira_aba = $(this).parent().parent().attr('id');
				}
			}
		});   
		
		/** ativa a primeira aba que estÃ¡ com campos invalidos */
		if(primeira_aba != ''){
			$('#a-' + primeira_aba).click();
		}
		
   }else{
	   validou = true;
	   /** verifica se o CPF é válido */
	   $('.cpf').each(function(){
		   if(!isCPF($(this).val())){
			   $(this).after("<label class='error' for='socio[tx_cpf_mf]' generated='true'>CPF informado incorreto.</label>");
			   $('#a-tabs-3').click();
			   validou = false;
			   return false;
		   }
	   })
	   
	   if(validou){
		   $('#formFicha').submit();
	   }
   }
}

function showMessage(message){
    alert(message);
}


$.fn.clearForm = function() {
    return this.each(function() {
        var type = this.type, tag = this.tagName.toLowerCase();
        if (tag == 'form')
            return $(':input',this).clearForm();
        if (type == 'text' || type == 'password' || tag == 'textarea')
            this.value = '';
        else if (type == 'checkbox' || type == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
};

var divDependente = {
    adicionar: function(bt){
        //add o html do formulario
        $(bt).parent().parent().after(divDependente.html());
        //deixa os botoes com o estilo jquery
        $('.btJqueryUI').button();
        //esconde o botÃ£o adicionar
        $(bt).hide();
        //exibe o botÃ£o remover
        $(bt).next('.btRemover').show();
        $('.date').unmask().mask('99/99/9999');
    },
    remover: function(bt){
        //remove a div do formulario
        $(bt).parent().parent().remove();
        //exibe apenas o ultimo botÃ£o adicionar
        $('.btAdicionar').hide();
        $('.btAdicionar:last').show();
        //nunca exibe o primeiro botÃ£o remover
        $('.btRemover').show();
        $('.btRemover:last').hide();
        //atualiza as mascaras
        $('.date').unmask().mask('99/99/9999')
    },
    html: function(){
        //gera um numero randomico de 0 a 100
        var i = parseInt(Math.random() * 101, 10);
        //gera o html
        var html = '<div class="divDependente" style="margin-top: 10px;">'
        + '<div>'
        + '<label>Nome:</label>'
        + '<input name="dependente[' + i + '][tx_dependente]" maxlength="255" class="required"/>'
        + '</div>'
        + '<div>'
        + '<label>Dt. Nascimento:</label>'
        + '<input name="dependente[' + i + '][dt_nascimento]" class="required date"/>'
        + '</div>'
        + '<div>'
        
        + '<label>Parentesco:</label>'
        + '<select name="dependente[' + i + '][tx_parentesco]" class="required">'
        + '<option value=""></option>'
        + '<option value="Pai">Pai</option>'
        + '<option value="M&atilde;e">M&atilde;e</option>'
        + '<option value="Sogro">Sogro</option>'
        + '<option value="Sogra">Sogra</option>'
        + '<option value="Filho">Filho</option>'
        + '<option value="Filha">Filha</option>'
        + '<option value="C&ocirc;njuge">C&ocirc;njuge</option>'
        + '<option value="Outro">Outro</option>'
        + '</select>'
        
        + '</div>'
        + '<div>'
        + '<label>UniversitÃ¡rio:</label>'
        + '<label for="dependente-' + i + '-tp_universitario-S" style="width: 100px;">'
        + 'Sim <input type="radio" value="S" name="dependente[' + i + '][tp_universitario]" id="dependente-' + i + '-tp_universitario-S" class="required">'
        + '</label>'
        + '<label for="dependente-' + i + '-tp_universitario-N" style="width: 100px;">'
        + 'NÃ£o <input type="radio" checked="checked" value="N" name="dependente[' + i + '][tp_universitario]" id="dependente-' + i + '-tp_universitario-N" class="required">'
        + '</label>'
        + '</div>'
        + '<div>'
        + '<button class="btJqueryUI btAdicionar" type="button" onclick="divDependente.adicionar(this)">Adicionar outro dependente</button>'
        + '<button class="btJqueryUI btRemover" type="button" onclick="divDependente.remover(this)">Remover esse dependente</button>'
        + '</div>'
        + '</div>';
                
        return html;
    }
}


function utf8_encode (argString) {
    if (argString === null || typeof argString === "undefined") {
        return "";
    }
     var string = (argString + ''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");
    var utftext = "",
        start, end, stringl = 0;
 
    start = end = 0;    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;
         if (c1 < 128) {
            end++;
        } else if (c1 > 127 && c1 < 2048) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc !== null) {
            if (end > start) {
                utftext += string.slice(start, end);            }
            utftext += enc;
            start = end = n + 1;
        }
    } 
    if (end > start) {
        utftext += string.slice(start, stringl);
    }
     return utftext;
}


function isCPF(cpf){
	
	   var filtro = /^\d{3}.\d{3}.\d{3}-\d{2}$/i;
	   if(!filtro.test(cpf)){        	     
		 return false;
	   }
	   
	   cpf = str_replace('.','', cpf);
	   cpf = str_replace('-','', cpf);
	    
	   if(cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" ||
		  cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" ||
		  cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" ||
		  cpf == "88888888888" || cpf == "99999999999"){
		  return false;
	   }

	   soma = 0;
	   for(i = 0; i < 9; i++)
	   	 soma += parseInt(cpf.charAt(i)) * (10 - i);
	   resto = 11 - (soma % 11);
	   if(resto == 10 || resto == 11)
		 resto = 0;
	   if(resto != parseInt(cpf.charAt(9))){
		 return false;
	   }
	   soma = 0;
	   for(i = 0; i < 10; i ++)
		 soma += parseInt(cpf.charAt(i)) * (11 - i);
	   resto = 11 - (soma % 11);
	   if(resto == 10 || resto == 11)
		 resto = 0;
	   if(resto != parseInt(cpf.charAt(10))){
		 return false;
	   }
	   return true;
}


function str_replace (search, replace, subject, count) {
    var i = 0,
        j = 0,
        temp = '',
        repl = '',
        sl = 0,        fl = 0,
        f = [].concat(search),
        r = [].concat(replace),
        s = subject,
        ra = Object.prototype.toString.call(r) === '[object Array]',        sa = Object.prototype.toString.call(s) === '[object Array]';
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    } 
    for (i = 0, sl = s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }        for (j = 0, fl = f.length; j < fl; j++) {
            temp = s[i] + '';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {                this.window[count] += (temp.length - s[i].length) / f[j].length;
            }
        }
    }
    return sa ? s : s[0];
}
