var current = 0;
var current2 = 0;
$(document).ready(function() {


		$('.in').fancybox({
		'transitionIn'	:	'elastic',
		'overlayOpacity':   0.7,
		'padding'		:	20,

		'autoDimensions':	true,
		'autoScale'		:	true,

		'speedIn'		:	600, 
		'speedOut'		:	200, 
		'overlayShow'	:	true,
		'scrolling'		:	'no'
		});
		$('.editar').fancybox({
		'transitionIn'	:	'elastic',
		'overlayOpacity':   0.7,
		'padding'		:	20,

		'autoDimensions':	true,
		'autoScale'		:	true,
		'speedIn'		:	600, 
		'speedOut'		:	200, 
		'overlayShow'	:	true,
		'scrolling'		:	'no'
		});
		$("#back").hide();
		$("#back1").hide();
		$(".peliborde").moveline();
		$(".revisar").tooltip();
		slideShow();
		$('.datepicker').datepicker({dateFormat: 'dd-mm-yy'});
		  pheight=$(document).height();

     $('body').append("<div id='blanco' style='height:"+pheight+"px;'></div>");

    $('#blanco').click(function() {

        mostrar();

    });



	$('.newsseries').click(function() {
		$('.newsseries').hide();
        	$('.nstr').show();

    });

  peliborde();

$('#respuestas').css({"max-height":"500px","overflow":"auto","display":"none","position":"absolute","left":$('#tags').offset().left+"px","top":($('#tags').offset().top+$('#tags').height()+4)+"px","width":$('#tags').width()+"px","background":"white","padding":"5px"})
$('#tags').keyup(function() {
 	palabra=$('#tags').val();
	if(palabra.length>0)
	{
		$('#respuestas').fadeIn();
		$.post("/php/autoc.php",{palabra:palabra},
		function(data){
			$('#respuestas').html(data);
			dentro_auto();
		});
	}
	else
		$('#respuestas').fadeOut();

   

});

$('#tags').blur(function() {
	$('#respuestas').fadeOut();
})

$('#tags').focus(function() {
	if($('#tags').val()!="")
		$('#respuestas').fadeIn();
})
   

});

function dentro_auto()
{
$('.dentroauto').click(function(){
	//alert("GIAK");
	window.location.href=$(this).children(".link_busc").text();
});
}

function peliborde()
{
$('.peliborde').click(function() {

      window.location.href=$(this).children("a:first").attr("href");

    });
}
jQuery.fn.moveline = function(){

    $(this).mousemove(function(e){
	  max=$(this).height();
	  $(this).children('div:first').show();
	mitad=$(this).children('div:first').height()/2;
	  if((e.pageY-$(this).offset().top)<=(max-mitad) && ((e.pageY-$(this).offset().top)-mitad>0))
			$(this).children('div:first').css("top",(e.pageY-$(this).offset().top)-(mitad));
		else
			if((e.pageY-$(this).offset().top)>mitad)
				$(this).children('div:first').css("top",max-$(this).children('div:first').height());
			else
				$(this).children('div:first').css("top","0");
    });
$(this).mouseleave(function() {
  $(this).children('div:first').hide();
});
}

function peticion()
{

	peticion=$('#contenido').val();
	$.post("/php/peticion.php",{peticion:peticion},
				   function(data) {
						mostrar();
						alert("¡Gracias por tu petición en cuanto podamos lo subiremos!");
					}
				   );
	
}

function anoticia()
{
	titulo=$('#titulonot').val();
	noticia=$('#noticia').val();
	$.post("/php/noticia.php",{noticia:noticia, titulo:titulo},
				   function(data) {
						mostrar();
						$('#tnoticias').prepend(data);
					}
				   );
	
}

function newsseries(contenido)
{
	email=$('#newsserie').val();
	$('#errorns').fadeOut();
	//alert(email+contenido);
	if(email!="")
	{
		$.post("/php/anewsseries.php",{contenido:contenido, email:email},
					   function(data) {
							if(data!=1)
								$('#errorns').html("Este email ya está utilizado para esta serie").fadeIn();
							else
								$('.nstr').html("Te has registrado perfectamente, los nuevos capítulos de esta serie te llegarán al email.");
						}
					   );
	}
	else
	{
		
		$('#errorns').html("El email no puede quedar vacío").fadeIn();
		$('#newsserie').focus();
	}
}
function anot(id, contenido, temporada, capitulo)
{
	$('.anotanot').remove();
	idioma=$('input[type="checkbox"]:checked').val();
	$.post("/php/anoticia.php",{id:id, contenido:contenido, temporada:temporada, capitulo:capitulo, idioma:idioma},
				   function(data) {
						//alert(data);
					}
				   );
	
}

