//Crea el blackout y el tooltip del deportista

function shortComments() {
	$('#np_comments_list ol li').each(function(){
		var para = $(this).find('p');
		var altura = $(this).height();
		//var css = ({'position' : 'absolute', 'bottom' : '0', 'right': '0px', 'display' : 'block', 'width' : '100%', 'background' : 'white', 'color' : 'blue',
		//	'text-align' : 'right', 'font-size' : '11px'
		//});
		if ( altura >= 100 ){
			$(this).css('height', '100px');
			$(this).append('<a href="#" title="Ver todo el comentario" class="view_more_comment">leer todo</a>');
			//$(this).find('.view_more_comment').css(css);
		}
	});
}

function alto_comentario(){
	var alto_container = $('#np_content').height();
		if (alto_container > 4000){
			alto = parseInt(3500 - $('.np_new_content').height());
			$('#np_comments_list').css({'overflow-y':'auto', 'height': alto});
			//alert('te pasaaaaaste');
		}
}

function append_sports(item){
	var single_name = item.find('img').attr('alt'); //rescata el nombre del deportista
	var link = item.attr('href'); //obtiene el link a la página del deportista
	if ( $(item+' .blackout').is(':visible') != true ){
		/* item.append('<span class="blackout"></span>'); */ //Opción con blackout
		item.append('<span class="tooltip_sports"><a href="'+link+'" title="Ver más">'+single_name+'</a></span>'); //agrega el tooltip con el nombre y link
		var pos = item.parent('li').position(); //obtiene la posicion de la foto del deportista
		var get_width = item.parent('li').width(); //obtiene el ancho de la foto
		var width = parseInt(pos.left)+parseInt(get_width); //resultado de posicion + ancho
		var width_tool = item.find('.tooltip_sports').width(); //obtiene el ancho del tooltip
		var pos_ul = $(item).parent('li').parent('ul').position(); //
		var lapos = parseInt(pos_ul.left);
		if (width_tool > width+(lapos)){ //si la posicion de la foto está de las primeras...
			item.find('.tooltip_sports').addClass('toolinvert'); //entonces agregar clase
		}
		var get_height = item.children('.tooltip_sports').find('a'); 
		var height = get_height.height(); //obtiene el alto del nombre del deportista
		if (height > 20){ //si es muy largo...
			item.find('.tooltip_sports').css({'line-height':'15px'}); //acorta las lineas
			item.find('.tooltip_sports a').css({'margin-top':'2px', 'display':'inline-block'});
		}
	}
}
//Funcion para carrusel de gente meds
function boxsports_initCallback(carousel) {
	jQuery('#sports_box_ctrl .np_rarrow').click(function() {
		carousel.next();
		//alert('works avanzar');
		return false;
	});

	jQuery('#sports_box_ctrl .np_larrow').click(function() {
		carousel.prev();
		//alert('works');
		return false;
	});
	carousel.clip.hover(function() {
		carousel.stopAuto();
	}, function() {
		carousel.startAuto();
	});
	$('.empty').removeAttr('class').removeAttr('jcarouselindex').addClass('empty');

};

//Funcion para carrusel de gente meds
function mainsports_initCallback(carousel) {
	jQuery('#sports_main_ctrl .np_rarrow').click(function() {
		carousel.next();
		return false;
	});

	jQuery('#sports_main_ctrl .np_larrow').click(function() {
		carousel.prev();
		return false;
	});
	carousel.clip.hover(function() {
		carousel.stopAuto();
	}, function() {
		carousel.startAuto();
	});

};

//carrusel de videos del sidebar
function videos_carousel_initCallback(carousel) {
	jQuery('#videos_side_ctrl .np_rarrow').click(function() {
		carousel.next();
		//alert('ok');
		return false;
	});

	jQuery('#videos_side_ctrl .np_larrow').click(function() {
		carousel.prev();
		return false;
	});
	carousel.clip.hover(function() {
		carousel.stopAuto();
	}, function() {
		carousel.startAuto();
	});

};

//Elimina el tooltip y el blackout
function remove_append(item){
	//item.find('.tooltip_sports, .blackout').remove();
	item.find('.tooltip_sports').remove();
}

