// ********************
// Funciones Menú
// ********************

var timeout     = 300;
var closetimer	= 0;
var menu      	= 0;
var item      	= 0;

function jsddm_open(){

	jsddm_canceltimer();
	jsddm_close();
	item = $(this).not('.bot').addClass('abierto');
	menu = $(this).find('ul').eq(0).css('display', 'inherit');
}

function jsddm_close(){

	if(menu) {	menu.css('display', 'none'); }
	if(item) {	item.removeClass('abierto'); }

}

function jsddm_timer(){

	closetimer = window.setTimeout(jsddm_close, timeout);
}

function jsddm_canceltimer(){

	if(closetimer){

		window.clearTimeout(closetimer);
		closetimer = null;
	}
}

// ********************
// Funciones Rand
// ********************
(function($){
    $.fn.rand = function(k){
        var b = this,
            n = b.size(),k = k ? parseInt(k) : 1;
 
        // Special cases
        if (k > n) return b.pushStack(b);
        else if (k == 1) return b.filter(":eq("
                + Math.floor(Math.random()*n) + ")");
 
        // Create a randomized copy of the set of elements,
        // using Fisher-Yates sorting
        r = b.get();
        for (var i = 0; i < n - 1; i++) {
            var swap = Math.floor(Math.random() * (n - i)) + i;
            r[swap] = r.splice(i, 1, r[swap])[0];
        }
        r = r.slice(0, k);
 
        // Finally, filter jQuery stack
        return b.filter(function(i){
            return $.inArray(b.get(i), r) > -1;
        });
    };
})(jQuery);


// **************************************
// Limitador de caracteres para el campos
// **************************************

function limitChars(textid, limit, continuar){

	var text = textid.val();
	var textlength = text.length;
	var info = textid.parent().find('.caracteres_disponibles');

	if(textlength > limit)
	{
		info.html(limit - textlength).addClass('no');
		if(continuar === false){
			textid.val(text.substr(0,limit));
		}
		return false;
	}
	else
	{
		info.html(limit - textlength).removeClass('no');
		return true;
	}
}

// ****************************
// Tips para votos
// ****************************

	function qtipVoto(objeto){

		// Para Voto
		objeto.qtip({ 
			content: objeto.hasClass('no') ? 'Ya no me gusta':'Me gusta',
			position: { corner: { target: 'topLeft', tooltip: 'bottomLeft' }, adjust: { x: 22, y: 4 }},
			style: { tip: 'bottomLeft', name: 'mystyle' }
		});
	}

// ****************************
// Tips para seguir
// ****************************

	function qtipSeguir(objeto){

		var seg = objeto.attr('rel').split('-');

		// Para Voto
		objeto.qtip({ 
			content: objeto.hasClass('no') ? 'Dejar de seguir a ' + seg[2] :'Seguir a ' + seg[2],
			position: { corner: { target: 'topLeft', tooltip: 'bottomLeft' }, adjust: { x: 22, y: 4 }},
			style: { tip: 'bottomLeft', name: 'mystyle' }
		});
	}

// ****************************
// Funcion para incorporar Facebox
// ****************************

	function bindFacebox(){

		$("a[rel*=facebox]").facebox({});
	}

// ****************************
// Funcion para Seguir Perfiles
// ****************************

	function bindSeguir(){
	
		$('.seguir').each(function() {
			
			$(this).unbind();

			var vid = $(this).attr('rel');
			var vid_array = vid.split('-');
			
			if(vid_array[0] == 'o'){
				registraSeguidor(trigger,vid,vid_array[0],vid_array[1]);
			}
			registraSeguidor($(this),vid,vid_array[0],vid_array[1]);

			qtipSeguir($(this));
			
		});
	}	

// ****************************
// Funcion para Votar Artículos
// ****************************

	function bindVotos(){
	
		$('.voto, .votos_listado').each(function() {
			
			$(this).unbind();
			
			var vid = $(this).attr('rel');
			var vid_array = vid.split('-');
			
			if(vid_array[0] == 'o'){
				var trigger = $(this).parents('li').find('a.op-gusta');
				registraVoto(trigger,vid,vid_array[0],vid_array[1],vid_array[2]);
			}
			registraVoto($(this),vid,vid_array[0],vid_array[1],vid_array[2]);

			qtipVoto($(this));
			
		});
	}	