function mostrar(pos)
{

	if(pos==1)
		$('#titulomostrar').html("¡Escribe aquí la petición y en un plazo de 24 horas intentaremos subirla!:<br/>¡Si escribes tu <b>email</b> te avisaremos!");
	if(pos==2)
		$('#titulomostrar').html("Escribe tu noticia");

      $('#contenido').val("");
 $('#titulonot').val("");

	$('#blanco').toggle();
      $('.pantalla').slideToggle();



}

function desplegar()
{

		$('#logindentro').slideToggle();

		
}

function analisis()
{
	fecha1=$('#fecha1').val();
	fecha2=$('#fecha2').val();
	$('#analisis').fadeOut();
	$.post("/php/analisis.php",{fecha1:fecha1, fecha2:fecha2},
				   function(data) {
						$('#analisis').html(data).fadeIn();
					}
				   );
}

function aclick(idlink)
{
	$.post("/php/aclick.php",{idlink:idlink},
				   function(data) {
					}
				   );
}

function paginacion(pos, contenido)
{
	if(contenido==1)
	{
		if(pos==1)
			current++;
		else
			current--;

		if(current<=0)
			$("#back").hide();
		else
			$("#back").show();
		$('#novedadespelis').fadeOut();
		$.post("/php/paginacion.php",{pagina:current, pelicula:1},
				   function(data) {
						$('#novedadespelis').html(data).fadeIn();
						$(".peliborde").moveline();
						 peliborde();
					}
				   );
	}	
	if(contenido==2)
	{
		if(pos==1)
			current2++;
		else
			current2--;

		if(current2<=0)
			$("#back1").hide();
		else
			$("#back1").show();
		$('#novedadesseries').fadeOut();
		$.post("/php/paginacion.php",{pagina:current2, pelicula:0},
				   function(data) {
						$('#novedadesseries').html(data).fadeIn();
						$(".peliborde").moveline();
						 peliborde();
					}
				   );
	}


	
}

 
function slideShow() {
 
    //Set the opacity of all images to 0
    $('#gallery a').css({opacity: 0.0});
     
    //Get the first image and display it (set it to full opacity)
    $('#gallery a:first').css({opacity: 1.0});
     
    //Set the caption background to semi-transparent
    $('#gallery .caption').css({opacity: 0.7});
 
    //Resize the width of the caption according to the image width
    $('#gallery .caption').css({width: $('#gallery a').find('img').css('width')});
     
    //Get the caption of the first image from REL attribute and display it
    //$('#gallery .content').html($('#gallery a:first').find('img').attr('rel'))
    //.animate({opacity: 0.7}, 400);
     
    //Call the gallery function to run the slideshow, 6000 = change to next image after 6 seconds
    setInterval('gallery()',15000);
     
}
 
function gallery() {
     
    //if no IMGs have the show class, grab the first image
    var currentt = ($('#gallery a.show')?  $('#gallery a.show') : $('#gallery a:first'));
 
    //Get next image, if it reached the end of the slideshow, rotate it back to the first image
    var next = ((currentt.next().length) ? ((currentt.next().hasClass('caption'))? $('#gallery a:first') :currentt.next()) : $('#gallery a:first'));  
     
    //Get next image caption
    var caption = next.find('img').attr('rel');
     
    //Set the fade in effect for the next image, show class has higher z-index
    next.css({opacity: 0.0})
    .addClass('show')
    .animate({opacity: 1.0}, 1000);
 
    //Hide the current image
    currentt.animate({opacity: 0.0}, 1000)
    .removeClass('show');
     
    //Set the opacity to 0 and height to 1px
    $('#gallery .caption').animate({opacity: 0.0}, { queue:false, duration:0 }).animate({height: '1px'}, { queue:true, duration:300 });
     
    //Animate the caption, opacity to 0.7 and heigth to 100px, a slide up effect
    $('#gallery .caption').animate({opacity: 0.7},100 ).animate({height: '50px'},500 );
     
    //Display the content
    $('#gallery .content').html(caption);
         
}


