$(document).ready(function() {
    boxResize();
    animaMenu();
});

$(window).resize(function(){
    boxResize();
});

/*
$(window).scroll(function () {
    var scrollTop = $(document).scrollTop();
    $(".section_nave").animate({
        marginTop: scrollTop+"px"
    },{
        duration:1000,
        queue:false
    }
    );
});
*/

function animaMenu() {
    $('.section_nave > ul > li > a').click(function(){
        var href = $(this).attr('href');
	
        href = href.split("#");
        href = href.reverse();
        
        var local = $("#"+href[0]).offset().top;
        
        $('html, body').animate({
            scrollTop: local
        }, 2000);
        
        return false;
    });
}


function boxResize() {
    var altura = $(window).height();
    
    //$('#container').css('min-height', altura * 8);
    $('.content').css('min-height', altura);
    //$('#nav').css('min-height', altura * 8);
    /*
    var alturaContainer = $('#container').height();
    $('#nav').css('min-height', alturaContainer);
    */
}

function mudaGaleria(id) {
    $('.section_fotos_left').html('');
    $('.section_fotos_left').load('load-galeriaFotos.php?id='+id);
}

function getHashTag() {
    var url = window.location.href;
		
    if(url.search("#") == -1)
        return false;
			
    url = url.split("#");
    url = url.reverse();
    return url[0];
}

//------------------------//------------------------------------//----------------

/*
 * Função para para por determinado tempo
 * @param milliseconds milisegundos
 */
function sleep(milliseconds) {
    var start = new Date().getTime();
    for (var i = 0; i < 1e7; i++) {
        if ((new Date().getTime() - start) > milliseconds){
            break;
        }
    }
}

//-----------------------------------------------------------------------------//
// VALIDA E-MAIL
//-----------------------------------------------------------------------------//

function validaEmail(email)
{
    if(email == "")
    {
        alert('Você precisa digitar um endereço de e-mail! ');
        return false;
    }

    if(email.search(/^\w+((-\w+)|(\.\w+))*\@\w+((\.|-)\w+)*\.\w+$/) == -1)
    {
        alert('Você precisa digitar um endereço de e-mail valido! ');
        return false;
    }

    return true;
}

function formataMoeda(campo,evt) {
   
    //para evitar caracteres alfas.
    if(((evt.keyCode < 96) || (evt.keyCode > 105)) && ((evt.keyCode < 48) || (evt.keyCode > 57)) ){
        campo.value = campo.value.replace(String.fromCharCode(evt.keyCode).toLowerCase(),"");
    }
    str = campo.value;

    while(str.search(",") != -1)
        str = str.replace(",","");
   
    var i = 0;

    while(i< str.length){
        if(str.substr(i,1) == ".")
            str = str.replace(".","");
        i++;
    }

    part1 = str.substr(0,str.length - 2);
    while(part1.search(" ") != -1)
        part1 = part1.replace(" ","");

    part2 = str.substr(str.length - 2,2);
    res = "";
    i = part1.length;
    sob = i % 3;
    if((sob != 0) && (i > 2))
        res = part1.substr(0,sob) + ".";
    else
        res = part1.substr(0,sob);
    j = 1;
    part1 = part1.substr(sob);
    i = 0;
    while(i < part1.length){
        if(j == 3){
            if(i + 1 == part1.length)
                res = res + part1.substr(i-2,3);
            else res = res + part1.substr(i-2,3) + ".";
        }
        i++;
        j = j<3?j+1:1;
    }
    campo.value = res + "," + part2;
	   
    if (campo.value == ',')
        campo.value = '';

}

function number_format( number, decimals, dec_point, thousands_sep ) {
    // %        nota 1: Para 1000.55 retorna com precisão 1 no FF/Opera é 1,000.5, mas no IE é 1,000.6
    // *     exemplo 1: number_format(1234.56);
    // *     retorno 1: '1,235'
    // *     exemplo 2: number_format(1234.56, 2, ',', ' ');
    // *     retorno 2: '1 234,56'
    // *     exemplo 3: number_format(1234.5678, 2, '.', '');
    // *     retorno 3: '1234.57'
    // *     exemplo 4: number_format(67, 2, ',', '.');
    // *     retorno 4: '67,00'
    // *     exemplo 5: number_format(1000);
    // *     retorno 5: '1,000'
    // *     exemplo 6: number_format(67.311, 2);
    // *     retorno 6: '67.31'

    decimals = decimals == '' ? 2 : decimals;

    var n = number, prec = decimals;
    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep == "undefined") ? ',' : thousands_sep;
    var dec = (typeof dec_point == "undefined") ? '.' : dec_point;

    var s = (prec > 0) ? n.toFixed(prec) : Math.round(n).toFixed(prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

    var abs = Math.abs(n).toFixed(prec);
    var _, i;

    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;

        _[0] = s.slice(0,i + (n < 0)) +
        _[0].slice(i).replace(/(\d{3})/g, sep+'$1');

        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }

    return s;
}

