/* FORMULARIO DE INSCRIPCION */
var enviandoRegistro = false;
var eliminarRegistro = false;
var concursoRegistro = false;

function checklengthDescripcion()
{
	var max = 550;
	var txt;
	txt = document.getElementById('descripcion');
	var n = txt.value.length;
	if (n>max)
	{
		txt.value = txt.value.substring(0, max);
		return false;
	}
}

function checklengthTitulo()
{
	var max = 50;
	var txt;
	txt = document.getElementById('nombre');
	var n = txt.value.length;
	if (n>max)
	{
		txt.value = txt.value.substring(0, max);
		return false;
	}
}

function checkFecha (fechaCreacion)
{
	return fechaCreacion.match( /^([0-9]{2})([-])([0-9]{2})([-])([0-9]{4})/);
}

function EnviarRegistro()
{
	if(!enviandoRegistro)
	{
		enviandoRegistro = true;

		categoriasOk = checkCategorias('blogoteca');
		
		if (document.getElementById('participaP20B').value != 'inactivo')
		{
		  categoriasConcursoOk = checkCategorias('concurso');
    }

		//Comprobamos datos obligatorios
		//Datos del blog
		if (trim(document.getElementById('nombre').value) == '')
		{
			alert('Debes introducir el nombre del blog');
			document.getElementById('nombre').focus();
			enviandoRegistro = false;
			return false;
		}
		if (document.getElementById('nombre').value.length > 50)
		{
			alert('El título del blog no puede contener más de 50 caracteres');
			document.getElementById('nombre').focus();
			enviandoRegistro = false;
			return false;
		}
		if (trim(document.getElementById('url').value) == '')
		{
			alert('Debes introducir la url del blog');
			document.getElementById('url').focus();
			enviandoRegistro = false;
			return false;
		}
		if (trim(document.getElementById('autor').value) == '')
		{
			alert('Debes introducir el autor del blog');
			document.getElementById('autor').focus();
			enviandoRegistro = false;
			return false;
		}
		if (trim(document.getElementById('descripcion').value) == '')
		{
			alert('Debes introducir la descripcion del blog');
			document.getElementById('descripcion').focus();
			enviandoRegistro = false;
			return false;
		}
		if (document.getElementById('descripcion').value.length > 550)
		{
			alert('La descripción no puede contener más de 550 caracteres');
			document.getElementById('descripcion').focus();
			enviandoRegistro = false;
			return false;
		}
		if ( (trim(document.getElementById('fechaCreacion').value) != '') && (!checkFecha(document.getElementById('fechaCreacion').value)) )
		{
			alert('Debes introducir la fecha de creación con formato adecuado (dd-mm-aaaa)');
			document.getElementById('fechaCreacion').focus();
			enviandoRegistro = false;
			return false;
		}
		if (categoriasOk != "")
    {
			alert(categoriasOk);
			enviandoRegistro = false;
			return false;
		}
		if ( (document.getElementById('participaP20B').value != 'inactivo') && (document.getElementById('participaP20B_S').checked) && (categoriasConcursoOk != "") )
		{
			alert(categoriasConcursoOk);
			enviandoRegistro = false;
			return false;
		}
		if (trim(document.getElementById('codigo').value) == '')
		{
			alert('Debes introducir el código de verificación');
			document.getElementById('codigo').focus();
			enviandoRegistro = false;
			return false;
		}
		document.getElementById('form_registro_directorio_blogs').submit();
	}
}

function seleccionar_Participacion (opc)
{
	if (opc == 'S')
  {
    $('#cat_premios').fadeIn("slow");
    $('#texto_confirmar').html('Pulsando "Confirmar Inscripción" aceptas las <a href="' + url_web_20m + 'aviso/legal/" target="_blank">condiciones de participación en 20minutos.es</a> y las <a href="/premios-20blogs/bases/" target="_blank">bases de los Premios 20Blogs</a>.');
	}
	else //if (opc == 'N')
	{
    $('#cat_premios').fadeOut("slow");
    $('#texto_confirmar').html('Pulsando "Confimar Inscripción" aceptas las <a href="' + url_web_20m + 'aviso/legal/" target="_blank">condiciones de participación en 20minutos.es</a>.');
	}
}

function seleccionar_categoriaConcurso (categoriaConcurso, ident_diseno)
{
  var ocultoDiseno = jQuery('#cat_diseno:hidden').length > 0;

  if (categoriaConcurso == ident_diseno) //Categoría Diseño
	{
		$('#cat_diseno').fadeOut("slow");
	}
	else if ( (categoriaConcurso != ident_diseno) && (ocultoDiseno) )
	{
		$('#cat_diseno').fadeIn("slow");
	}
}