function slideShow2() {
 
    //Set the opacity of all images to 0
    $('#gallery2 a').css({opacity: 0.0});
     
    //Get the first image and display it (set it to full opacity)
    $('#gallery2 a:first').css({opacity: 1.0});
     
    //Set the caption background to semi-transparent
    $('#gallery2 .caption2').css({opacity: 0.7});
 
    //Resize the width of the caption according to the image width
    $('#gallery2 .caption2').css({width: $('#gallery2 a').find('img').css('width')});
     
    //Get the caption of the first image from REL attribute and display it
  
     
    //Call the gallery function to run the slideshow, 6000 = change to next image after 6 seconds
    setInterval('gallery2()',7000);
     
}
 
function gallery2() {
     
    //if no IMGs have the show class, grab the first image
    var currentt = ($('#gallery2 a.show2')?  $('#gallery2 a.show2') : $('#gallery2 a:first'));
 
    //Get next image, if it reached the end of the slideshow, rotate it back to the first image
    var next = ((currentt.next().length) ? ((currentt.next().hasClass('caption2'))? $('#gallery2 a:first') :currentt.next()) : $('#gallery2 a:first'));  
     
    //Get next image caption
    var caption = next.find('img').attr('rel');
     
    //Set the fade in effect for the next image, show class has higher z-index
    next.css({opacity: 0.0})
    .addClass('show2')
    .animate({opacity: 1.0}, 1000);
 
    //Hide the current image
    currentt.animate({opacity: 0.0}, 1000)
    .removeClass('show2');
     
    //Set the opacity to 0 and height to 1px
    $('#gallery2 .caption2').animate({opacity: 0.0}, { queue:false, duration:0 }).animate({height: '1px'}, { queue:true, duration:300 });
     
    //Animate the caption, opacity to 0.7 and heigth to 100px, a slide up effect
    $('#gallery2 .caption2').animate({opacity: 0.7},100 ).animate({height: '50px'},500 );
     
    //Display the content
    $('#gallery2 .content2').html(caption);
         
}

function nova(id,cont,l,tipo,idcat)
{
	titulo=$('#nombre').text();
	descrev=$('#descrev').val();
	$.post("/php/revisar.php",{texto: "/admin/modificarcontenido.php?id="+id+"&cont="+cont+"&l="+l+"&tipo="+tipo+"&idcat="+idcat, titulo: titulo, pos: 1,descrev:descrev},
				   function(data) {
						$.fancybox.close();
						alert("Lo revisaremos lo antes posible, gracias por ayudar");
					}
				   );
}

function votar(contenido, pos)
{
	$('#numvotos').html("");
	$('#numvotos').fadeOut();
	if(pos==1)
	{
		$.post("/php/votar.php",{contenido: contenido, pos: pos},
				   function(data) {
						$('#numvotos').html(data).fadeIn();
					}
				   );
	}
	
}

function addcat(id,cat)
{
	if(id==1)
	{
		nombre=$('#nombre').val();
		$.post("/php/addcat.php",{nombre: nombre, id: id},
					   function(data) {
								$.fancybox.close();
								location.reload();
						}
					   );
	}
	if(id==2)
	{
		nombre=$('#nombre').val();
		imagen=$('#imagen').val();
		descripcion=$('#descripcion').val();
		

						
						var prueba = $.ajaxFileUpload({
						url:'/php/fotoforo.php', 
						fileElementId:'imagen',
						dataType: 'script',
						async: false,
						success: function (data)
								{
									img=data;
									$.post("/php/addcat.php",{nombre: nombre, imagen:img, descripcion:descripcion, cat:cat, id: id},
									function(data) {
										$.fancybox.close();
										//location.reload();
									}
									);
								}
						}).responseText;
		
		

	}
}

function revisado(id)
{
	$.post("/php/revisar.php",{id : id, pos: 2},
				   function(data) {
					$('#'+id).remove();
				   }
				   );
}

