function setCookie(name, value, expires, path, domain, secure) {
	var date = new Date();
	date.setTime(expires)
	document.cookie= name + "=" + 
		escape(value) + 
		((expires) ? "; expires=" + date.toUTCString() : "") + 
		((path) ? "; path=" + path : "") + 
		((domain) ? "; domain=" + domain : "") + 
		((secure) ? "; secure" : "");
}

function getCookie(name) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return '';
	} else {
		begin += 2;
	}
	var end = document.cookie.indexOf(";", begin);
	if (end == -1) {
		end = dc.length;
	}
	return unescape(dc.substring(begin + prefix.length, end));
}

/* MARCADORES GUIAS CINE Y DOCUS */

function trim(texto) {
	// Elimina blancos al principio y al final del texto y simplifica blancos internos
	return typeof(texto) == 'string' ? texto.replace(/\s+/g, ' ').replace(/^\s*|\s*$/g,'') : texto
}

function indiceVector(valor, vector) {
	var posicion = -1
	for (var i=0; i<vector.length;i++)
		if (valor == vector[i]) 
			posicion = i
	return posicion
}

function anadeClase(nodo, clase) {
	var clases = nodo.className.split(' ')
	if (indiceVector(clase, clases) == -1)
		clases.push(clase)
	nodo.className = trim(clases.join(' '))
}

function tieneClase(nodo, clase) {
	var clases = nodo.className.split(' ')
	return (indiceVector(clase, clases) > -1)
}

function quitaClase(nodo, clase) {
	var clases = nodo.className.split(' ')
	clases.splice(indiceVector(clase, clases), 1)
	nodo.className = trim(clases.join(' '))
}

if (location.pathname.indexOf('/guiacine/')>=0) {
	var marcadores = getCookie('cine201002').split(' ')
} else {
	var marcadores = getCookie('docu201002').split(' ')
}

function conmutaMarcador () {
	// quita/pone la clase a los H1, eliminando/añadiendo el id del evento en/a la cookie
	if (tieneClase(this, 'marcado')) {
		quitaClase(this, 'marcado')
		marcadores.splice(indiceVector(idEvento, marcadores), 1)
	} else {
		anadeClase(this, 'marcado')
		marcadores.push(idEvento)
	}
	// datos a cambiar cada mes: nombre cookie, fecha caducidad
	if (location.pathname.indexOf('/guiacine/')>=0) {
		setCookie('cine201002', trim(marcadores.join(' ')), Date.parse('March, 1 2010 01:00:00'), '/')
	} else {
		setCookie('docu201002', trim(marcadores.join(' ')), Date.parse('March, 1 2010 01:00:00'), '/')
	}
}

if (location.pathname.indexOf('guiacine/p')>=0) {
	// estamos en una ficha, activa y actualiza el H1
	var tituloH1 = document.getElementById('title')
	tituloH1.onclick = conmutaMarcador
	tituloH1.setAttribute('title', 'Pulsa para marcar esta película (se verá marcada en todos los listados)')
	var idEvento = location.pathname.substring(2+location.pathname.lastIndexOf('/p'), location.pathname.lastIndexOf('.'))
	if (indiceVector(idEvento, marcadores) != -1)
		anadeClase(tituloH1, 'marcado')
} if (location.pathname.indexOf('guiadoc/p')>=0) {
	// estamos en una ficha, activa y actualiza el H1
	var tituloH1 = document.getElementById('title')
	tituloH1.onclick = conmutaMarcador
	tituloH1.setAttribute('title', 'Pulsa para marcar este documental (se verá marcado en todos los listados)')
	var idEvento = location.pathname.substring(2+location.pathname.lastIndexOf('/p'), location.pathname.lastIndexOf('.'))
	if (indiceVector(idEvento, marcadores) != -1)
		anadeClase(tituloH1, 'marcado')
} else {
	// no estamos en una ficha: busca los enlaces a marcar y márcalos
	var enlaces = document.getElementsByTagName('a')
	for (var i=0, enlaces; enlace = enlaces[i]; i++) {
		var uri = enlace.getAttribute('href')
		if ((uri.indexOf('guiacine/p')>=0) || (uri.indexOf('guiadoc/p')>=0) || (uri.charAt(0)=='p')) { // lo primero y segundo para IE/Opera, lo tercero para FF
			uriId = uri.substring(2+uri.lastIndexOf('/p'), uri.lastIndexOf('.'))
			if (indiceVector(uriId, marcadores) != -1) {
				anadeClase(enlace, 'marcado')
			}
		}
	}
}

/* FILTRO PAQUETE CANALES */

function filtraPaquete() {
	var opciones, opcion, paquete, eventos, evento, i
	opciones = document.getElementsByTagName('option')
	for (i=0; opcion = opciones[i]; i++)
		if (opcion.selected)
			paquete = opcion.value
	eventos = document.getElementsByTagName('div')
	for (i=0; evento = eventos[i]; i++)
		if (evento.parentNode.nodeName.toLowerCase() == 'div') {
			evento.style.display = 'none' // algo ineficiente pero necesario por problema de redibujado de Firefox
			if ((paquete == '') || (evento.className.indexOf(paquete) != -1))
				evento.style.display = 'block'
		}
}

if (document.location.pathname.indexOf('/d') > 0) { // si es un indice diario
	var paquetes, nodoFiltro, etiquetaSelect, etiquetaOption, infoPaquete, i
	var paquetes = new Array ('cpdig|C+ Digital', 'cpest|C+ Estrenos', 'cpfut|C+ Fútbol', 'cpinf|C+ Infantil', 'cpdoc|C+ Documental', 'cpser|C+ Series', 'cptot|C+ Total', 'dpfam|D+ Familiar', 'dptot|D+ Total', 'bsico|Básico', 'bscin|Básico Cine', 'taqll|Taquillas', 'tqllx|Taquillas X')
	etiquetasH1 = document.getElementsByTagName('h1')
	nodoFiltro = document.createElement('div')
	nodoFiltro.id = 'filtro'
	nodoFiltro.appendChild(document.createTextNode('Filtro:'))
	etiquetaSelect = nodoFiltro.appendChild(document.createElement('select'))
	etiquetaOption = etiquetaSelect.appendChild(document.createElement('option'))
	etiquetaOption.setAttribute('value', '')
	etiquetaOption.appendChild(document.createTextNode('ninguno'))
	for (i=0, paquetes; paquete = paquetes[i]; i++) {
		infoPaquete = paquete.split('|')
		etiquetaOption = etiquetaSelect.appendChild(document.createElement('option'))
		etiquetaOption.setAttribute('value', infoPaquete[0])
		if (infoPaquete[0] == 'dptot')
			etiquetaOption.setAttribute('selected', 'selected')
		etiquetaOption.appendChild(document.createTextNode(infoPaquete[1]))
	}
	etiquetasH1[0].insertBefore(nodoFiltro, etiquetasH1[0].firstChild)
	etiquetaSelect.onchange = filtraPaquete
}

filtraPaquete()
