$(document).ready(function() {
	
jQuery.fn.Shake = function(){ 
     this.each(function(init){ 
          var jqNode = $(this); 
          jqNode.css({position: 'relative'}); 
          for (var x = 1; x <= 4; x++){ 
		  
               jqNode.animate({ left: -10 },30).animate({ left: 0 },30).animate({ left: 10 },30) .animate({ left: 0 },100); 
			   
          } 
     }); 
	return this; 
}
   
	var numItems = $("#eventos .list ul li").length; //numero de itens na lista
	var itemWidth = 147; //largura de um item
	var visibleItems = 4;
	var index = 0;
	var slide = 0;
	var totalWidth = numItems*itemWidth; //largura total da lista
	
	//resto da divisão arredondado
	var div = Math.floor(numItems/visibleItems); 
		
	//atribui uma largura à lista de fotos
	$("#eventos .list ul").css({"width":totalWidth + "px"});
	
	//clicando na seta
	$("#eventos .arrow-right").click(function() {
       
		//direção que o slide deve seguir, esquerda ou direita
		var direction = $(this).attr("direction");
				
		/*
			Incrementa ou decrementa o índice de acordo com a direção.
			Para mudar a direção basta trocar os sinais.
		*/
		if (direction == 'right') {
		   index = index-1; 
		} else {
		   index = index+1;
		}
		
		slide = index*itemWidth;

		//atingiu o fim, zera slide e índice
		if ((slide == (-1 * totalWidth)) || (-1 * index == (numItems - visibleItems) + 1 && direction == 'right')) {
		
			slide = 0;
		   	index = 0;

		} else if (slide > 0) {
		
		   //slide = -1 * (totalWidth - itemWidth);
		   //index = -1 * (numItems - 1);
		
		}
       
       	$("#eventos .list ul").animate({ "left" : slide + "px" }, function(){
			
			var subtitle_index = index * (-1);
						   
		});
			
		
   	});
	
	function showEvent(calendar_id){
		
		var returnContainer = $("#eventos .container");
		
		returnContainer.ajaxStart(function(){
			returnContainer.html('<div class="loading"></div>');
		});
				
		$.ajax({
			url: "ajax/ShowEvent.ajax.php",
			type: "POST",
			data: ({"calendar_id" : calendar_id}),
			dataType: "html",
			success: function(data){
				returnContainer.html(data);
			}
		});
		
	}
	
	function getEventVideo(calendar_id){
		
		var returnContainer = $("#center .video .container");
		
		$.ajax({
			url: "ajax/GetEventVideo.ajax.php",
			type: "POST",
			data: ({"calendar_id" : calendar_id}),
			dataType: "html",
			success: function(data){
				returnContainer.html(data);
			}
		});
		
	}
	
	//clicando no evento
	$("#eventos .list ul li").click(function() {
		
		var current = $(this).parents(2).find(".current");
				
   		showEvent($(this).attr("calendar_id"));
		getEventVideo($(this).attr("calendar_id"));
		
		current.html($(this).html()).Shake();
   	
	});
	
	showEvent($("#eventos .container").attr("calendar_id"));
   	getEventVideo($("#eventos .container").attr("calendar_id"));
	
});
