/* Voltar ao topo */

$(function(){$.fn.scrollToTop=function(){
	$(this).hide().removeAttr("href");
	
		if($(window).scrollTop()!="0"){
		
	$(this).fadeIn("slow")}var scrollDiv=$(this);$(window).scroll(function(){if($(window).scrollTop()=="0"){$(scrollDiv).fadeOut("slow")}else{$(scrollDiv).fadeIn("slow")}});
	$(this).click(function(){$("html, body").animate({scrollTop:0},"slow")})}});

  $(function() {
    $("#to-top-button").scrollToTop();
        });

/* Menu Carreira FadeOut e FadeIn */
		
$(document).ready(function(){
    trataAncora();

	$('#menuprincipal a[href=#nav-carreira],#menucarreira a').click( function() {
        $('#menucarreira').fadeIn(1000);
        return false;
    } );

    $('#menuprincipal a[href!=#nav-carreira], #to-top-button').click( function() {
        $('#menucarreira').fadeOut(1000);

        return false;
    } );
});

function trataAncora() {
    var ancora = window.location.href.split("#")[1];
    if( ancora ) {
        switch( ancora ) {
            case 'carreira':
            case 'atletico':
            case 'selecao':
            case 'vitoria':
            case 'kashima':
            case 'rennes':
            case 'cska':
            case 'olympiacos':
                    $('#menucarreira').fadeIn(1000);
                break;
            default:
                break;
        }
    }
}


$(document).ready(function(){ 

	$('#menucarreira').hide();
	
	$("#menucarreira a").fadeTo('slow', 0.33);	
		
	$("#menucarreira a").mouseover(function() { 
		$(this).fadeTo('fast', 1);					
	}).mouseout(function() { 	
		$(this).fadeTo('slow', 0.33);		
	});					 	 		 	 		 		 		 
	
});

/* ---------------------------------- */

/* Scroll Vertical */

$(function(){
    $('a[href*=#]').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
        && location.hostname == this.hostname) {
            var $target = $(this.hash);
            $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
            if ($target.length) {
                var targetOffset = $target.offset().top;
                $('html,body').animate({scrollTop: targetOffset}, 1000);
                return false;
            }
        }
    });
});


/* ---------------------------------- */

/* Adicionar Class na tag Body */

$(document).ready(function(){ 

	$("a[href*=#nav-noticias]").click( function(){ 
		$("body").removeClass("carreira_texto , multimidia_texto , contato_texto").addClass("noticias_texto");
	});
	
	$("a[href*=#nav-carreira]").click( function(){
		$("body").removeClass("noticias_texto , multimidia_texto , contato_texto").addClass("carreira_texto");
	});
	
	$("a[href*=#nav-multimidia]").click( function(){ 
		$("body").removeClass("carreira_texto , noticias_texto , contato_texto").addClass("multimidia_texto");
	});
	
	$("a[href*=#nav-contato]").click( function(){ 
		$("body").removeClass("carreira_texto , noticias_texto , multimidia_texto").addClass("contato_texto");
	});
	
	$("#to-top-button").click( function(){ 
		$("body").removeClass("carreira_texto , noticias_texto , multimidia_texto , contato_texto").addClass("noticias_texto");
	});	 		 	 

});


/* jQuery Galeria de Foto */

            $(function() {
				//the loading image
				var $loader		= $('#st_loading');
				//the ul element 
				var $list		= $('#st_nav');
				//the current image being shown
				var $currImage 	= $('#st_main').children('img:first');
				
				//let's load the current image 
				//and just then display the navigation menu
				$('<img>').load(function(){
					$loader.hide();
					$currImage.fadeIn(2000);
					//slide out the menu
					setTimeout(function(){
						$list.animate({'left':'0px'},500);
					},
					1000);
				}).attr('src',$currImage.attr('src'));
				
				//calculates the width of the div element 
				//where the thumbs are going to be displayed
				buildThumbs();
				
				function buildThumbs(){
					$list.children('li.album').each(function(){
						var $elem 			= $(this);
						var $thumbs_wrapper = $elem.find('.st_thumbs_wrapper');
						var $thumbs 		= $thumbs_wrapper.children(':first');
						//each thumb has 180px and we add 3 of margin
						var finalW 			= $thumbs.find('img').length * 183;
						$thumbs.css('width',finalW + 'px');
						//make this element scrollable
						makeScrollable($thumbs_wrapper,$thumbs);
					});
				}
				
				//clicking on the menu items (up and down arrow)
				//makes the thumbs div appear, and hides the current 
				//opened menu (if any)
				$list.find('.st_arrow_down').live('click',function(){
					var $this = $(this);
					hideThumbs();
					$this.addClass('st_arrow_up').removeClass('st_arrow_down');
					var $elem = $this.closest('li');
					$elem.addClass('current').animate({'height':'170px'},200);
					var $thumbs_wrapper = $this.parent().next();
					$thumbs_wrapper.show(200);
				});
				$list.find('.st_arrow_up').live('click',function(){
					var $this = $(this);
					$this.addClass('st_arrow_down').removeClass('st_arrow_up');
					hideThumbs();
				});
				
				//clicking on a thumb, replaces the large image
				$list.find('.st_thumbs img').bind('click',function(){
					var $this = $(this);
					$loader.show();
					$('<img class="st_preview"/>').load(function(){
						var $this = $(this);
						var $currImage = $('#st_main').children('img:first');
						$this.insertBefore($currImage);
						$loader.hide();
						$currImage.fadeOut(1000,function(){
							$(this).remove();
						});
					}).attr('src',$this.attr('alt'));
				}).bind('mouseenter',function(){
					$(this).stop().animate({'opacity':'1'});
				}).bind('mouseleave',function(){
					$(this).stop().animate({'opacity':'0.2'});
				});
				
				//function to hide the current opened menu
				function hideThumbs(){
					$list.find('li.current')
						 .animate({'height':'50px'},400,function(){
							$(this).removeClass('current');
						 })
						 .find('.st_thumbs_wrapper')
						 .hide(200)
						 .andSelf()
						 .find('.st_link span')
						 .addClass('st_arrow_down')
						 .removeClass('st_arrow_up');
				}

				//makes the thumbs div scrollable
				//on mouse move the div scrolls automatically
				function makeScrollable($outer, $inner){
					var extra 			= 800;
					//Get menu width
					var divWidth = $outer.width();
					//Remove scrollbars
					$outer.css({
						overflow: 'hidden'
					});
					//Find last image in container
					var lastElem = $inner.find('img:last');
					$outer.scrollLeft(0);
					//When user move mouse over menu
					$outer.unbind('mousemove').bind('mousemove',function(e){
						var containerWidth = lastElem[0].offsetLeft + lastElem.outerWidth() + 2*extra;
						var left = (e.pageX - $outer.offset().left) * (containerWidth-divWidth) / divWidth - extra;
						$outer.scrollLeft(left);
					});
				}
            });