function sugerirCategorias()
{
  var mapeos =
  {
    1: '1',
    3: '3',
    5: '4',
    6: '5',
    7: '6',
    8: '7',
    9: '8',
    10: '9',
    12: '5',
    11: '5',
    20: '14',
    13: '5',
    14: '17,5',
    15: '10',
    16: '10',
    18: '11',
    4: '16',
    19: '13',
    23: '15,5',
    24: '17',
    22: '14',
    25: '18',
    26: '3',
    27: '4',
    29: '2',
    31: '19',
    21: '14',
    28: '20',
    32: '12'
  };

  var categoriasTxt = '';
  jQuery(':checkbox:checked').each(function(i)
  {
      var tmp1 = jQuery(this).attr('value').replace(/(.+)\|\|.+/g, '$1');
      var tmp2 = mapeos[tmp1];
      if (tmp2 != undefined)
      {
        categoriasTxt += tmp2 + ',';
      }
  });

  var categoriasTxt = categoriasTxt.replace(/(.*),$/, '$1');
  var categorias = categoriasTxt.split(',');

  jQuery('li[@id^=concurso_]').removeClass('destacada');

  jQuery(categorias).each(function(i)
  {
    jQuery('li#concurso_' + this).addClass('destacada');
  });
}


/* /FORMULARIO DE INSCRIPCION */

function CambiarCapaRegistro(op)
{
	if (op == 'borrar')
	{
		document.getElementById('operacion').value = 'eliminacion';
		
		$('#class_modif').removeClass("seleccionada");
		$('#class_modif').addClass("no_seleccionada");
    document.getElementById('capa_datos').style.display = 'none';

    $('#class_elim').removeClass("no_seleccionada");
    $('#class_elim').addClass("seleccionada");
    document.getElementById('capa_borrar').style.display = 'block';

    if (document.getElementById('capa_conc') != null)
    {
		  $('#class_conc').removeClass("seleccionada");
		  $('#class_conc').addClass("no_seleccionada");
		  document.getElementById('capa_conc').style.display = 'none';
    }
	}
	else if (op == 'modificar')
	{
		document.getElementById('operacion').value = 'modificacion';

		$('#class_modif').removeClass("no_seleccionada");
		$('#class_modif').addClass("seleccionada");
    document.getElementById('capa_datos').style.display = 'block';

    $('#class_elim').removeClass("seleccionada");
    $('#class_elim').addClass("no_seleccionada");
    document.getElementById('capa_borrar').style.display = 'none';

    if (document.getElementById('capa_conc') != null)
    {
		  $('#class_conc').removeClass("seleccionada");
      $('#class_conc').addClass("no_seleccionada");
		  document.getElementById('capa_conc').style.display = 'none';
    }
	}
	else if (op == 'concurso')
	{
		document.getElementById('operacion').value = 'concurso';

    $('#class_modif').removeClass("seleccionada");
		$('#class_modif').addClass("no_seleccionada");
    document.getElementById('capa_datos').style.display = 'none';

    $('#class_elim').removeClass("seleccionada");
    $('#class_elim').addClass("no_seleccionada");
    document.getElementById('capa_borrar').style.display = 'none';

    if (document.getElementById('capa_conc') != null)
    {
		  $('#class_conc').removeClass("no_seleccionada");
      $('#class_conc').addClass("seleccionada");
		  document.getElementById('capa_conc').style.display = 'block';
    }
  }
}

function CapaRegistro(elemento, operacion)
{
	document.getElementById('form_modificacion_directorio_blogs').action = elemento.href;
	document.getElementById('form_modificacion_directorio_blogs').operacion_href.value = operacion;
	document.getElementById('form_modificacion_directorio_blogs').submit();
	return false;
}

function EliminarRegistro(tipo_mensaje)
{
	if (eliminarRegistro) return;

	//Comprobamos datos obligatorios
	if (trim(document.getElementById('codigo_elim').value) == '')
	{
		alert('Debes introducir el código de verificación');
		document.getElementById('codigo_elim').focus();
		return false;
	}
	
	if (tipo_mensaje == 'simple')
	{
    texto = '¿Estás seguro de querer eliminar el blog? Desparecera tu presencia en laBlogoteca.';
  }
  else //if (tipo_mensaje == 'doble')
  {
    texto = '¿Estás seguro de querer eliminar el blog? Desparecera tu presencia tanto en laBlogoteca como en Premios 20Blogs.';
  }

	if (confirm(texto))
	{
		eliminarRegistro = true;
		document.getElementById('form_registro_directorio_blogs').submit();
	}
}