//---------------------------------------------------------------//
// MASK
//---------------------------------------------------------------//

function MASK(form) {
	
    $(form + ' input[mask=telefone]').each( function() {
		
        $(this).mask("(99) 9999-9999");
	
    });

    $(form + ' input[mask=cep]').each( function() {
		
        $(this).mask("99999-999");
	
    });

    $(form + ' input[mask=cpf]').each( function() {
		
        $(this).mask("999.999.999-99");
	
    });

    $(form + ' input[mask=cnpj]').each( function() {
		
        $(this).mask("99.999.999/9999-99");
	
    });

    $(form + ' input[mask=data]').each( function() {
		
        $(this).mask("99/99/9999");
	
    });

    $(form + ' input[mask=moeda]').each( function() {
		
        $(this).keyup( function(event) {
			
            formataMoeda(this,event);
								
        });

    });
	
    $(form + ' input[mask=dia_mes]').each( function() {
		
        $(this).mask("99/99");
	
    });
	
    $(form + ' input[mask=time]').each( function() {
		
        $(this).mask("99:99:99");
	
    });
	
    $(form + ' input[mask=numero]').each( function() {
		
        $(this).keyup( function(event) {
								
            if(((event.keyCode < 96) || (event.keyCode > 105)) && ((event.keyCode < 48) || (event.keyCode > 57)) ){
                $(this).val( $(this).val().replace(String.fromCharCode(event.keyCode).toLowerCase(),"") );
            }

            //verifica se não é numero
            if (isNaN($(this).val()))
                $(this).val("");

		
        });

    });

}

//--------------------------------------//
//      Validações  
//--------------------------------------//


var Validacao = {
    'Cadastro': function(form)
    {

        if ( $('#nome','#'+form).val() == "" || $('#nome','#'+form).val() == "Nome")
        {
            alert('Você precisa preencher o campo nome! ');
            $('#nome','#'+form).focus();
            return false;
        }

        if (!validaEmail($('#email','#'+form).val()))
        {
            $('#email','#'+form).focus();
            return false;
        }
        
        $.post("controller.php", $('#'+form).serialize(), function(retorno){
            alert(retorno);
            document.getElementById(form).reset();
            return false;
        });
		
        return false;
    },
    
    'Contato': function(form)
    {

        if ( $('#nome','#'+form).val() == "")
        {
            alert('Você precisa preencher o campo nome! ');
            $('#nome','#'+form).focus();
            return false;
        }

        if (!validaEmail($('#email','#'+form).val()))
        {
            $('#email','#'+form).focus();
            return false;
        }

        if ( $('#telefone','#'+form).val() == "")
        {
            alert('Você precisa preencher o campo telefone! ');
            $('#telefone','#'+form).focus();
            return false;
        }

        if ( $('#data_nascimento','#'+form).val() == "")
        {
            alert('Você precisa preencher o campo aniversario! ');
            $('#data_nascimento','#'+form).focus();
            return false;
        }

        if ( $('#mensagem','#'+form).val() == "")
        {
            alert('Você precisa preencher o campo mensagem!');
            $('#mensagem','#'+form).focus();
            return false;
        }
        
        $('.botoes-contato').html('Enviando...');
        $.post("controller.php", $('#'+form).serialize(), function(retorno){
            alert(retorno);
            $('.botoes-contato').html('<input type="reset" value=" " /> <input type="submit" value=" " name="btnEnviar" id="btnEnviar" />');
            document.getElementById(form).reset();
            return false;
        });
		
        return false;
    },
    
    'Lista': function(form)
    {

        error = 0;
        
        $('#'+form+' input[valida=nome]').each(function() {
            if($(this).val() == "")
            {
                alert('Você precisa digitar o nome! ')
                $(this).focus();
                error++;
                return false;
            }

        });
        
        if(error > 0)
            return false;

        $('#'+form+' input[valida=email]').each(function() {

            if(!validaEmail($(this).val()))
            {
                $(this).focus();
                error++;
                return false;
            }

        });

        if(error > 0)
            return false;

        
        $.post("controller.php", $('#'+form).serialize(), function(retorno){
            alert(retorno);
            document.getElementById(form).reset();
            $.fancybox.close();
            return false;
        });
		
        return false;
    },
    
    'Participa': function(form)
    {

        if (!validaEmail($('#email','#'+form).val()))
        {
            $('#email','#'+form).focus();
            return false;
        }

        if ( $('#resposta','#'+form).length > 0) {
            if ( $('#resposta','#'+form).val() == "" || $('#resposta','#'+form).val() == "resposta")
            {
                alert('Você precisa preencher o campo resposta!');
                $('#resposta','#'+form).focus();
                return false;
            }
        }
        
        $.post("controller.php", $('#'+form).serialize(), function(retorno){
            alert(retorno);
            document.getElementById(form).reset();
            $('.popup').fadeOut(300);
            return false;
        });
		
        return false;
    }
}