function activar(link,contenido,capi,pos,genero,sino)
{
	if(pos==1)
	{
		$.post("/php/activar.php",{idlink : link, contenido: contenido, capi: capi, pos: 1},
				   function(data) {
						$('#'+link).remove();
						if($('.tb').text()=="")
							$.fancybox.close();
					}
				   ); 
	}
	if(pos==2)
	{
		$.post("/php/activar.php",{idlink : link, contenido: contenido, capi: capi, pos: 2, genero: genero},
				   function(data) {
						$('#'+link).remove();
						if($('.tb').text()=="")
							$.fancybox.close();
						if(sino==1)
							location.reload();
					}
				   ); 
	}
	if(pos==3)
	{
		$.post("/php/activar.php",{contenido: contenido, pos: 3},
				   function(data) {
				   //alert("hola");
						$('#'+contenido).remove();
						if($('.tb').text()=="")
							$.fancybox.close();
					}
				   ); 
	}
	if(pos==4)
	{
		$.post("/php/activar.php",{contenido: contenido, pos: 4, genero: genero},
				   function(data) {
						$('#'+contenido).remove();
						if($('.tb').text()=="")
							$.fancybox.close();
					}
				   ); 
	}

	
		
	
	
		
}
function modificar(tipo, l, cat)
{
var calidad = $('#calidad :selected').val();
var idioma = $('#idioma :selected').val();
if(tipo==1)
	var link = encodeURIComponent($('#online').val());
if(tipo==2)
	var link = encodeURIComponent($('#descarga').val());
	
$("#partes input").each(function(){
str = str + encodeURIComponent($(this).val())+",";
});

var dataString = 'calidad='+ calidad + '&idioma=' + idioma+'&link='+link+'&l='+l+'&cat='+cat+'&str='+str+'&stron='+stron;

		$.ajax({
      type: 'POST',
      url: '/php/modificar.php',
      data: dataString,
      success:   function(data) {
		$.fancybox.close();
		str="";
		location.reload();
        }
		});

}
var str ="";
var stron="";
function insertar(id)
{
	if(id==3 || id==4 || id==5 )
	{
		var titulo = encodeURIComponent($('#titulo').val());
		var img = $('#imagen').val();
		var descripcion = encodeURIComponent($('#descripcion').val());
		var extension = (img.substring(img.lastIndexOf("."))).toLowerCase();
		var descarga = encodeURIComponent($('#descarga').val());
		var nota = $('#nota').val();
		

				if(titulo!="" && img!="" && descripcion!="")
				{
					if ((extension==".jpg") || (extension==".gif") || (extension==".png") ) 
					{
						$("#loading")
						.ajaxStart(function(){
							$(this).show();
						})
						.ajaxStop(function(){
							$(this).hide();
							$.fancybox.close();
						});
						
						var prueba = $.ajaxFileUpload({
						url:'/php/fotocont.php', 
						fileElementId:'imagen',
						dataType: 'script',
						async: false,
						success: function (data)
								{
									img=data;
									$("#partes input").each(function(){
									str = str + encodeURIComponent($(this).val())+",";
									});
									var dataString = 'id='+id+'&titulo='+titulo+'&nota='+nota+'&img='+img+'&descripcion='+descripcion+'&str='+str+'&descarga='+descarga;
									$.ajax({
									type: 'POST',
									url: '/php/insertarcont.php',
									data: dataString,
									success:   function(data) {
									str="";
									}
									});
								}
						}).responseText;
					
					}
					else
					{
						$('.error').text('LA IMAGEN TIENE QUE SER: JPG/GIF/PNG').show('bounce',400);
						$('.error').hide('clip',1000);
					}
				}
				else
				{
					$('.error').text('TIENES QUE INTRODUCIR TODOS LOS DATOS').show('bounce',400);
					$('.error').hide('clip',1000);
				}
			}
		

	if(id==2)
	{
		var titulo = encodeURIComponent($('#titulo').val());
		var genero = $('#genero').val();
		var img = $('#imagen').val();
		var descripcion = encodeURIComponent($('#descripcion').val());
		var extension = (img.substring(img.lastIndexOf("."))).toLowerCase();
		$.post("/php/titulo.php", { titulo: titulo },
		   function(data) {
						if(data=="si")
						{
								if(titulo!="" && img!="" && descripcion!="")
								{
									if ((extension==".jpg") || (extension==".gif") || (extension==".png") ) 
									{
										$("#loading")
										.ajaxStart(function(){
											$(this).show();
										})
										.ajaxStop(function(){
											$(this).hide();
											$.fancybox.close();
										});
										
										var prueba = $.ajaxFileUpload({
										url:'/php/fotocont.php', 
										fileElementId:'imagen',
										dataType: 'script',
										async: false,
										success: function (data)
												{
													img=data;
													var dataString = 'id='+id+'&titulo='+titulo+'&img='+img+'&descripcion='+descripcion+'&genero='+genero;
													$.ajax({
													type: 'POST',
													url: '/php/insertarcont.php',
													data: dataString,
													success:   function(data) {
													}
													});
												}
										}).responseText;
									
									}
									else
									{
										$('.error').text('LA IMAGEN TIENE QUE SER: JPG/GIF/PNG').show('bounce',400);
										$('.error').hide('clip',1000);
									}
								}
								else
								{
									$('.error').text('TIENES QUE INTRODUCIR TODOS LOS DATOS').show('bounce',400);
									$('.error').hide('clip',1000);
								}
						}
						else
						{
								$('.error').text('LA SERIE '+titulo+' YA SE ENCUENTRA EN NUESTRA BASE DE DATOS').show('bounce',400);
								$('.error').hide('clip',1000);
						}
				});
	}

	if(id==10)
	{
		var titulo = encodeURIComponent($('#titulo').val());
		var temporada = $('#temporada').val();
		var capitulo = $('#capitulo').val();
		var serie = $('#serie').val();
		var calidad = $('#calidad').val();
		var idioma = $('#idioma').val();
		var online = encodeURIComponent($('#online').val());
		var descarga = encodeURIComponent($('#descarga').val());
		if(titulo!="" && temporada!="" && capitulo!="" && serie!="" && calidad!="" && idioma!="" && (online!="" || descarga!=""))
		{
			var dataString = 'id='+id+'&titulo='+titulo+'&calidad='+calidad+'&idioma='+idioma+'&online='+online+'&descarga='+descarga+'&capitulo='+capitulo+'&temporada='+temporada+'&serie='+serie;
			$.ajax({
			type: 'POST',
			url: '/php/insertarcont.php',
			data: dataString,
			success:   function(data) {
					$.fancybox.close();
				}
			});	
		}
		else
		{
			$('.error').text('TIENES QUE INTRODUCIR TODOS LOS DATOS').show('bounce',400);
			$('.error').hide('clip',1000);
		}
	}
	if(id==11){
		//var titulo = encodeURIComponent($('#titulo').val());
		var temporada = $('#temporada').val();
		//var capitulo = $('#capitulo').val();
		var serie = $('#serie').val();
		var calidad = $('#calidad').val();
		var idioma = $('#idioma').val();
		//var online = encodeURIComponent($('#online').val());
		var descarga = $('#tdescarga').val();
		//alert(descarga);
  		var descargas = descarga.split('\n');
		//for(i=0;i<descargas.length;i++)alert(descargas[i]);


		if( temporada!=""  && serie!="" && calidad!="" && idioma!="" && descarga!="")
		{
			for(i=0;i<descargas.length;i++){
				if(descargas[i]!=""){
				var dataString = 'id=10'+'&titulo=Capitulo '+(i+1)+'&calidad='+calidad+'&idioma='+idioma+'&online='+'&descarga='+descargas[i]+'&capitulo='+(i+1)+'&temporada='+temporada+'&serie='+serie;
				$.ajax({
				type: 'POST',
				url: '/php/insertarcont.php',
				data: dataString,
				success:   function(data) {
						$.fancybox.close();
					}
				});
				}
			}
		}
		else
		{
			$('.error').text('TIENES QUE INTRODUCIR TODOS LOS DATOS').show('bounce',400);
			$('.error').hide('clip',1000);
		}
	}
	if(id==1 || id==12)
	{
		var titulo = encodeURIComponent($('#titulo').val());
		var ano = $('#ano').val();
		var estreno = $('#estreno').val();
		var genero = $('#genero').val();
		var calidad = $('#calidad').val();
		var idioma = $('#idioma').val();
		var img = $('#imagen').val();
		var online = encodeURIComponent($('#online').val());
		var descarga = encodeURIComponent($('#descarga').val());
		var descripcion = encodeURIComponent($('#descripcion').val());
		
		if(id==12)
		{
			estreno="0";
			img="0.jpg";
			descripcion="0";
			genero="0";
		}
		var extension = (img.substring(img.lastIndexOf("."))).toLowerCase();
		if(titulo!="" && ano!="" && genero!="" && calidad!="" && idioma!="" && img!="" && (online!="" || descarga!="") && descripcion!="")
		{
			if ((extension==".jpg") || (extension==".gif") || (extension==".png") ) 
			{
				$("#loading")
				.ajaxStart(function(){
					$(this).show();
				})
				.ajaxStop(function(){
					$(this).hide();
					$.fancybox.close();
				});
				
				if(id==1)
				{
				
				var prueba = $.ajaxFileUpload({
				url:'/php/fotocont.php', 
				fileElementId:'imagen',
				dataType: 'script',
				async: false,
				success: function (data)
						{
							img=data;
							$("#partes input").each(function(){
							str = str + $(this).val()+",";
							});
							$("#parteson input").each(function(){
							stron = stron + $(this).val()+",";
							});
							var dataString = 'id='+id+'&titulo='+titulo+'&ano='+ano+'&estreno='+estreno+'&genero='+genero+'&calidad='+calidad+'&idioma='+idioma+'&img='+img+'&online='+online+'&descarga='+descarga+'&descripcion='+descripcion+'&str='+str+'&stron='+stron;
							$.ajax({
							type: 'POST',
							url: '/php/insertarcont.php',
							data: dataString,
							success:   function(data) {
							str="";
							stron="";
							}
							});
						}
				}).responseText;
				}
				else
				{
					//alert("Hola");
					$("#partes input").each(function(){
							str = str + $(this).val()+",";
							});
							$("#parteson input").each(function(){
							stron = stron + $(this).val()+",";
							});
							var dataString = 'id='+id+'&titulo='+titulo+'&ano='+ano+'&calidad='+calidad+'&idioma='+idioma+'&online='+online+'&descarga='+descarga+'&str='+str+'&stron='+stron;
							$.ajax({
							type: 'POST',
							url: '/php/insertarcont.php',
							data: dataString,
							success:   function(data) {
							str="";
							stron="";
							$.fancybox.close();
							}
							});
				}
			
			}
			else
			{
				$('.error').text('LA IMAGEN TIENE QUE SER: JPG/GIF/PNG').show('bounce',400);
				$('.error').hide('clip',1000);
			}
		}
		else
		{
			$('.error').text('TIENES QUE INTRODUCIR TODOS LOS DATOS').show('bounce',400);
			$('.error').hide('clip',1000);
		}
	}
	
}