// ****************************
// Funcion para Registrar Voto
// ****************************

	function registraVoto(trigger,target,tipo,id,usuario){

		trigger.click(function(){

			var seleccion = $('a.voto[rel="' + target + '"]');

			if(usuario){

			seleccion.find("span").html('<img class="spinner" src="/imagenes/layout/spinner_rojo.gif">');
	
				$.ajax({
					type: "POST",
					data: { 'action':'voto', 'tipo': tipo, 'id': id, 'usuario': usuario },
					url: "/includes/vistas/articulos/texto_votos.php",
					success: function(msg)
					{
						seleccion.find("span").html(msg);
						seleccion.find("span").fadeOut("fast");
						seleccion.find("span").fadeIn("fast");
						seleccion.toggleClass('no');
			   			seleccion.qtip('destroy');
						qtipVoto(seleccion);
					}
				});

			} else {
			
				$.facebox({ajax:'/acceso/opciones/popup'});
			}

		});
	}

// *******************************
// Funcion para Registrar Seguidor
// *******************************

	function registraSeguidor(trigger,target,seguidor,seguido){

		trigger.click(function(){

			var seleccion = $('a.seguir[rel="' + target + '"]');

			if(seguidor){

			seleccion.find("span").html('<img class="spinner" src="/imagenes/layout/spinner_rojo.gif">');
	
				$.ajax({
					type: "POST",
					data: { 'action':'seguir', 'seguidor': seguidor, 'seguido': seguido },
					url: "/perfiles/seguir/perfil",
					success: function(msg)
					{
						seleccion.find("span").html(msg);
						seleccion.find("span").fadeOut("fast");
						seleccion.find("span").fadeIn("fast");
						seleccion.toggleClass('no');
			   			seleccion.qtip('destroy');
						qtipSeguir(seleccion);
					}
				});

			} else {
			
				$.facebox({ajax:'/acceso/opciones/popup'});
			}

		});
	}
	
