//Additional Core Methods
Date.prototype.toOneDay = function(){return parseInt(this.getTime()/(1000*60*60*24),10);}
Date.prototype.isToday = function(otherDate){return this.toOneDay() == otherDate.toOneDay()?true:false;}
Date.prototype.isPast = function(otherDate){return this < otherDate?true:false;}
Date.prototype.isFuture = function(otherDate){return this > otherDate?true:false;}
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, '');}

$(document).ready(function(){
	var gallery_max_width = $("#galeriaFoto").width();
    var gallery_max_height = $("#galeriaFoto").height();
    
	// Triggers the selection of a gallery item
	function selectGalleryImg(item) {
		var selected_item = $("#galeriaNav #thumbsWrapper ul li:eq("+item+")");
		var carousel = $("#thumbsWrapper").siblings(".carouselNav");
		var legend = $(selected_item).find("a").attr("title");
		var credit = $(selected_item).find("p.thumb-credito").text();
		var src = $(selected_item).find("a").attr("href");

		$(selected_item)
			.addClass("active")
			.siblings()
				.removeClass("active");

		$(carousel).find("li").removeClass("disabled");
		$("#galeriaHoverNav").find("li").removeClass("disabled");

		if(item == 0) {
			$(carousel).find("li.ant").addClass("disabled");
			$("#galeriaHoverNav").find("li.ant").addClass("disabled");
		}
		if (item == $(carousel).data("carousel_length")-1) {
			$(carousel).find("li.prox").addClass("disabled");
			$("#galeriaHoverNav").find("li.prox").addClass("disabled");
		}

		$("#galeriaFoto .credito").text(credit);
		$("#galeriaFoto .legenda").text(legend);
		$("#galeriaInterval .num").text(item+1);

		loadGalleryImg(src);
	}

	// Loads image on gallery container
	function loadGalleryImg(src) {
		var img = new Image();

		$("#galeriaImg")
			.addClass("carregando animating");
		$("#galeriaImg img")
			.remove();

		$(img)
			.load(function(){
				$(this).css("display", "none");

				$("#galeriaImg").append(this);
				if($(this).width() > gallery_max_width) { // resizes image if it's too big to fit the container
					$(this).css("width", gallery_max_width);
                    $(this).css("height", "auto");
				}
               
				$("#galeriaImg")
					.removeClass("carregando")
					.animate({
						height: $(this).height(),
						width: $(this).width()
					}, function(){
						$("#galeriaImg").removeClass("animating");
					});
				$("#galeriaFoto .credito").css("width", $(this).width());

				$(this).fadeIn();
			})
			.error(function(){
				alert("Erro ao carregar imagem");
			})
			.attr("src", src);
	}

	function scrollCarousel(c, direction) {
		var carousel = $(c);
		var length = $(carousel).data("carousel_length");
		var offset = $(carousel).data("carousel_offset");
		var visible_items = $(carousel).data("carousel_visible_items");
		var item_width = $(carousel).data("item_width");

		// fix to melhor da semna componente
		if ($(carousel).parent(".carousel").is("#melhorSemanaNav")) {
			length = length + 1;
		}
		// fix to guia 10 mais left component
		if($(".categoriasWrapper").width() <= 210) {
			visible_items = visible_items - 1
			if(offset == (length - offset) -1) {
				item_width = item_width + 4;
			}
		}


		if(direction == "right") {
			if(length - offset <= visible_items) { // end of carousel

			} else {
				$(carousel).data("is_animating", true);
				$(carousel).data("carousel_offset", offset+1);
				$(carousel).siblings(".carouselItems").find("ul")
					.css("position", "absolute")
					.animate({ left : (offset+1)*item_width*-1}, "normal", null, function(){
						$(carousel).data("is_animating", false);
					});
			}
		} else {
			if(offset == 0) { // end of carousel

			} else {
				$(carousel).data("is_animating", true);
				$(carousel).data("carousel_offset", offset-1);
				$(carousel).siblings(".carouselItems").find("ul")
					.css("position", "absolute")
					.animate({ left : (offset-1)*item_width*-1}, "normal", null, function(){
						$(carousel).data("is_animating", false);
					});
			}
		}
	}

	// Loads carousel data and stores on each object
	$("ul.carouselNav").each(function(){
		var carousel_items = $(this).siblings(".carouselItems");

		var item_width = $(carousel_items).find("li:first").outerWidth(true);
		var carousel_width = $(carousel_items).width();

		var carousel_length = $(carousel_items).find("li").length;
		var carousel_visible_items = Math.ceil(carousel_width / item_width);

		$(this)
			.data("is_animating", false)
			.data("item_width", item_width)
			.data("carousel_offset", 0)
			.data("carousel_length", carousel_length)
			.data("carousel_visible_items", carousel_visible_items);
	});

	// Tries to load first gallery image
	if ($("#galeriaNav #thumbsWrapper li:first").length > 0) {
		selectGalleryImg(0);
	}

	// Handles clicks on gallery items
	$("#galeriaNav #thumbsWrapper ul a").click(function(){
		var index = $("#galeriaNav #thumbsWrapper li").index($(this).parents("li"));

		selectGalleryImg(index);

		return false;
	});

	// Handles clicks on carousel nav
	$("#galeriaNav .carouselNav li a").click(function(){
		if(!$(this).parents(".carouselNav").data("is_animating")) {
			var selected = $(this).parents(".carouselNav").siblings(".carouselItems").find("li").index($(".active"));

			if($(this).parents("li").is(".ant") && !$(this).parents("li").is(".disabled")){
				if(selected > 0) {
					selectGalleryImg(selected-1);
				}
				scrollCarousel($(this).parents(".carouselNav"), "left");
			} else if (!$(this).parents("li").is(".disabled")) {
				if(selected < $(this).parents(".carouselNav").data("carousel_length")-1) {
					selectGalleryImg(selected+1);
				}
				scrollCarousel($(this).parents(".carouselNav"), "right");
			}
		}

		return false;
	});

	// Handles clicks on carousel hover nav
	$("#galeriaHoverNav a").click(function(){
		var carousel = $("#galeriaNav .carouselNav");

		if(!$(carousel).data("is_animating")) {
			var selected = $(carousel).siblings(".carouselItems").find("li").index($(".active"));

			if($(this).parents("li").is(".ant") && !$(this).parents("li").is(".disabled")){
				if(selected > 0) {
					selectGalleryImg(selected-1);
				}
				scrollCarousel($(carousel), "left");
			} else if (!$(this).parents("li").is(".disabled")) {
				if(selected < $(carousel).data("carousel_length")-1) {
					selectGalleryImg(selected+1);
				}
				scrollCarousel($(carousel), "right");
			}
		}

		return false;
	});

	// Handles clicks on carousel hover nav
	$("#galeriaImg")
		.live("mouseover", function(){
			$("#galeriaFoto").addClass("over");
		})
		.live("mouseout", function(){
			$("#galeriaFoto").removeClass("over");
		});

	function fixFooterLinks(){
		$("#contRodape li").each(function(){
			var width = $(this).width()+3;
			$(this).css({
				'width' : width
			});
		});
		$("#contRodape li").css("clear", "none");
	}

	function fixPhotoCredit(){
		$("#container .imgMateria").each(function(){
			if(navigator.userAgent.match(/Safari/i)) {
				$(this).find("img").load(function(){
					var width = $(this).width();
					$(this).siblings(".credito").css("width", width);
				});
			} else {
				var width = $(this).find("img").width();
				$(this).find(".credito").css("width", width);
			}
		});
	}

	var active_item = 0;
	var home_tv_length = $("#homeTv ol li").length;
	var home_tv_timeout;
	var home_tv_duration = 5000;

	function scrollHomeItems(item) {
		var item_length = $("#homeTv ol li").width();

		$("#homeTvNavSetas li").addClass("animating");
		$("#homeTvNavItems li").addClass("animating");

		clearInterval(home_tv_timeout);

		$("#homeTv ol").animate({ left : item_length*item*-1  }, 800,null,function(){
			active_item = item;

			$("#homeTvNavItems li").removeClass("active");
			$("#homeTvNavItems li:eq("+item+")").addClass("active");

			$("#homeTvNavSetas li").removeClass("disabled");
			if(active_item == 0) {
				$("#homeTvNavSetas li.ant").addClass("disabled");
			}
			if(active_item == home_tv_length-1) {
				$("#homeTvNavSetas li.prox").addClass("disabled");
			}

			$("#homeTvNavSetas li").removeClass("animating");
			$("#homeTvNavItems li").removeClass("animating");

			home_tv_timeout = setInterval(function(){
				if(active_item == home_tv_length-1) {
					scrollHomeItems(0);
				} else {
					scrollHomeItems(active_item+1);
				}
			}, home_tv_duration);
		});
	}

	function setupHomeTv() {
		$("#homeTvNavSetas li").click(function(){
			if($(this).is(".ant") && !$(this).is(".disabled") && !$(this).is(".animating")) {
				scrollHomeItems(active_item-1);
			} else if (!$(this).is(".disabled") && !$(this).is(".animating")) {
				scrollHomeItems(active_item+1);
			}
			return false;
		});

		$("#homeTvNavItems li").click(function(){
			if(!$(this).is(".active") && !$(this).is(".animating")) {
				scrollHomeItems($("#homeTvNavItems li").index(this));

				return false;
			}
		});

		home_tv_timeout = setInterval(function(){
			if(active_item == home_tv_length-1) {
				scrollHomeItems(0);
			} else {
				scrollHomeItems(active_item+1);
			}
		}, home_tv_duration);
	}

	$("#homeBusca li strong").click(function(){
		$("#homeBusca ul > li").removeClass("active");
		$(this).parents("li").addClass("active");
	});

	setupHomeTv();

	// Internet Explorer naughty tricks
	var ua = navigator.userAgent;

	if(ua.match(/msie (\d+)/i)) {
		$("#navConteudo .selecionada").append("<span></span>");
	}

	fixFooterLinks();
	fixPhotoCredit();

	$('#botaoTooltip').hover(
		function(){
			$('#tooltipTags').show();
		},
		function(){
			$('#tooltipTags').hide();
		}
	);

	// Scroll Navigation Guia 10 mais, Melhor da Semana
	$("#guia10maisNav .carouselNav li a, #melhorSemanaNav .carouselNav li a").click(function(){
		var item = $(this).parents(".carouselNav");

		if(!$(item).data("is_animating")) {
			if($(this).parents("li").is(".ant") && !$(this).parents("li").is(".disabled")){
				scrollCarousel($(item), "left");
			} else if (!$(this).parents("li").is(".disabled")) {
				scrollCarousel($(item), "right");
			}
		}
		// fix to melhor da semana
		var carousel_visible_items = "";
		if ($(item).parent(".carousel").is("#melhorSemanaNav")) {
			carousel_visible_items = $(item).data("carousel_visible_items")-2;
		} else {
			carousel_visible_items = $(item).data("carousel_visible_items")-1;
			// fix to guia 10 mais left component
			if($(".categoriasWrapper").width() <= 210) {
				carousel_visible_items = $(item).data("carousel_visible_items")+1;
			}
		}
		// disabled nav ant
		if($(item).data("carousel_offset") == 0) {
			$(item).find("li.ant").addClass("disabled");
			$(item).find("li.ant").addClass("disabled");
		} else { $(item).find("li.ant").removeClass("disabled"); }
		// disabled nav prox
		if($(item).data("carousel_offset") == carousel_visible_items) {
			$(item).find("li.prox").addClass("disabled");
			$(item).find("li.prox").addClass("disabled");
		} else { $(item).find("li.prox").removeClass("disabled"); }

		return false;
	});

	// Clear input on focus
	var clearMePrevious = '';
	$('.clearMeFocus').focus(function() {
		if($(this).val() == $(this).attr('title')){
			clearMePrevious = $(this).val();
			$(this).val('');
		}
	});
	$('.clearMeFocus').blur(function() {
		if($(this).val() == '') {
			$(this).val(clearMePrevious);
		}
	});

	// Combo Revistas regionais
	$('#jumpCidades').change(function(){
		window.open($(this).val());
		return false;
	});

	// Limita o numero de Caracteres Comentario
	function limitChars(txt, limit) {
		var text = $('#'+ txt).val();
		var textlength = text.length;
		if(textlength > limit) {
			$("#numCaracteres").css('color','red');
			$('#'+ txt).val(text.substr(0,limit));
			return false;
		} else {
			$("#numCaracteres").css('color','');
			$("#numCaracteres span").text( (limit - textlength) );
			return true;
		}		
	}
	var limit = eval($("#numCaracteres span").text())
	$('#comment').keyup(function() {
		limitChars('comment', limit);
	});
	
	// Modal de Votação
	$('a.modal').click(function(e){
		e.preventDefault();
		
		//manipula o form de votação
		$("input:checked").removeAttr('checked');
		
		if($(this).hasClass('gostei')){
			$('#votoGostei').attr('checked','checked');
			$('#fieldGostei').show();
			$('#fieldNaoGostei').hide();
		}else	if($(this).hasClass('naoGostei')){
			$('#votoNaoGostei').attr('checked','checked');
			$('#fieldGostei').hide();
			$('#fieldNaoGostei').show();
		}
		
		$('#votoGostei').click(function(){
			$('#fieldGostei').show();
			$('#fieldNaoGostei').hide();
		});
		
		$('#votoNaoGostei').click(function(){
			$('#fieldGostei').hide();
			$('#fieldNaoGostei').show();
		});
		
		var ua = navigator.userAgent;

		if(ua.match(/msie 6.0/i)) {
			var w_width = $(document).width()-17;
		}else	if(ua.match(/msie 8.0/i)) {
			var w_width = $(document).width()-21;
		}else{
			var w_width = $(document).width();
		}
		
		var w_height = $(document).height();
		
		var modal = '<div id="modal"></div>';
		
		var modal_css = {
			'position' : 'absolute',
			'width' : w_width+'px',
			'height' : w_height+'px',
			'top' : 0,
			'left' : 0,
			'background' : '#000',
			'opacity' : '0.45',
			'filter' : 'alpha(opacity=45)',
			'display' : 'none',
			'z-index' : '9000'
		};
		
		$('body').append(modal);
		$('#modal').css(modal_css).fadeIn('fast', function(){
			$('#modalWindow').fadeIn('fast');
			$('#modalContent').fadeIn('fast');
		});
		$('.fecharModal, #btnCancelar').click(function(e){
			e.preventDefault();
			$('#modalContent').fadeOut('fast');
			$('#modalWindow').fadeOut('fast', function(){
				$('#modal').fadeOut('slow');
			});
		});
		
	});
	
	// Modal Exclusao de Comentario e Denuncia
	addBehaviorForModalExclusao();
	
	// Modal Denuncia
	addBehaviorForModalDenuncia();

});