function anota()
{
$('#notas').html('<textarea id="nota" rows="10" cols="20">Escribe aquí la nota</textarea>').show('bounce',400);
}

function adesc()
{
$('#partes').append('<input type="text" />');
}

function adescon()
{
$('#parteson').append('<input type="text" />');
}

function comprobar2(){
var nombre = encodeURIComponent($('#nombre').val());
var email = encodeURIComponent($('#email').val());
var asunto = encodeURIComponent($('#asunto').val());
var mn = encodeURIComponent($('#mn').val());
if(nombre=="" || email=="" || asunto=="" || mn==""){
	$('#error').text('DEBES INTRODUCIR TODOS LOS DATOS').show('bounce',400);
	$('#error').hide('clip',1000);
	
	
}else{
var dataString =  'nombre='+nombre +'&email='+email +'&asunto='+asunto+ '&mn='+mn;
		$.ajax({
      type: "POST",
      url: "/php/contacto.php",
      data: dataString,
      success:   function(data) {
	  $('#mensaje').html('<font color=#2fb400><b>SU MENSAJE HA SIDO ENVIADO CORRECTAMENTE, NOS PONDREMOS EN CONTACTO CON USTED LO ANTES POSIBLE, GRACIAS.</b></font>');
	  }
		});
}
}