// ********************
// ejecutamos varios
// ********************
$(document).ready(function($) {

	// Menú
	$('#menu > li').bind('mouseover', jsddm_open);
	$('#menu > li').bind('mouseout',  jsddm_timer);
//	document.onclick = jsddm_close;

	// Contamos la cantidad de links a ocultar
	var enlaces = 0;
	$('a.unlink').each(function() {
		enlaces = enlaces + 1;
	});
	
	// Bloqueo de links para usuario no logeado
	$('a.unlink').rand(enlaces*.7).attr("href", "javascript:jQuery.facebox({ajax:'/acceso/opciones/popup'});")

	// Facebox
	bindFacebox();

	// Estilo del tooltip tipo
	$.fn.qtip.styles.mystyle = {
	  padding: 0,
	  background: '#DEE300',
	  color: 'black',
	  textAlign: 'center',
	  border: {
	     width: 8,
	     radius: 8,
	     color: '#DEE300'
	  }
	}
	// Para Caras Autores en Páginas de Contenidos
	$('.retrato_autor[title], .logo_estudio[title]').qtip({ 
	position: {
	  corner: {
	     target: 'topMiddle',
	     tooltip: 'bottomMiddle'
	  }
	},
	style: {
		  tip: 'bottomMiddle',
		  name: 'mystyle'
		  },
	show: {
		  effect: { length: 300 }  
		  }
	});
	// Para banderines home
	$('.listado_articulos h2 strong[title]').qtip({ 
	position: {
	  corner: {
	     target: 'topCenter',
	     tooltip: 'bottomCenter'
	  }
	},
	style: {
	  tip: 'bottomLeft',
		  name: 'mystyle'
	},
	show: {
		  effect: { length: 300 }  
		  }
	});
	// Para banderines listados
	$('.listado_articulos div[title]').qtip({ 
	position: {
	  corner: {
	     target: 'bottomLeft',
	     tooltip: 'topRight'
	  },
	  adjust: { 
	     x: 26, 
	     y: -26 
	  }
	},
	style: {
	  tip: 'topRight',
		  name: 'mystyle'
	},
	show: {
		  effect: { length: 300 }  
		  }
	});
	// Para Artículos del autor y cuadro de precios (explicación de moneda)
	$('.listado_articulos .del_autor a[title], form.cuadro_precios td.right[title]').qtip({ 
	position: {
	  corner: {
	     target: 'leftMiddle',
	     tooltip: 'rightMiddle'
	  },
	  adjust: { 
	     x: 2 
	  }
	},
	style: {
		  tip: 'rightMiddle',
		  name: 'mystyle'
		  },
	show: {
		  effect: { length: 300 }  
		  }
	});
	// Para Banderitas en debate y en listados
	$('#opiniones li div h3[title], #listado_autores h2[title], #home_destacados p strong[title], #articulo_enc strong[title], .suscriptores p[title], .opiniones span[title]').qtip({ 
	position: {
	  corner: {
	     target: 'bottomLeft',
	     tooltip: 'topLeft'
	  },
	  adjust: { 
	     x: 10
	  }
	},
	style: {
		  tip: 'topLeft',
		  name: 'mystyle'
		  },
	show: {
		  effect: { length: 300 }  
		  }
	});
	// Para redes sociales contenidos
	$('.redes a[title], .facebook, .twitter, .linkedin, .recomendar, .publicar').qtip({ 
	position: {
	  corner: {
	     target: 'bottomMiddle',
	     tooltip: 'topMiddle'
	  }
	
	},
	style: {
		  tip: 'topMiddle',
		  name: 'mystyle'
		  },
	show: {
		  effect: { length: 300 }  
		  }
	});
	// Artículos debatientes
	$('#datos_pub a[title]').qtip({ 
	position: {
	  corner: {
	     target: 'rightMiddle',
	     tooltip: 'leftMiddle'
	  }
	},
	style: {
		  tip: 'leftMiddle',
		  name: 'mystyle'
		  },
	show: {
		  effect: { length: 300 }  
		  }
	});
	// Sponsors
	$('#pie a[title]').qtip({ 
	position: {
	  corner: {
	     target: 'topMiddle',
	     tooltip: 'bottomMiddle'
	  },
	  adjust: { 
	     y: -26
	  }
	},
	style: {
		  tip: 'bottomMiddle',
		  name: 'mystyle',
	  width: 140
		  },
	show: {
		  effect: { length: 300 }  
		  }
	});
				$('.opiniones li, .suscriptores li, #opiniones li h5').not('.perfil .opiniones li').each(function() {
					$(this).qtip({
					   content: {
					     url: '/includes/tooltip_usuario.php',
					     data: { "id" : $(this).find("img").attr("class")},
					     method: 'get'
					   },
					   position: {
					      corner: {
			         	  target: 'topLeft',
			         	  tooltip: 'bottomLeft'
			     	      },
			      	      adjust: { 
			         	  y: 5,
			         	  x: 24
			         	  }
					   },
					   style: {
					   	  tip: 'bottomLeft',
					   	  name: 'mystyle'
					   	  }
					})
				});
	

	// Ponemos las notas
	$('#articulo_texto sup').each(function() {
			$(this).qtip({
				content: $('#articulo_notas ol li:nth-child('+ $(this).text() +')').text(), 
				position: {
				  corner: {
				     target: 'topMiddle',
				     tooltip: 'bottomMiddle'
				  }
				},
				style: {
					  tip: 'bottomMiddle',
					  name: 'mystyle',
					  'text-align': 'left',
					  width: 300
					  },
				show: {
					  effect: { length: 300 }  
					  }
			});
	});
	
	// Ver más
	$('.ver_mas').click(function() {
		
   		var link = $(this).attr('href');
   		var boton = $(this);
   		var split = $(this).attr('href').split('/');
   		var nuevo = parseInt(split[3]) + 10;
		$.ajax({
			type: "POST",
			beforeSend: function(){
				boton.html('<img class="spinner" src="/imagenes/layout/spinner_rojo.gif">');
			},
			data: { 'nada' : 0  },
			url: link,
			success: function(msg){
				boton.before(msg);
				boton.html('Ver más');
				boton.attr('href',link.replace(split[3], nuevo));
			}
		});
    	return false;
	});

	bindVotos();
	bindSeguir();
});
