$(document).ready(function(){

    $('#status').history(function(e, currentHash, previousHash) {
        if(currentHash != '')
            carregaHash('#'+currentHash);
        else
            carregaHash('');

        //desmarca e marca tags ao navegar pelo browser
        desmarcaTags();
        marcaTags(currentHash);

        //desmarca e marca categorias ao navegar pelo browser
        $('#mainMenuItem dd').removeClass('current');
        $('#mainMenuItem dd.' + currentHash).addClass('current');
    });


    //pegando o HASH
    var hash    =   window.location.hash;


    //se existir HASH o carregamento é por AJAX
    if (hash){
        carregaHash(hash);
        marcaTags(hash);
        $('#mainMenuItem dd.' + hash.substr(1)).addClass('current');
    } else {
        $('#trabalhosItem').show();
    }
    
    //redirecionando se o idioma do browser não for PT-BR e nao tiver cookie com idioma
//    if( navigator.language == undefined ) navigator.language = '';
//        if (navigator.language.toLowerCase() != 'pt-br' && (getCookie('idioma') == null || getCookie('idioma') == ''))
//            window.location =    baseUrl + 'en/' + location.href.replace(baseUrl,'');
    


    //funcoes do lightbox
    $('#stillsItem .lightBox').fancybox({
        'width'     :   '910',
        'scrolling' :   'no',
        'autoScale' :   false,
        'changeSpeed':  200,
        'overlayOpacity': 0.8,
        'overlayColor': '#000'
    });

    

    //campos clicaveis
    $('.clicavel').focus(function(){

        if( $(this).val() == $(this).attr('title') ){
            $(this).val('');
        }

    });
    $('.clicavel').blur(function(){

        if( $(this).val() == '' ){
            $(this).val($(this).attr('title'));
        }

    });

    //newsletter
    $("#newsletterForm").submit( function(){

        $.post(
            $(this).attr('action'),
            {email : $('#newsletter').val()},
            function (data){

                $('#newsletterForm .msgResposta').html(data);
                $('#newsletterForm .msgResposta').fadeIn(500);
                setTimeout(function(){
                    $('#newsletterForm .msgResposta').fadeOut(500)
                },5000)
            });

        return false;
    } );








    //verifica se os caches estao validos
    if ( $('#atividadesItem .content').html() == '' ){
        //atividades
        $.get( baseUrl + "home/ajax_atividades", "" ,
            function (data) {
                $('#atividadesItem .content').html(data)
                
            }
        );
    }

    if ( $('#twitterItem .content').html() == '' ){
        //tweet
        $.get( baseUrl + "home/ajax_tweet", "" ,
            function (data){
                $('#twitterItem .content').html(data);
            }
        );
    }
    
});







function getCookie(c_name){
    if (document.cookie.length>0)
      {
      c_start=document.cookie.indexOf(c_name + "=");
      if (c_start!=-1)
        {
        c_start=c_start + c_name.length+1;
        c_end=document.cookie.indexOf(";",c_start);
        if (c_end==-1) c_end=document.cookie.length;
        return unescape(document.cookie.substring(c_start,c_end));
        }
      }
    return "";
}


function marcaTags(hash){
    //tratando a hash passada
    var arrTagRecebida     =   hash.split('+');

    for (i in arrTagRecebida)
        if (i > 0)
            $('#tagsItem .' + arrTagRecebida[i] + ' a').addClass('current');
}

function desmarcaTags(){
    $('#tagsItem a').removeClass('current');
}




function carregaHash(hash){

    if (hash != '')
        $.history.add(hash);
    
    $('#todosTrabalhosLine').fadeOut(300);
    
    $.ajax({
            type:       "POST",
            url:        baseUrl + "home/ajax_tags",
            data:       {hash: hash},
            dataType:   "html",

            beforeSend: function (data) {
                $('#contentLine a').animate({
                    opacity: 0.2
                },2000);
            },

            success:    function (data) {
                $('#contentLine').html(data);
                $('#trabalhosItem').stop(false,true).fadeIn(1000);
                $('#contentLine').prepend('<script type="text/javascript" src="'+ baseUrl + ASSETS + '/js/columns.js"></script>');
            }

        });
        endereco  =   replaceAll( location.href , "+" , ":" );
        $('#langSwitchItem .pt a').attr('href', endereco.replace("#","pt/hash/") );
        $('#langSwitchItem .en a').attr('href', endereco.replace("#","en/hash/") );
}

function replaceAll(string, token, newtoken) {
	while (string.indexOf(token) != -1) {
 		string = string.replace(token, newtoken);
	}
	return string;
}





function carregaTag(tag){

    var tagRecebida =   tag.substr(1);

    var encontrado  =   false;


    //tratando a hash passada
    var arrTagRecebida     =   tagRecebida.split('+');

    //identifica como está a hash agora
    var hashAtual  =   window.location.hash;

    //divide a hash atual em grupos de tags
    var tagsAtuais  =   hashAtual.substr(1).split('+');
    
    if(arrTagRecebida.length == 1 || arrTagRecebida[0] != 'tags'){

        tagsAtuais  =   arrTagRecebida;
        $('#tagsLine').slideUp(170);
        $('#tagsItem a').removeClass('current');
        $('#mainMenuItem dd').removeClass('current');
        $('#mainMenuItem dd.' + arrTagRecebida[0]).addClass('current');

    } else {

        $('#mainMenuItem dd:not(.tags)').removeClass('current');
        $('#todosTrabalhosLine').hide();

        for (var i in tagsAtuais){

            if ( i >= 1 ){

                if (tagsAtuais[i] == arrTagRecebida[1]){
                    tagsAtuais.splice(i,1);
                    encontrado  =   true;
                    $('#tagsItem .' + arrTagRecebida[1] + ' a').removeClass('current');
                }

            }

        }

        if (encontrado  === false){
            tagsAtuais.splice(0,1,'tags');
            tagsAtuais.push(arrTagRecebida[1]);
            $('#tagsItem .' + arrTagRecebida[1] + ' a').addClass('current');
        }
    }


    novaHash    =   tagsAtuais.join('+');

    window.location.hash    =   novaHash;

    carregaHash('#' + novaHash);

}

function tagsShow(){
        
    if( $('#tagsLine').css('display')=='none' )
        $('#tagsLine').slideDown(170);
    else {
        $('#tagsLine').slideUp(170);
        $('.tags').removeClass('current');
    }
    
}

function jobsShow(){
    carregaImgs('.limite');
    $('.limite').fadeIn(500);
    verificaOffset();
    $('#todosTrabalhosLine').hide();
}