var cant_click_video = 8;
$(document).ready(function(){
	
	//Para borrar... solo muestra de botones current
	$('.np_menu_tabs li:last').addClass('current');
	$('.np_menu_tabs li a').click(function(e){
		e.preventDefault();
		$('.np_menu_tabs li').removeClass('current');
		$(this).parent().addClass('current');	
	});
	//hover de articulos mas valorados
	$('.np_articles_widget_list h3 a, .np_articles_related_list h3 a').mouseenter(function(){
		$(this).parent().parent().find('.black_screen').hide();
		$(this).parent().find('a').css('color', '#606');
	}).mouseleave(function(){
		$(this).parent().parent().find('.black_screen').show();
		$(this).parent().find('a').css('color', '#000');
	});
	$('.np_articles_widget_list > li > a, .np_articles_related_list > li > a').mouseenter(function(){
		$(this).find('.black_screen').hide();
		$(this).parent().find('a').css('color', '#606');
	}).mouseleave(function(){
		$(this).find('.black_screen').show();
		$(this).parent().find('a').css('color', '#000');
	});
	//calendario
	$('#np_schedule_list li:even').addClass('odd');
	
	//Al posarse encima, crea el tooltip y la cortina negra
	$('.sports_act li a.person').mouseenter(function(){
		append_sports($(this));
	}).mouseleave(function(){
		remove_append($(this));
	});
	if ( $('#np_content').find('.gente_meds_cont')){
		$('#np_content').css('padding-bottom','0px');
	}
	
	//Galería de videos del sidebar
	$('.np_list_videos li a').click(function(){
		var loader = '/img/ajax-loader.gif';
		var visor = $('.np_video_visor');
		var get_link_iframe = $(this).attr('href').split('/');
		get_link_iframe = get_link_iframe[1];
		var info_video = $(this).attr('rel').split('|');
		if(info_video[2] == 0){
			var iframe = '<object width="230" height="160">'+
						'<param value="http://www.youtube.com/v/'+get_link_iframe+'?version=3&amp;hl=es_ES&amp;rel=0" name="movie">'+
						'<param value="transparent" name="wmode">'+
						'<param value="true" name="allowFullScreen"><param value="always" name="allowscriptaccess">'+
						'<embed width="230" height="160" allowfullscreen="true" allowscriptaccess="always" wmode="transparent" type="application/x-shockwave-flash" src="http://www.youtube.com/v/'+get_link_iframe+'?version=3&amp;hl=es_ES&amp;rel=0">'+
				'</object>';
		}else{
			var iframe = '<object width="230" height="160">'+
						'<param name="allowfullscreen" value="true" />'+
						'<param name="allowscriptaccess" value="always" />'+
						'<param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=8269311&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=00adef&amp;fullscreen=1" />'+
						'<embed src="http://vimeo.com/moogaloop.swf?clip_id='+get_link_iframe+';?>&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=00adef&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="230" height="160">'+
						'</embed>'+
				'</object>'
		}
		//var iframe = '<iframe width="230" height="160" src="'+get_link_iframe+'" frameborder="0" allowfullscreen></iframe>'
		visor.html('<img class="video_loader" src="'+loader+'" alt="Cargando" />');
		setTimeout(function(){
			$('.np_widget_inside').children('h4').html(info_video[0]);
			$('.np_widget_inside').children('p').html(info_video[1]);
			visor.html(iframe);
		}, 700);
		return false;
	});
	//Puntuacion de noticias
	$('.item_marking_slot').mouseenter(function(){
		var parent = $(this).parent();
		if (parent.hasClass('none')){
			$(this).addClass('current');
			$('.current').prevAll().addClass('current');
			$(this).nextAll().removeClass('current');
		}
	}).click(function(){
		var parent = $(this).parent();
		if (parent.hasClass('none')){
			$(this).addClass('current');
			$('.current').prevAll().addClass('current');
			$(this).nextAll().removeClass('current');
			parent.removeClass('none');
			var rel = $(this).attr('rel');
			var news_id = $('#NewsId').val();
			//console.log(news_id);
			$.ajax({
				url: '/news/save_calification/'+news_id+'/'+rel,
				data: '',
				success: function(html){
					parent.append('<strong style="margin-left:5px;color:#0c0; font-size:11px;">Haz calificado esta noticia</strong>');
				}
			});
			//parent.append('<strong style="margin-left:5px;color:#0c0; font-size:11px;">Haz calificado esta noticia</strong>');
			setTimeout(function(){
				parent.find('strong').fadeOut(300, function(){
					$(this).remove();
				});
			}, 2000);
		}
	});
	$('.item_marking').mouseleave(function(){
		if ( $(this).hasClass('none') ){
			$('.item_marking_slot').removeClass('current');
		}
	});
	
	//Caja de comentarios
	var show_comment = 'Ver todos <img src="/img/articles_layout/down_arrow.png" alt="Mostrar" />';
	var hide_comment = 'Ocultar todos <img src="/img/articles_layout/up_arrow.png" alt="Ocultar" />';
	var comments_list = $('#np_comments_list');
	
	shortComments();
	
	$('.view_more_comment').live('click', function(e){
		e.preventDefault();
		$(this).parent().height('auto');
		$(this).remove();
		alto_comentario();
	});
	
	comments_list.hide();
	$('.np_show_all a').live('click', function(e){
		e.preventDefault();
		
		alto_comentario();
		
		if ($(this).hasClass('np_cshow')){
			$(this).removeClass('np_cshow').addClass('np_chide');
			$(this).attr('title','Ocultar');
			$(this).html(hide_comment);
			comments_list.slideDown(300);
		}else{
			$(this).removeClass('np_chide').addClass('np_cshow');
			$(this).attr('title','Mostrar');
			$(this).html(show_comment);
			comments_list.slideUp(300);
		}
	});
	var comment_form = $('.np_comments_form');
	$('.np_login_comment').live('click', function(e){
		e.preventDefault();
		comment_form.slideToggle(300);
	});
	
	$('.register_comment').click(function(e){
		e.preventDefault();
		$('.commentDialog').dialog({
			modal: true,
			open: function ()
			{
				$(this).load('/users/users/register_ajax');
			},         
			height: 350,
			width: 750,
			title: 'Agregar Usuario',
			buttons: {
				"Guardar": function() {
					$.ajax({
						type: 'POST',
						url: '/users/users/register_ajax',
						data: $('#UserRegisterAjaxForm').serialize(),
						beforeSend: function(){
							$('.preload').show();
						},
						success: function(html) {
							//console.log(html);
							parseInt(html);
							if(isNaN(html)){
								$('.commentDialog').html(html);
								$('.commentDialog').dialog('open');
							}else{
								$('.commentDialog').dialog('close');
							}
						}
					});
				}
			}
		});
	});
	$('.loginUser').click(function(e){
		$.ajax({
			type: 'POST',
			url: '/admin/login',
			data: $('.UserComment').serialize(),
			beforeSend: function(){
				$('.preload').show();
			},
			success: function(html) {
				$('.np_result_ajax').html(html);
			}
		});
		e.preventDefault();
	});
	$('.submitComment').click(function(e){
		$.ajax({
			type: 'POST',
			url: '/comments/add',
			data: $('.UserComment').serialize(),
			beforeSend: function(){
				$('.preload').show();
			},
			success: function(html) {
				$.ajax({
					url: '/comments/get_container_comments/'+$('#CommentNewsId').val(),
					data: '',
					beforeSend: function(){
						$('.preload').show();
					},
					success: function(html) {
						$('.np_comments_full').html(html);
						shortComments();
						alto_comentario();
					}
				})
				//$('.np_result_ajax').html(html);
				$('#np_ccomment').val('');
				$('.np_comments_form').hide();
			}
		});
		e.preventDefault();
	});
	
	$('.deleteComment').live('click', function(e){
		e.preventDefault();
		if(confirm("Esta seguro de eliminar este comentario?")){
			var rel = $(this).attr('rel');
			$.ajax({
				url: '/comments/delete/'+rel,
				data: '',
				success: function(html){
				}
			});
			//cant_comments = $('.cantComments').attr('rel')-1;
			cant_comments = parseInt($('.cantComments').text());
			text_final = (cant_comments-1);
			$('.cantComments').html(text_final);
			$(this).parent().parent().remove();
		}
	})
	
	var carousel_ul = $('#box_sports_list_container'); //obtiene el carrusel chico de gente meds
	if ( carousel_ul.hasClass('two_lines') == false ){ //si NO tiene la clase para 2 lineas...
		$('#box_sports_list_container').css('height', '112px'); //acorta la altura a una línea
	}
	
	
	
	//Noticias destacadas
	$("#box_sports_list_container.two_lines").jcarousel({
		scroll: 5,
		wrap: 'last',
		animation: 300,
		initCallback: boxsports_initCallback
	});
	
	$("#box_sports_list_container.max_lines").jcarousel({
		scroll: 5,
		wrap: 'last',
		animation: 300,
		initCallback: boxsports_initCallback
	});

	$("#box_sports_list_container.one_line").jcarousel({
		scroll: 5,
		wrap: 'last',
		animation: 300,
		initCallback: boxsports_initCallback
	});
	
	$("#main_sports_list_container").jcarousel({
		scroll: 5,
		//size: cantidad_big,
		wrap: 'last',
		animation: 300,
		initCallback: mainsports_initCallback
	});
	
	$(".np_list_videos_container").jcarousel({
		scroll: 1,
		wrap: 'last',
		animation: 300,
		initCallback: videos_carousel_initCallback
	});
	/* reemplazado por carrusel
	$('.page_news').live('click', function(e){
		$('.page_news').parent().removeClass("current_pag");
		$(this).parent().addClass("current_pag");
		var rel = $(this).attr('rel');
		$('.newsFront').hide();
		var loader = '/img/ajax-loader.gif';
		var imagen = '<img class="video_loader" src="'+loader+'" alt="Cargando" />';
		$('.ajaxLoader').html(imagen);
		$('.np_breadcrumb_home').hide();
		setTimeout(function(){
			$('.ajaxLoader').html('');
			$('.newsPP'+rel).show();
		}, 800);
		e.preventDefault();
	});
	*/

	
	/*Carrusel*/
	
		$("#np_news_current_issues #carHomeNews, #np_lastest_news_sport #carHomeNews").jcarousel({
			scroll: 1,
			wrap: 'last',
			animation: 700,
			auto: cant_click_video,
			initCallback: news_carousel_initCallback,
			itemVisibleInCallback: {
				onBeforeAnimation: function(asdf, asdf1){
					var currentItem = jQuery(asdf1).attr('jcarouselindex');
					jQuery('.np_paginator_news_home li').removeClass('current_pag');
					jQuery('.np_paginator_news_home li a[rel="'+currentItem+'"]').parent().addClass('current_pag');
				}
			}
		});
	
	
	$('.viewVideo').live('click', function(e){
		e.preventDefault();
		var info = $(this).attr('rel').split('|');
		$('.titleNewsVideo').html(info[1]);
		$('.video_description').html(info[2]);
		if(info[0] == 1){
			$('.videoEmbed').html(
				"<object width='400' height='250'>"+
					"<param name='allowfullscreen' value='true' />"+
					"<param name='allowscriptaccess' value='always' />"+
					"<param name='movie' value='http://vimeo.com/moogaloop.swf?clip_id=8269311&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=00adef&amp;fullscreen=1' />"+
					"<embed src='http://vimeo.com/moogaloop.swf?clip_id="+info[3]+"&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=00adef&amp;fullscreen=1' type='application/x-shockwave-flash' allowfullscreen='true' allowscriptaccess='always' width='400' height='250'>"+
					"</embed>"+
				"</object>"
			);
		}else{
			$('.videoEmbed').html(
				"<object width='400' height='250'>"+
					"<param name='movie' value='http://www.youtube.com/v/"+info[3]+"?version=3&amp;hl=es_ES'></param>"+
					"<param name='allowFullScreen' value='true'></param>"+
					"<param name='allowscriptaccess' value='always'></param>"+
					"<embed src='http://www.youtube.com/v/"+info[3]+"?version=3&amp;hl=es_ES' wmode='transparent' type='application/x-shockwave-flash' width='400' height='250' allowscriptaccess='always' allowfullscreen='true'></embed>"+
				"</object>"
			);
		}
	});
	$('.GoToPage').live('click', function(){
		//e.preventDefault();
		var go = $(this).text();
		$('.contentPages').fadeOut(290);
		$('.currentPage'+go).delay(300).fadeIn();
		$('.GoToPage').parent().removeClass('current');
		$(this).parent().addClass('current');
	});
	
	
	$('.image_sport').hover(
		function(){
			var relHover = $(this).attr('rel');
			if(relHover != ""){
				$(this).attr('rel', $(this).attr('src'));	
				$(this).attr('src', relHover);
			}
		},
		function(){
			var relOriginal = $(this).attr('rel');
			if(relOriginal != ""){
				$(this).attr('rel', $(this).attr('src'));
				$(this).attr('src', relOriginal);
			}
		}
	);
	
	$('.politicsOfUsage').live('click', function(e){
		e.preventDefault();
		$('.politicsOfUsageContent').dialog({
			height: 500,
			width: 750/*,
			title: 'Terminos y Condiciones de Uso'*/
		});
	});
	
	$('.linkNews').click(function(e){
		//e.preventDefault();
		var rel = $(this).attr('rel');
		$.ajax({
			type: 'POST',
			url: '/sports/peoples/get_news/'+rel,
			data: '',
			beforeSend:function(){
				$('.ajaxLoader').show();
			},
			success: function(html){
				$('.np_new_content').html(html);
				$.ajax({
					url: '/sports/peoples/get_newstags/'+rel,
					data: '',
					beforeSend:function(){
						$('.ajaxLoader').show();
					},
					success: function(html){
						$('#np_related_articles').html(html);
					}
				});
			}
		});
	});

	$('.articulo').click(function(e){
		$('.share_button_news').show();
		$('.latest_rel_articles').show();
		$('.np_new_content').show();
		$('.fichaPeople').html('');
		$('.galleryPeople').html('');
	});
	
	//$('.readMoreNews').click(function(e){
	//	e.preventDefault();
	//	$('.hideLi').fadeIn();
	//	$(this).children('img').attr('src', '/img/articles_layout/up_arrow.png');
	//	$(this).text('Ocultar ');
	//});
	$('.readMoreNews a').click(function(e){
		e.preventDefault();
		
		alto_comentario();
		
		if ($(this).hasClass('np_cshow')){
			$(this).removeClass('np_cshow').addClass('np_chide');
			$(this).attr('title','Ocultar');
			$(this).html(hide_comment);
			$('.hideLi').slideDown(300);
		}else{
			$(this).removeClass('np_chide').addClass('np_cshow');
			$(this).attr('title','Mostrar');
			$(this).html(show_comment);
			$('.hideLi').slideUp(300);
		}
	});
	var breadcrumb = $('.np_breadcrumb.posabstit');
	if ( breadcrumb.height() > 12 && breadcrumb.height() <= 23 ){
		breadcrumb.css('top','-27px')
	}else if ( breadcrumb.height() > 23 ){
		breadcrumb.css('top','-41px')
	}
	$('#issues_left .left:last').addClass('ultimo');
	/* mostrar noticias del listado*/
	var cant_click = 0;
	$('.showMoreCurrentIssues a').click(function(e){
		e.preventDefault();
	//	if ( $('.ultimo').is(':hidden') ){
	//		cant_click++;
	//		console.log(cant_click);
	//		var next_click = cant_click+1;
	//		$('.block_news_'+cant_click).nextUntil('.block_news_'+next_click).show();
	//		$('.block_news_'+next_click).show();
	//		return true;
	//	}
	//	return false;
	});

	var showMoreCurrentIssues = $('.showMoreCurrentIssues');
	var contScroll = 0;
	$(window).scroll(function () {
		if (isScrolledIntoView(showMoreCurrentIssues) && contScroll == 0){
			contScroll = 1;
			if ( contScroll == 1){
				contScroll++;
				if ( $('.ultimo').is(':hidden') ){
					setTimeout(function(){
						$('.showMoreCurrentIssues a').html('cargando...');
					}, 1000);
				}
				setTimeout(function(){
					if ( $('.ultimo').is(':hidden') ){
						cant_click++;
						var next_click = cant_click+1;
						$('.block_news_'+cant_click).nextUntil('.block_news_'+next_click).fadeIn(700);
						$('.block_news_'+next_click).show();
						contScroll = 0;
					}
					$('.showMoreCurrentIssues a').html('más <img src="/img/articles_layout/down_arrow.png" alt="Ver mas" />');
				}, 3000);
			}
		}
	});
	
	$('.send_friend').click(function(e){
		e.preventDefault();
		var news_id = $('#news_id').val();
		$('.dialogFiend').dialog({
			modal: true,
			height: 500,
			width: 750,
			open: function ()
			{
				$(this).load('/send_friends/add/'+news_id);
			},         
			title: 'Enviar a un amigo',
			buttons: {
				"Enviar": function() {
					$.ajax({
						type: 'POST',
						url: '/send_friends/add/'+news_id,
						data: $('#SendFriendAddForm').serialize(),
						beforeSend: function(){
							$('.preload').show();
						},
						success: function(html) {
							if(html == "El envio ha sido exitoso."){
								$('.dialogFiend').html(html);
								setTimeout(function(){
									$('.dialogFiend').dialog("destroy");
								}, 2000);
							}else{
								$('.dialogFiend').html(html);
							}
						}
					});
				}
			}
		});
	});
});

var cantVideos = 0;


function news_carousel_initCallback(carousel) {
	
	
		
	jQuery('.np_paginator_news_home li a').click(function(e) {
		e.preventDefault();
		var thisRel = jQuery(this).attr('rel');
		//console.log(cant_click_video);
		//if($('newsPP'+thisRel).children('object').length){
		//	cantVideos++;
		//}
		//console.log(cantVideos);
		carousel.startAuto();
		carousel.scroll(jQuery.jcarousel.intval(thisRel));
		return false;
	});
	
	jQuery('.yt_img').click(function() {
		carousel.stopAuto();
		return false;
	});
	

	//jQuery('#sports_list_ctrl .np_larrow').click(function() {
		//carousel.prev();
		//return false;
	//});
	//carousel.clip.hover(function() {
		//carousel.stopAuto();
	//}, function() {
		//carousel.startAuto();
	//});

};

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}