function ConfirmarParticipacion()
{
	if(!enviandoRegistro)
	{
		concursoRegistro = true;

    categoriasConcursoOk = checkCategorias('concurso');

  	//Comprobamos datos obligatorios
		if (categoriasConcursoOk != "")
		{
			alert(categoriasConcursoOk);
			concursoRegistro = false;
			return false;
		}
  	
    if (trim(document.getElementById('codigo_conc').value) == '')
    {
      alert('Debes introducir el código de verificación');
			concursoRegistro = false;
			return false;
     }

  	 document.getElementById('form_registro_directorio_blogs').submit();
	}
}

/* COMBO CATEGORÍAS */
function IrListadoCategoria(categoria)
{
	if (categoria != '')
	{
		document.location.href = '/blogs-de-'+categoria+'/';
	}
}
/* /COMBO CATEGORÍAS */

/* BÚSQUEDA */
function BusquedaBlogsDirectorio(name_form)
{
	name_input = name_form.getElementsByTagName("input");

  terminos_busqueda = name_input[2].value;
  
  if (name_input[1].checked == true)
  {
    patron_busqueda = '/busqueda/premios-20blogs/';
  }
  else //if (name_input[2].checked == true)
  {
    patron_busqueda = '/busqueda/lablogoteca/';
  }

	if(terminos_busqueda != '')
	{
		terminos_busqueda = Reemplazar(terminos_busqueda , '/', '$$');
		document.location.href = patron_busqueda + URLEncode(terminos_busqueda) + '/';
	}
	else
	{
		alert('Por favor, introduce el texto que quieras buscar.');
	}
}
/* /BÚSQUEDA */

/* MÓDULO AGREGADOR DE TOPS  */
function PersonalizarTops (categoria, top)
{
	ActualizaHTMLCode(categoria, top);

	var url_widget = '/widget/tops/' + categoria  + '/' + top + '/';
	oldHTML = $('#capa_modulo').html();
	$.ajax
	({
		type: "GET",
		dataType: "text",
		url: url_widget,
		timeout: 5000,
		success: function(respuesta)
		{
			respuesta = respuesta.replace(/\\'/g, '&#39;').replace(/document.write\('([^']+)'\);/g,'$1').replace(/\\"/g, '"');
			respuesta = respuesta.replace(/<link[^>]+>/g, '').replace(/<script[^>]+><\/script>/g, '');
			$('#capa_modulo').find('#lablogoteca_modulo_top').remove().end().append(respuesta);
			return false;
		},
		error: function(p1,p2,p3)
		{
			$('#capa_modulo').html(oldHTML);
			return false;
		}
 	});
}

function ActualizaHTMLCode(categoria, top)
{
	var codigo_widget = $('#capa_codigo1').val().replace(/widget\/tops\/.*$/, 'widget\/tops\/' + categoria  + '\/' + top + '\/"><\/script>');
	
	$('#capa_codigo1').val(codigo_widget);
	$('#capa_codigo2').val(codigo_widget);
}

function CambiarPaso(num_paso)
{
	if (num_paso == '1')
	{
		$('#paso_1').addClass("activo");
	  $('#paso_2').removeClass("");
	  $('#paso_3').removeClass("");
	}
	if (num_paso == '2')
	{
		$('#paso_1').removeClass("");
	  $('#paso_2').addClass("activo");
	  $('#paso_3').removeClass("");
	}
	if (num_paso == '3')
	{
		$('#paso_1').removeClass("");
	  $('#paso_2').removeClass("");
	  $('#paso_3').addClass("activo");
	}
}
/* /MÓDULO AGREGADOR DE TOPS  */

function checkCategorias(tipoCategorias)
{
	var texto = "";
	var vacio = false;
	if (tipoCategorias == 'blogoteca')
	{
    categorias = document.form_registro_directorio_blogs.elements['categorias[]'];
  }
  else //if (tipoCategorias == 'concurso')
  {
    categorias = document.form_registro_directorio_blogs.elements['categoriaConcurso'];
  }
	
	var i = 0;
	$cont = 0;
	while( (i < categorias.length) )
	{
		if (categorias[i].checked == true)
		{
			vacio = true;
			$cont++;
		}
		i++;
	}

	if (vacio == false)
	{
	   if (tipoCategorias == 'blogoteca')
	   {
		    texto = 'Debes seleccionar alguna categoría de laBlogoteca.';
     }
	   else //if ($tipoCategorias == 'concurso')
	   {
		    texto = 'Debes seleccionar una categoría de Premios 20Blogs.';
     }

		return texto;
	}
	return texto;
}

function onLoadCapaPremios ()
{
  var jObj = $('#desplegable_premios');
  jObj.hover(
    function() {
      jObj.addClass("pactivo");
    },
    function () {   
      jObj.removeClass("pactivo");
    }
  );
}