/*
	Javascript
	Website: NOMEDOWEBSITE
    Created: 11-03-2011
    Modified: 23-03-2011
    Author: João Fraga - jgfraga@gmail.com
*/

/*
 * Make a element fly, using float
 * @author JoÃ£o Gabriel - jgfraga[at]gmail.com
 * @param relative_to DOMObject - The parent related
 * @param buffer int - Space from left of the parent related
 */

jQuery.fn.fly = function( relative_to, buffer ) {

  buffer = (typeof buffer !== 'undefined') ? buffer : 0;

  var offset = relative_to.offset(),
      size   = relative_to.width(),
      left   = (offset.left + size) + buffer;

  $(this).css({
   'left': left,
   'position': 'fixed',
   'top' : '40%'
  });

};

function is_logged() {
    return $("#user_id").val() != 0;
}

function show_login_form() {
    $("#login-link").click();
}

$('document').ready(function(){

    // CUFON
    Cufon.replace('#edicao .num,#curriculo *')
    //Cufon.replace('#artigos .autor',{fontStyle:'italic'})

    $('#nota').fly($('#wrapper'));
    if( !is_logged() ){
        $('#nota').click(function(){
            show_login_form()
        })
    }

    // Here come the live javascript

    $('#edicao .atual').click(function(){
        $('#edicao .edicoes').slideDown();
    })

    $('.deslogado a, a.deslogado').append(
        '<div class="deslogado-info">' +
        '<p>Faça login para marcar seus artigos preferidos, criar notas e participar do espaço público.</p>' +
        '</div>'
    );

    $('.deslogado a, a.deslogado').mouseenter(function(){
        $(this).children('.deslogado-info').show();
    }).mouseleave(function(){
        $(this).children('.deslogado-info').hide();
    }).mousemove(function(e){
        $(this).children('.deslogado-info').css({
            'left' : (e.pageX + 20) + 'px'
        });
    }).click(function(){
        $('#login-link').animate({
            opacity: 0.25
        },300,function(){
            $(this).animate({
                opacity: 1
            })
        });
        return false;
    })

    $(document).bind('click', function(e) {

        var $clicked = $(e.target);

        if (! $clicked.parents().hasClass("edicoes") && ! $clicked.parents().hasClass("atual") )
            $(".edicoes").slideUp();
    });

    // MIDIA

    $('#midia #thumbs li').click(function(){
        if($(this).hasClass('image')) {

            $('#midia #show #midia-img').attr({'src':''}).hide();

            var img = new Image();
            var image_src = $(this).find('.original img').attr('src');
            var subtitle = $(this).find('.original .subtitle').text();
            img.src = image_src;
            var originalHeight = $('#midia #show #midia-img').height();

            img.onload = function() {

                var newHeight = this.height;
                $('#midia #show').animate({
                    'height' : newHeight
                },"normal",function(){
                    $('#midia #prev, #midia #next').css({
                        'margin-top' : (newHeight/2) - 15
                    });
                    $('#midia #show #midia-img').attr({'src':image_src}).height(newHeight).show();
                });
                if( subtitle.length > 0 )
                    $("#midia #show").append('<div class="subtitle">'+subtitle+'</div>')
            }

            $('#video').empty().hide();

        } else if ( $(this).hasClass('video') ) {

            $('#midia #show').css({'min-height':'420px'})
            $('#midia #show #midia-img').animate({
                    'height' : 420
                },"normal");
            $('#midia #show').animate({
                  'height' : 420
              },"normal",function(){
                  $('#midia #prev, #midia #next').css({
                      'margin-top' : (420/2) - 15
                  });
                 // $('#midia #show #midia-img').attr({'src':image_src}).height(newHeight).show();
              });
            $("#midia #show .subtitle").remove();
            $('#video').empty().append($(this).find('.embed').html()).show();
        } else if ( $(this).hasClass('embed-item') ) {

            $('#midia #show').css({'min-height':'420px'})
            $('#midia #show #midia-img').animate({
                    'height' : 420
                },"normal");
            $('#midia #show').animate({
                  'height' : 420
              },"normal",function(){
                  $('#midia #prev, #midia #next').css({
                      'margin-top' : (420/2) - 15
                  });
                 // $('#midia #show #midia-img').attr({'src':image_src}).height(newHeight).show();
              });
            $("#midia #show .subtitle").remove();
            $('#video').empty().append($(this).find('.embed textarea').val()).show();
        }

        $('#midia #thumbs li').removeClass('active');
        $(this).addClass('active');
        return false;
    })

    $('#midia #next').click(function(){
         $('#midia #thumbs li.active').next().click();
    })

    $('#midia #prev').click(function(){
         $('#midia #thumbs li.active').prev().click();
    })

    $("#value > div").hide();
	$("#value > div:eq(0)").show();
	$("#tabs > a:eq(0)").css("background", "url(tab-selected.jpg) top left no-repeat");

    $('#login-link').leanModal();

    $('#midia #thumbs li:first-child').click();


    // SALVAR NOTA
    $('#nota form').ajaxForm({
        dataType: 'xml',
        success: function(xml){
            result = $(xml).find('usuario-nota').attr('result');
            id = $(xml).find('usuario-nota').attr('id');

            if( result == 'success' ) {
                $('#nota-id').val(id);
                $('#nota .header').animate({
                    'backgroundColor' : '#55FF55'
                },400,function(){
                    $(this).animate({'backgroundColor' : '#FAFAFA'},400)
                })
            }

            if( $(xml).find('usuario-nota').attr('type') == 'created' ) {
                numNotas = parseInt($('#numNotas').html()) + 1;
                $('#numNotas').html(numNotas)
                $('#nova-nota').addClass('ativo');
            }

        }
    });

    // NOVO TOPICO
    if( is_logged() ) {
        $('#criar-topico').leanModal();
        $('#criar-resposta').leanModal();
    } else {
        $('#criar-topico, #criar-resposta').click(function(){
            show_login_form();
            return false;
        })
    }

    /* FONT SIZE */
    var originalFontSize = $('.conteudo p').css('font-size');
    var originalLineHeight = $('.conteudo p').css('line-height');

    $('.resetFont').click(function(){
        $('.conteudo p').css({'font-size':originalFontSize,'line-height':originalLineHeight})
        return false;
    })
    $('.increaseFont').click(function(){
        var currentFontSize = $('.conteudo p').css('font-size');
        var currentFontSizeNum = parseFloat(currentFontSize, 10);
        var newFontSize = currentFontSizeNum*1.1;
        var newLineHeight = newFontSize*1.5;
        $('.conteudo p').css({'font-size':newFontSize,'line-height':newLineHeight+'px'});
        return false;
    })

    // Validate

    $('#user-login').validate();
    $('#user-register').validate();
    $('#nova-resposta form').validate();
    $('#novo-topico form').validate();

    $('#info-capa').hide();
    $('#destaque').mouseenter(function(){
        $('#info-capa').show();
    }).mouseleave(function(){
        $('#info-capa').hide();
    })

    // Idiomas

    $("#idiomas a.en").click(function(){
        var t=((window.getSelection&&window.getSelection())||(document.getSelection&&document.getSelection())||(document.selection&&document.selection.createRange&&document.selection.createRange().text));var e=(document.charset||document.characterSet);if(t!=''){location.href='http://translate.google.com/?text='+t+'&hl=en&langpair=auto|en&tbb=1&ie='+e;}else{location.href='http://translate.google.com/translate?u='+encodeURIComponent(location.href)+'&hl=en&langpair=auto|en&tbb=1&ie='+e;};
    })

    $("#idiomas a.es").click(function(){
        var t=((window.getSelection&&window.getSelection())||(document.getSelection&&document.getSelection())||(document.selection&&document.selection.createRange&&document.selection.createRange().text));var e=(document.charset||document.characterSet);if(t!=''){location.href='http://translate.google.com/?text='+t+'&hl=en&langpair=auto|es&tbb=1&ie='+e;}else{location.href='http://translate.google.com/translate?u='+encodeURIComponent(location.href)+'&hl=en&langpair=auto|es&tbb=1&ie='+e;};
    })

    $("#idiomas a.fr").click(function(){
        var t=((window.getSelection&&window.getSelection())||(document.getSelection&&document.getSelection())||(document.selection&&document.selection.createRange&&document.selection.createRange().text));var e=(document.charset||document.characterSet);if(t!=''){location.href='http://translate.google.com/?text='+t+'&hl=en&langpair=auto|fr&tbb=1&ie='+e;}else{location.href='http://translate.google.com/translate?u='+encodeURIComponent(location.href)+'&hl=en&langpair=auto|fr&tbb=1&ie='+e;};
    })

})