function quitaacentos(str)
{
	str=str.replace(/á/g, "a");
	str=str.replace(/é/g, "e");
	str=str.replace(/í/g, "i");
	str=str.replace(/ó/g, "o");
	str=str.replace(/ú/g, "u");

	return str;
}



/*$(function() {
		$( "#tags" ).autocomplete({
		source: "/php/contenido.php",
  		select: function(event, ui) { 
				str=ui.item.value;
				str=quitaacentos(str)
				//alert(str);
				$.post("/php/link.php", { term:  str },
				   function(resp){
					//alert(resp);
					if(resp[0] ==null || resp[1]==null || resp[2]==null)
						window.location.href = "/";
					else 
						window.location.href = "/"+resp[2]+"/"+resp[1]+"/"+resp[0]+"/";

				   }, "json");

		}

			
		});
	});*/

$(function() {
		$( "#accordion" ).accordion({
			autoHeight: false,
			navigation: true
		});
	});
	
	$(function() {
		$( "#accordion2" ).accordion({
			autoHeight: false,
			navigation: true
		});
	});

function logout(){
	$.ajax({
    url: '/sesion/logout.php',
    success:   function(data) {
		location.reload();
		}
	});
}
	
$(function() {
		$( "#sortable" ).sortable();
		$( "#sortable" ).disableSelection();
	});
	
