$(document).ready(function(){

    var hy = $(document).height();
    var hElementy = $("#container").height();
    //total para afastamento do top
    ty = (hy - hElementy) / 2;

    if(parseInt(ty) > 23)
        $("#container").css('padding-top',ty+'px');

    $.history.init(function(url) {
        if(url != "") {
            /*
			$('#content').fadeOut(400,function(){
        		$('#content').empty();
                loadPage(url == "" ? "home" : url);
            });*/


            $('.section_content_capa').animate({
                height: 'toggle'
            }, 'slow');

            setTimeout(function(){
                $('.section_content').empty();
                loadPage(url == "" ? "home" : url);
            }, 1000);

        } else {
            loadPage(url == "" ? "home" : url);
            $('.section_content_capa').css('display', 'block');
        }
    });

    $('.section_menu ul li a').click(function() {
        if($(this).attr('class') != 'none') {
            var url = $(this).attr('href');
            url = url.replace(/^.*#/, '');
            $.history.load(url);
        }
    });
/*
	$("a.fancybox").fancybox({
		'width' : 775,
		'height' : 620,
		'padding' : 0,
        'autoScale' : false,
        'transitionIn' : 'none',
		'transitionOut' : 'none',
		'type' : 'iframe'
	});
	*/


});

function loadCliente() {

    $("#container_content").carouFredSel({
        items       : 1,
        circular : false,
        auto : false,
        pagination  : "#paginacao",
        width : 270,
        height : 420,
        scroll : {
            easing          : "easeOutBounce",
            duration        : 2000
        }
    });

}

function loadEquipe() {

    $("#container_content").carouFredSel({
        items       : 1,
        circular : false,
        auto : false,
        pagination  : "#paginacao",
        width : 300,
        height : 420,
        scroll : {
            easing          : "easeOutBounce",
            duration        : 2000
        }
    });

}

function loadBlog() {

    $("a.fancyBlog").fancybox();
    $("#container_content").carouFredSel({
        items       : 1,
        circular : false,
        auto : false,
        pagination  : "#paginacao",
        width : 300,
        height : 420,
        scroll : {
            easing          : "easeOutBounce",
            duration        : 2000
        }
    });


}

function loadFacaWoodoo() {

    $("a.fancyBlog").fancybox();
    $("a.fancySwf").fancybox({
        'padding'           : 0,
        'autoScale'         : false,
        'transitionIn'      : 'none',
        'width'             : 630,
        'height'            : 500,
        'type'              : 'iframe',
        'scrolling'         : 'no',
        'transitionOut'     : 'none'
    });

}

function loadPage(num) {
    a = num.split("/");
    num = a[0];
    resto = a[1];

    $('.section_menu ul li .selected').remove();
    $('.section_menu ul li a:[href=#' + num + ']').parent().append('<div class="selected"></div>');

    var animacoes = ["boneco","cocando","girando","piscando","stretch"];

    if(num == 'home' || num == 'blog' ||  num == 'cool_stuff')
        pos = 0;

    if(num == 'woodoo' || num == 'faca_woodoo')
        pos = 1;

    if(num == 'equipe')
        pos = 2;

    if(num == 'clientes')
        pos = 3;

    if(num == 'contato')
        pos = 4;

    $("#animacao").fadeOut(1000, function(){
        var so = new SWFObject("_swf/" + animacoes[pos] + ".swf", "animacaoSWF", "315", "455", "8");
        so.addParam('wmode','transparent');
        so.write("animacao");
    });

    setTimeout(function(){
        $("#animacao").fadeIn(1000);
    }, 500);
    

    $('.section_content').load(num +".php", "", function(){

        if(num == 'faca_woodoo')
            loadFacaWoodoo();
        if(num == 'clientes')
            loadCliente();
        if(num == 'equipe')
            loadEquipe();
        if(num == 'blog' ||  num == 'cool_stuff' ||  num == 'home') {
            loadBlog();
        }

        setTimeout(function(){
            $('.section_content_capa').animate({
                height: 'toggle'
            }, 'slow')
        }, 1000);

        setTimeout(function(){
            if(num == 'blog' ||  num == 'cool_stuff' ||  num == 'home') {
                if(resto != "" && resto != undefined) {
                    $.fancybox({
                        'autoScale'		: false,
                        'transitionIn'	: 'none',
                        'transitionOut'	: 'none',
                        'href'	: 'load_blog.php?B='+resto
                    });
                }
            }
        }, 2000);

    });
}

//---------------------------------------------------------------------------------//
// COMMONS
//---------------------------------------------------------------------------------//

/*
 * 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("");


        });

    });

}

var Validacao = {

    'Contato': function(form)
    {

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

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

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

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

        $('#botoes-comentario','#'+form).html('<img src="img/loading.gif" border="0" align="absmiddle" /> Carregando...');
        $.post("ajax_contato.php", $('#'+form).serialize(), function(retorno){
            alert(retorno);
            document.getElementById(form).reset();
            $('#botoes-comentario','#'+form).html('<input id="btnContato" name="btnContato" value="Enviar" type="submit"  class="btnColor w60"  />');
        });
        return false;
    }

}