function opentab(num) {
	$("#value > div").hide();
	$("#value > div:eq(" + (num-1) + ")").fadeIn();
	$("#tabs > a").css("background", "#EEE");
	$("#tabs > a:eq(" + (num-1) + ")").css("background", "#FFF");
}

function toggleFavorite(id) {
    $.ajax({
        'url' : id,
        dataType: 'xml',
        'success' : function(xml) {
            if ($(xml).find('usuario-favorito').attr('type') == 'created') {
                numFavoritos = parseInt($('#numFavoritos').html()) + 1;

            }
            else if ($(xml).find('usuario-favorito').attr('type') == 'deleted') {
                numFavoritos = parseInt($('#numFavoritos').html()) - 1;
            }
            $('#numFavoritos').html(numFavoritos);
        }
    })
    $('#favoritar'). toggleClass('ativo');
    return false;
}

function deletaNota(id){
	if ( confirm('Tem certeza que deseja apagar sua nota?') ) {  $('#deletar_nota_'+id).click(); }
}


// Here come the functions
$(document).ready(function(){

    //Get our elements for faster access and set overlay width
    var div = $('div#thumbs'),
                 ul = $('div#thumbs ul'),
                 // unordered list's left margin
                 ulPadding = 15;

    //Get menu width
    var divWidth = div.width();

    //Remove scrollbars
    div.css({overflow: 'hidden'});

    //Find last image container
    var lastLi = ul.find('li:last-child');

    //When user move mouse over menu
    div.mousemove(function(e){

      //As images are loaded ul width increases,
      //so we recalculate it each time
      var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;

      var left = (e.pageX - div.offset().left) * (ulWidth-divWidth) / divWidth;
      div.scrollLeft(left);
    });
});