function addBehaviorForModalExclusao() {

	$('a.icoExcluir').click(function(e){
		e.preventDefault();
		$("#commentIdExcluir").val($(this).attr('rel'));
		
		var ua = navigator.userAgent;

		if(ua.match(/msie 6.0/i)) {
			var w_width = $(document).width()-17;
		}else	if(ua.match(/msie 8.0/i)) {
			var w_width = $(document).width()-21;
		}else{
			var w_width = $(document).width();
		}
		
		var w_height = $(document).height();
		
		var modal = '<div id="modal"></div>';
		
		var modal_css = {
			'position' : 'absolute',
			'width' : w_width+'px',
			'height' : w_height+'px',
			'top' : 0,
			'left' : 0,
			'background' : '#000',
			'opacity' : '0.45',
			'filter' : 'alpha(opacity=45)',
			'display' : 'none',
			'z-index' : '9000'
		};
		
		$('body').append(modal);
		$('#modal').css(modal_css).fadeIn('fast', function(){
			$('div.modalWindow').fadeIn('fast');
			$('div.modalContent').fadeIn('fast');
		});
		$('div.modalExcluir .fecharModal, div.modalExcluir .bt_cancelar').click(function(e){
			e.preventDefault();
			$('div.modalContent').fadeOut('fast');
			$('div.modalWindow').fadeOut('fast', function(){
				$('#modal').fadeOut('slow');
			});
		});

	});
}

