// Documento JavaScript
var url = document.location.href;
var GA_SECTION = '';
var GA_SUBSECTION = '';
if(url.match(/\/www\.que\.es\/(.*)\//)){
	GA_SECTION = url.match(/\/www\.que\.es\/(.*)\//)[1];
	if(GA_SECTION.match(/(.*)\/(.*)/)){
		GA_SUBSECTION = GA_SECTION.split(/\//g)[1];
		GA_SECTION = GA_SECTION.split(/\//g)[0];
	}
}
if(url=='http://www.que.es/') {
	GA_SECTION = 'Home';
	GA_SUBSECTION = '';
}

var browserName = navigator.appName;
function ImprimirArticulo() {
	window.print();
}

function ilumina(id,className) {
	if(className == null) className = "activo";
	if(objMenu = document.getElementById(id)) {
		objMenu.className = className;
	}
}

function abreMenumas() {
	document.getElementById('mn-mas').className = "mnmenu2-activo";
}

function cierraMenumas() {
	document.getElementById('mn-mas').className = "mnmenu2";
}

function mqMin(elID) {
	alert('Minimizar módulo: En desarrollo...');
	document.getElementById(elID).className = "mqminimizado modQUE";

}
function mqMax(elID) {
	alert('Maximizar módulo: En desarrollo...');
	document.getElementById(elID).className = "mqmaximizado modQUE";
}

// herramientas de artículo
function ntbCloseTolls() {
	document.getElementById('sharethis').style.display = 'none';
	document.getElementById('envialanoticia').style.display = 'none';
	document.getElementById('ntbenviar').className ='';
	document.getElementById('rectificalanoticia').style.display = 'none';
	//document.getElementById('ntbcorregir').className ='';
}

function ntbForms(capa,enlace){
	ntbCloseTolls();
	document.getElementById(capa).style.display = 'block';
	document.getElementById(enlace).className ='activo';
}
function ocultacapasarticulo(capa,enlace){
	ntbCloseTolls();
}

function ntbImprimir() {
	window.print();
}

function votarticulo(valorvoto) {
	alerta = 'Función Voto. Ha votado ' + valorvoto + ' estrellas.';
	document.getElementById('ntbvaloracion').innerHTML = '<div class=votado>Gracias por dar <strong>' + valorvoto + ' </strong> votos</div>';
}

function checkemail(email) {
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	if (filter.test(email)) {
		return true
	}
	else {
		return false;
	}
}

function enviarNoticia() {
	var max_longitud = 120;
	var formulario =  window.document.envio_noticia;

	var nombre = formulario.nombre.value;
	var email_remitente = formulario.email_remitente.value;
	var para = formulario.para.value;
	var email_destinatario = formulario.email_destinatario.value;
	var comentario = formulario.comentario.value;

	if (!nombre || !email_remitente || !para || !email_destinatario)  {
		alert('No ha rellenado todos los campos');
		return;
	}

	if (!checkemail(email_remitente)) {
		alert('El email del remitente no es correcto');
		formulario.email_remitente.focus();
		return;
	}

	if (!checkemail(email_destinatario)) {
		alert('El email del destinatario no es correcto');
		formulario.email_destinatario.focus();
		return;
	}

	/*
	var http = createRequestObject();
	var qs = "nombre=" + nombre + "&email_remitente=" + email_remitente + "&para=" + para;
	qs += "&email_destinatario=" + email_destinatario + "&comentario=" + comentario;
	qs += "&url=" + window.document.location.href;
	*/

	$.get("/backend/enviar_noticia.php",
		{nombre: nombre, email_remitente: email_remitente, para: para, email_destinatario: email_destinatario, comentario: comentario,
		url: window.document.location.href, r: Math.random()},
		function(response) {
			if (response) {
				if (response.indexOf('OK') > -1) {
					var url_mostrar = (window.document.location.href.length > max_longitud) ? window.document.location.href.substr(0, max_longitud) + "..." : window.document.location.href;
					elHTML = "<form action=><div class=envianoticia><div class=envianoticiaOK><p>Su correo ha sido enviado correctamente.</p><p>Página enviada:</p><p class=url><a href='" + window.document.location.href + "' title='" + window.document.location.href + "'>" + url_mostrar + "</a></p></div><div class=clear></div></div><div class='envianoticia-botones boton'></div></form>";
				}
				else {
					elHTML = "<form action=><div class=envianoticia><div class=envianoticiaOK><p>Ha ocurrido un ERROR al enviar la página, por favor intentelo más tarde.</p></div><div class=clear></div></div><div class='envianoticia-botones boton'><a href=javascript:cerrarEnviarNoticia();>Cerrar</a></div></form>";
				}

				window.document.envio_noticia.reset();
				window.document.getElementById('contenidoenvianoticia').innerHTML = elHTML;
			}
			else {
				alert("Ha habido un problema al enviar la noticia, por favor, intentelo más tarde.");
			}
		}
	);
}

function masNoticias(id,accion) {
	if((accion == null) || ((accion != '+') && (accion != '-'))) accion = '+';
	visibles = $('#' + id + ' div:visible').filter(
		function() {
			return (this.id.indexOf(id) == 0);
		}
	);
	ocultos = $('#' + id + ' div:hidden').filter(
		function() {
			return (this.id.indexOf(id) == 0);
		}
	);
	
	var noticias = visibles.length;
	
	if((accion == '+') && (ocultos.length > 0)) {
		$(ocultos[0]).slideDown();
		noticias++;
	}
	if((accion == '-') && (visibles.length > 1)) {
		$(visibles[visibles.length - 1]).slideUp();
		noticias--;
	}
	
	$.cookie(id, noticias, { path: '/', domain: 'que.es', expires: 30 });
	$.post("/backend/portada.php", { columna: id, contenido: noticias } );
}
 

function votarEncuesta(frm, dominio) {
	var id_encuesta = frm.id_encuesta;
	var opciones = frm.id_opcion;
	var id_opcion = 0;
	if((frm.id_encuesta != null) && (opciones != null)) {
		var opcionCheck = false;
		for(j=0;j<opciones.length;j++) {
			if(opciones[j].checked) {
				opcionCheck = true;
				id_opcion = opciones[j].value;
				break;
			}
		}
		if(opcionCheck) {
			if(dominio == null) {
				$.get('/backend/votarEncuesta.php'
					,{id_encuesta: id_encuesta.value, id_opcion: id_opcion}
					,function (respuesta) {
						respArr = respuesta.split('##');
						if(respArr.length == 2) {
							alert(respArr[1]);
							if((respArr[0] != 'ERROR') && (respArr[0].indexOf("/") == 0)) {
								window.location = respArr[0];
							}
						}
					}
				)
			} else { // Encuestas en ozu
				frm.method = 'get';
				frm.target = 'blank';
				frm.action = 'http://www.que.es/backend/votarEncuesta.php?dominio=1&id_encuesta=' + id_encuesta.value + '&id_opcion=' + id_opcion;
				frm.submit();
			}
		}
		else {
			alert('No has seleccionado ninguna opción de la encuesta');
			return false;
		}
	}
	else {
		alert('Faltan datos en la encuesta');
	}
}

function selPestana(contenedor,contenido) {
	if($('#' + contenedor) && ($('#cont-' + contenedor + '-' + contenido))) {
		if($('#pest-' + contenedor)) {
			$('#pest-' + contenedor + ' div').attr("className","pest-off");
			$('#pest-' + contenedor + '-' + contenido).attr("className","pest-on");
		}
		$('#cont-' + contenedor + ' div').hide();
		$('#cont-' + contenedor + '-' + contenido).show();
	}
}

function galeria_foto(url,id_foto) {
	/* $.get('/backend/fotoGaleria.php'
		,{url: url, id_foto: id_foto}
		,function (respuesta) {
			$('#galeria-contenido').html(respuesta);
		}
	) */
	$('#galeria-contenido').load('/backend/fotoGaleria.php?url=' + url + '&id_foto=' + id_foto);
}

function galerias(id_contenedor,id_seccion,id,pag) {
	if(pag == null) pag = 1;
	$.get('/backend/galerias.php'
		,{id_contenedor: id_contenedor, id_seccion: id_seccion, id: id, pag: pag}
		,function (respuesta) {
			respArr = respuesta.split('##');
			if(respArr.length == 2) {
				if(respArr[0] == 'OK') {
					$('#' + id).html(respArr[1]);
				}
			}
		}
	)
}
function texto_google(id_elemento){
	if(id_elemento.value=='Powered by Google') {id_elemento.value='';}	
}

//Infoempleo

function abrir(cadena) {
    var a, cad, cad_aux;
    
    if (cadena == 'trabajo')
    {
        cad = 'http://www.infoempleo.com/trabajo';
        cad_aux = cad;
        
        if (document.getElementById('id_tipo_oferta').checked == true)
        {
		        cad += '/puesto-de-trabajo_Sin-especificar';
        }
        
        if(document.getElementById('F_PClaveTrabajo').value != 'Palabra clave' && document.getElementById('F_PClaveTrabajo').value != '')
        {
		    cad += '/palabra_' + escapeUtf8(document.getElementById('F_PClaveTrabajo').value);
        }
        if (document.getElementById('F_AGeografica').selectedIndex > 0)
        {
            cad += '/en_' + escapeUtf8(document.getElementById('F_AGeografica')[document.getElementById('F_AGeografica').selectedIndex].text); 
            cad += '/selAGeografica_' + document.getElementById('F_AGeografica').selectedIndex;
        }
        if (document.getElementById('F_AFuncional').selectedIndex > 0)
        {
            cad += '/area-de-empresa_' + escapeUtf8(document.getElementById('F_AFuncional')[document.getElementById('F_AFuncional').selectedIndex].text);
            cad += '/selAFuncional_' + document.getElementById('F_AFuncional').selectedIndex;
        }
    }        
    else
    {
        cad = 'http://www.infoempleo.com/cursos/';
        cad_aux = cad;
        
        if(document.getElementById('F_PClaveFormacion').value != 'Palabra clave' && document.getElementById('F_PClaveFormacion').value != '')
        {
		    cad += '/palabra_' + escapeUtf8(document.getElementById('F_PClaveFormacion').value) + '/';
        }
    }
    
    if (cad == cad_aux)
    {
        cad += '/';
    }
    a=window.open(cad);
}



function vaciarCaja(obj)
{
    if (obj.value == 'Palabra clave')
    {
        obj.value = '';
    }
}

function escapeUtf8(cad) 
{
    var contaTextoSeo = 0;
    var cadAux = cad.toString().toLowerCase();
    
    cadAux = cadAux.replace(/á/g,"a");
    cadAux = cadAux.replace(/à/g,"a");
    cadAux = cadAux.replace(/é/g,"e");
    cadAux = cadAux.replace(/è/g,"e");
    cadAux = cadAux.replace(/í/g,"i");
    cadAux = cadAux.replace(/ì/g,"i");
    cadAux = cadAux.replace(/ó/g,"o");
    cadAux = cadAux.replace(/ò/g,"o");
    cadAux = cadAux.replace(/ú/g,"u");
    cadAux = cadAux.replace(/ü/g,"u");
    cadAux = cadAux.replace(/ù/g,"u");
    cadAux = cadAux.replace(/\//g,"-");
    cadAux = cadAux.replace(/ /g,"-");
    cadAux = cadAux.replace(/,/g,"-");
    cadAux = cadAux.replace(/\|/g,"-");
    cadAux = cadAux.replace(/ñ/g,"nn");
    cadAux = cadAux.replace(/--/g,"-");
    
    while (contaTextoSeo < cadAux.length)
    {
        if (cadAux.substring(contaTextoSeo, contaTextoSeo + 1) != '-' && cadAux.substring(contaTextoSeo, contaTextoSeo + 1) != 'ç' &&
        ! (cadAux.substring(contaTextoSeo, contaTextoSeo + 1).charCodeAt() >= 97 && cadAux.substring(contaTextoSeo, contaTextoSeo + 1).charCodeAt() <= 122) &&
        ! (cadAux.substring(contaTextoSeo, contaTextoSeo + 1).charCodeAt() >= 48 && cadAux.substring(contaTextoSeo, contaTextoSeo + 1).charCodeAt() <= 57))
        {
            cadAux = cadAux.replace(cadAux.substring(contaTextoSeo, contaTextoSeo + 1), '');
            contaTextoSeo -= 1;
        }   
        contaTextoSeo += 1;
    }  
    return cadAux;
}

function infoempleo_ajax(provincia){
$.get('http://www.que.es/backend/getInfoempleo.php', 
	{provincia: provincia}, 
	function (data)  {
			var contenido = '';
			var clase = 'impar';
			$(data).length;
			$(data).find('item').each(function(i) {
					if(i<3){
						contenido += '<h3 class="' + clase + '"><a href="' + $(this).find('link').text() + '" target="_blank">' + $(this).find('title').text() + '</a></h3>';
						clase = (clase == 'par') ? 'impar' : 'par';
					}
				}
			);
			$('#contenido-infoempleo').html(contenido);
		}
	);
}

function reload() {
	
	var pagina = document.location.href;
	var v = 1;
	
	if (pagina.indexOf('anker_') != -1) {
		
		var campos = document.location.href.split('?');
		var campos2 = campos[1].split('_');
		
		v = isNaN(parseInt(campos2[1])) ? 1 : (parseInt(campos2[1]) + 1);
		pagina = campos[0];
	}
	
	urlreload = pagina + "?anker_" + v;
	
	window.location = urlreload;
}