function efecto(){	
			var options = {};

				$( "#usulogin" ).effect( 'shake', 150 );
				
}

function registro(nick, pass, email)
{
	$( '#rs' ).fadeOut();
	email=$('#email').val();
	nick=$('#name').val();
	pass=$('#password').val();
	//alert(nick);
	var dataString = 'email='+ email+ '&nick='+ nick+ '&pass='+pass;

	if(email!="" && nick!="" && pass!="")
	{	
		$.ajax({
	      type: "POST",
	      url: "/php/reg.php",
	      data: dataString,
	      success:   function(data) {
				//alert(data);
			  if(data=="nick")
			  {
				$( '#rs' ).html("*El usuario <b>"+nick+"</b> ya existe").fadeIn();
			  }
			  if(data=="email")
			  {
				$( '#rs' ).html("*El email <b>"+email+"</b> ya existe").fadeIn();
			  }
			  if(data=="1")
			  {
			 	$( '#rs' ).html("*Te has registrado correctamente, Logeate.").fadeIn();
			
			  }
		      }
		});
	}
	else
	{
		$( '#rs' ).html("*Todos los datos son obligatorios").fadeIn();
	}

}

function loginnuevo()
{
alert("Login todavía inactivo! puedes utilizar el antiguo! gracias!");
}

/*$(function() {
		// a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
		$( "#dialog:ui-dialog" ).dialog( "destroy" );
		
		var name = $( "#name" ),
			email = $( "#email" ),
			password = $( "#password" ),
			allFields = $( [] ).add( name ).add( email ).add( password ),
			tips = $( ".validateTips" );
			
		function updateTips( t ) {
			tips
				.text( t )
				.addClass( "ui-state-highlight" );
			setTimeout(function() {
				tips.removeClass( "ui-state-highlight", 1500 );
			}, 500 );
		}

		function checkLength( o, n, min, max ) {
			if ( o.val().length > max || o.val().length < min ) {
				o.addClass( "ui-state-error" );
				updateTips( "Revisa el " + n + ", mínimo " +
					min + " carácteres máximo " + max + "." );
				return false;
			} else {
				return true;
			}
		}

		function checkRegexp( o, regexp, n ) {
			if ( !( regexp.test( o.val() ) ) ) {
				o.addClass( "ui-state-error" );
				updateTips( n );
				return false;
			} else {
				return true;
			}
		}
		
		$( "#dialog-form" ).dialog({
			autoOpen: false,
			width: 370,
			autoHeight: false,
			modal: true,
			buttons: {
				"Crear cuenta": function() {
					var bValid = true;
					allFields.removeClass( "ui-state-error" );

					bValid = bValid && checkLength( name, "nombre", 3, 16 );
					bValid = bValid && checkLength( email, "email", 6, 80 );
					bValid = bValid && checkLength( password, "password", 5, 16 );

					bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Símbolos no permitidos en el usuario" );
					bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "ej. megatube@megatube.es" );
					bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Símbolos no permitidos en la contraseña" );

					if ( bValid ) {
					registro(name.val(),password.val(),email.val());
					}
				},
				Cancelar: function() {
					$( this ).dialog( "close" );
				}
			},
			close: function() {
				allFields.val( "" ).removeClass( "ui-state-error" );
			}
		});

		$( "#create-user" )

			.click(function() {
				$( "#dialog-form" ).dialog( "open" );
			});
	});*/
	
function comprobar(){
var nick = $('#usu').val();
var pass = $('#pass').val();

var dataString = 'nick='+ nick + '&pass=' + pass;
	$("#errorlogin").fadeOut();
		$.ajax({
      type: 'POST',
      url: '/sesion/ses.php',
      data: dataString,
      success:   function(data) {
		  if(data=="si")
		  {
			location.reload();
		  }
		  else
		  {
			$("#errorlogin").html("*Usuario/Contraseña incorrectos").fadeIn();
			//efecto();
		  }
        }
		});
}