function addBehaviorForModalDenuncia() {
	$('a.icoDenuncia').click(function(e){
		e.preventDefault();
		$("#commentIdDenuncia").val($(this).attr('rel'));
		
		var ua = navigator.userAgent;

		if(ua.match(/msie 6.0/i)) {
			var w_width = $(document).width()-17;
		}else	if(ua.match(/msie 8.0/i)) {
			var w_width = $(document).width()-21;
		}else{
			var w_width = $(document).width();
		}
		
		var w_height = $(document).height();
		
		var modal = '<div id="modal"></div>';
		
		var modal_css = {
			'position' : 'absolute',
			'width' : w_width+'px',
			'height' : w_height+'px',
			'top' : 0,
			'left' : 0,
			'background' : '#000',
			'opacity' : '0.45',
			'filter' : 'alpha(opacity=45)',
			'display' : 'none',
			'z-index' : '9000'
		};
		
		$('body').append(modal);
		$('#modal').css(modal_css).fadeIn('fast', function(){
			$('#modalDenuncia').fadeIn('fast');
		});
		$('#modalDenuncia .fecharModal, #modalDenuncia .bt_cancelar').click(function(e){
			e.preventDefault();
			$('#modalDenuncia').fadeOut('fast', function(){
				$('#modal').fadeOut('fast');
			});
		});
	});
}

errorReport = function(){
  var url = "/reportar-erro?return_to=" + document.location.pathname.replace(/^[\/]/,'');  
  document.location = url;
}