/* Expandir Box de Notícia */

$(document).ready(function(){
	$('.box-noticia').css('display', 'none')
	$('span', '#box-noticias').click(function() {
		$(this).next().slideToggle('slow')
		.siblings('.box-noticia:visible').slideToggle('fast');
	
	});
})			

/* Formulário */

$(document).ready(function(){
$('.form-contato').bind('submit', function(){
	var formdata = $(this).serialize();

        $.ajax({
            type: "POST",
            url: 'envia.php',
            data: formdata,
            success: function( resultado )
            {
                $('.form-resposta').html(resultado);
				$(".form-contato").reset();
            },
            error: function( resultado )
            {
                alert('Ocorreu um erro ao enviar o e-mail. Favor envie a mensagem para contato@duducearense.com.br');
                
            }
        });
	return false;
});
})

// Reseta dados do formulário
jQuery.fn.reset = function (){
   $(this).each (function(){
      this.reset();
   });
}

// Twitter //

function twitterTimeline(username, count){
	
	var url = 'http://search.twitter.com/search.json?callback=?&rpp='+ count +'&q=from:'+ username;
	
	var loading = $("<p>Carregando...<\/p>");
	
	$("#twitter").append(loading);
	
	$.getJSON(url,function(data){
		$("#twitter").empty();
		$.each(data.results, function(i, obj){
			if(i == 0){
				$("#twitter").prepend('<ul class="tweet-list"><li class="tweet-content-' + i + '">');
			}else{
				$('.tweet-list').append('<li class="tweet-content-' + i + '">')	
			}
			$('.tweet-content-' + i + '').append('<span class="tweet-link-' + i + '">' + obj.text.replace(/#(.*?)(\s|$)/g, '<span class="hash">#$1 <\/span>').replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, '<a href="$&">$&<\/a> ').replace(/@(.*?)(\s|\(|\)|$)/g, '<a href="http://twitter.com/$1">@$1 <\/a>$2'), ' <span class="time"><a href="http://twitter.com/'+username+'/statuses/'+this.id_str+'" target=_blank>' +H(this.created_at)+'<\/a><\/span>');
		});
	});
	
	$("h3").append(' @' + username);
}
 
 
var K = function () {
    var a = navigator.userAgent;
    return {
        ie: a.match(/MSIE\s([^;]*)/)
    }
}();
 
var H = function (a) {
    var b = new Date();
    var c = new Date(a);
    if (K.ie) {
        c = Date.parse(a.replace(/( \+)/, ' UTC$1'))
    }
    var d = b - c;
    var e = 1000,
        minute = e * 60,
        hour = minute * 60,
        day = hour * 24,
        week = day * 7;
    if (isNaN(d) || d < 0) {
        return ""
    }
    if (d < e * 7) {
        return "agora"
    }
    if (d < minute) {
        return Math.floor(d / e) + " segundos atrás"
    }
    if (d < minute * 2) {
        return "1 minuto atrás"
    }
    if (d < hour) {
        return Math.floor(d / minute) + " minutos atrás"
    }
    if (d < hour * 2) {
        return "1 hora atrás"
    }
    if (d < day) {
        return Math.floor(d / hour) + " horas atrás"
    }
    if (d > day && d < day * 2) {
        return "ontem"
    }
    if (d < day * 365) {
        return Math.floor(d / day) + " dias atrás"
    } else {
        return "mais de um ano atrás"
    }
};
 
 
$(document).ready(function(){
	twitterTimeline('duducearense', 1);
});
