/**
 * FolioScript.js © 2009-2010 FOLIOServer.com
 */



function mainWindowOnLoad(event) {
    // Youtube etc
    VideoPlayers.load();
    // Helper: IE6:focus, a.target_blank, readCookie(foliocms_fontsize)
    Helpers.load();
    // Lo mas visto, votado y comentado
    Lomas.load();
    // Rotar suscribir / buscar en cabecera
    Suscribir.load();
    
    HighSlideHelper.load();
}



function FolioConsoleLog() {
    var consolajs = $('consolajs');
    if (consolajs != null && typeof consolajs != 'undefined') {
        for( var i = 0; i < arguments.length; i++ ) {
        	consolajs.insert(i+": "+arguments[i]+'<br/>');
        }
    }
	try {
	    if (typeof console != 'undefined' && console) {
            for( var i = 0; i < arguments.length; i++ ) {
                console.log(i+": "+arguments[i]);
            }
	    } else {
	        /*var consolajs = $('consolajs');
	        if (consolajs != null && typeof consolajs != 'undefined') {
	            for( var i = 0; i < arguments.length; i++ ) {
	            	consolajs.insert(i+": "+arguments[i]+'<br/>');
	            }
	        } else {
	        	// console not available
	        }*/
	    }
	} catch (e) {
		// ...
	}
}

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };

function mostrarEnviarAmigo() {
    var enviaramigo = $('enviaramigo');
    if (!enviaramigo.visible()) {
        new Effect.Parallel([
            new Effect.SlideDown(enviaramigo, {sync: true, transition: Effect.Transitions.spring}),
            new Effect.Appear(enviaramigo, {sync: true, from: 0.1})
        ], {
            duration: 0.5,
            queue: { position: 'end', scope: 'enviaramigoscope', limit: 1 }
        });
    } else {
        new Effect.Parallel([
            new Effect.SlideUp(enviaramigo, {sync: true})/*,
            new Effect.Fade(enviaramigo, {sync: true, from: 0.8})*/
        ], {
            duration: 0.33,
            queue: { position: 'end', scope: 'enviaramigoscope', limit: 1 }
        });
    }
}

function esconderEnviarAmigo() {
	Effect.SlideUp('enviaramigo', {afterFinish: function() {
        $('enviaramigoForm').show();
        $('enviaramigoRespuesta').hide();
        $('enviaramigoRespuesta').update();
    }});
}

function enviarAmigo(form) {
    if (!form || form == '') {
        FolioConsoleLog('enviarAmigo(): parametro form no especificado');
        alert('Error interno');
        return false;
    }
    Element.extend(form);
	form.hide();
	$('enviaramigoRespuesta').setStyle({
        'backgroundImage': 'url(images/loadingAnimation.gif)',
        'display': 'block'
    });
	new Ajax.Request('modulos/a_enviaramigo.php', {
	  method: 'post',
	  parameters: form.serialize(),
	  onComplete: function(transport) {
        $('enviaramigoRespuesta').setStyle({'backgroundImage': 'none'});
        var lang = window.lang;
        if (typeof lang == 'undefined') {
        	lang = { "menCerrar": "[&times;]"};
        }
		$('enviaramigoRespuesta').update(transport.responseText+'<a href="javascript:esconderEnviarAmigo()">&nbsp;'+lang.menCerrar+'</a>');
	  }
	});
	return false;
}

function irA(id) {
	new Effect.ScrollTo(id);
}


/*** FOLIO SCROLL GALERIA ***/
var position = 0;
var anchura = 0;
var leftTimeout = null;
var rightTimeout = null;
function FolioScrollStart(e) {


	x = Event.pointerX(e);
	vpx = $('bloque_fotos').viewportOffset();//Element.viewportOffset(bloque);
	porcent = parseInt((x-vpx[0])*100/$('bloque_fotos').getWidth());
	if (porcent >= 75)
	{
		mouseover = true;
		FolioScroll(1);
	} else if (porcent <= 25) {
		mouseover = true;
		FolioScroll(0);
	} else {
		FolioScrollStop();
	}
}

function FolioScrollStop() {
	mouseover = false;
	if (leftTimeout)
		clearTimeout(leftTimeout);
	if (rightTimeout)
		clearTimeout(rightTimeout);
}

function FolioScroll(dir) {
	if (!mouseover)
		return false;
	if (dir == 1)
	{
		if (position > (0 - anchura + $('bloque_fotos').getWidth()))
		{
			position -= 5;
			$('tira').setStyle({left: position+'px'});
			leftTimeout = setTimeout("FolioScroll(1)", 10);
		}
	} else {
		if (position < 0)
		{
			position += 5;
			$('tira').setStyle({left: position+'px'});
			rightTimeout = setTimeout("FolioScroll(0)", 10);
		}
	}
}

function FolioScrollSalta (e) {
	if (this == $('flecha_izq') && position < -110)
	{
		position += 112;
		$('tira').setStyle({left: position+'px'});
	} else if (this == $('flecha_der') && position > (0 - anchura + $('bloque_fotos').getWidth())){
		position -= 112;
		$('tira').setStyle({left: position+'px'});
	}
	if (position < (0 - anchura + $('bloque_fotos').getWidth()))
		position = (0 - anchura + $('bloque_fotos').getWidth());
}
/* FIN folioscroll */


function radioGroupCheck(el) {
	radios = $$('input.radioButtonGroup');
	for(i=0;i<radios.length;i++)
	{
		if (radios[i] != el)
			radios[i].checked = false;
	}
	return true;
}

function guardarOrden(id) {
    var serial = Sortable.serialize(id);
    new Ajax.Request('banners.php', {
      method: 'post',
      parameters: serial,
      onSuccess: function(transport) {
        alert(transport.responseText);
        if (ov)
            ov.hide();
      }
    });
}

function guardaTitulos(id) {
    var serie = $('imagenesTitulos').serialize();
    new Ajax.Updater('imagenes_titulos', 'imagenes.php?'+serie, {
      method: 'post',
      parameters: {guardarTitulos: id, resto: serie},
      onSuccess: function() {
          Effect.Fade('imagenes_titulos');
          recargaFotos(idObjeto, tablaObjeto);
      }
    });
}


function foco(yo) {
	ips = $$('.foco');
	for(i=0;i<ips.length;i++)
	{
		if (ips[i] && ips[i].style && ips[i].style.backgroundColor)
			ips[i].style.backgroundColor = '#ffffff';
	}
	yo.fondo_bak = yo.style.backgroundColor;
	yo.style.backgroundColor = '#FFFFC0';
}

function enfoca() {
	Element.addClassName(this, 'enfocado');
}

function desenfoca() {
	Element.removeClassName(this, 'enfocado');
}


function hilite(luzear, el) {
	if (luzear)
	{
		el.bgstyle_backup = el.parentNode.style.backgroundColor;
		el.style.backgroundColor = '#FFF1AF';
	}
	else
	{
		el.style.backgroundColor = el.bgstyle_backup;
	}
}


function verImagen(id, ext) {
	$('foto_grande').hide();
	$('foto_grande').src = 'upload/img/img_'+id+'.'+ext;
	$('foto_grande').onload = function() {
		Effect.Appear(this);
	};
}

/* esto que es??? */
function jsDebug(lineas) {
	$('jsDebug').style.display = 'block';
	$('jsDebug').innerHTML = lineas;
}


/********** CALENDARIO **********//********** CALENDARIO **********//********** CALENDARIO **********/

function showCalendario(el) {
    if ($('calendario_'+el).style.display != 'none') {
        var effects = [
            new Effect.BlindUp('calendario_'+el)
        ];
    } else {
        if (el == 'llegada' && $('calendario_salida').style.display != 'none') {
            var effects = [
                new Effect.BlindDown('calendario_'+el, {sync: true}),
                new Effect.BlindUp('calendario_salida', {sync: true})
            ];
        } else if (el == 'salida' && $('calendario_llegada').style.display != 'none') {
            var effects = [
                new Effect.BlindDown('calendario_'+el, {sync: true}),
                new Effect.BlindUp('calendario_llegada', {sync: true})
            ];
        } else {
            var effects = [
                new Effect.BlindDown('calendario_'+el)
            ];
        }
    }
    new Effect.Parallel(effects, {duration: 0.2, queue: { position: 'end', scope: 'calendario_scope', limit: 1 }});
}

function pickCalendario(tipo, dia) {
	$('fecha_dia_'+tipo).selectedIndex = dia;
	showCalendario(tipo);
	fixFechas(tipo);
}

function bloquea(el, bloqueo) {
	$(el).bloqueo = bloqueo;
}

function loadCalendario(mes, tipo) {
    FolioConsoleLog(mes, tipo);

	mes = parseInt(mes);
	if (!meses[mes] || (tipo == 'salida' && mes < parseInt($('fecha_mes_llegada').options[$('fecha_mes_llegada').selectedIndex].value))) {
        FolioConsoleLog(meses);
		fixFechas(tipo);
		return 1;
	}


	// fijar dias del mes seleccionables
    var element_id = 'fecha_dia_'+tipo;
	var menu_dias = $(element_id);
	menu_dias.update();
	var llegada_dias = $(tipo+'_dias');
	var tr_dias = '<tr class="dias_semana">';
	for(i=0;i<dias.length;i++)
		tr_dias += '<td>'+dias[i]+'</td>';
	tr_dias += '</tr>';
	llegada_dias.update(tr_dias);
	var dia_semanal = meses[mes].dia_semanal;
	if (dia_semanal == 0)
		dia_semanal = 7;

	var tr = '<tr>';
	for(i=0;i<dia_semanal-1;i++)
		tr += '<td></td>';

	for (i=1;i<=meses[mes].dias;i++)
	{
		var option = new Element('option', { 'value': i }).update(i+'&nbsp;');
		Element.insert(menu_dias, option);

		if (dia_semanal > 7) {
			tr += '<tr>';
			dia_semanal = 1;
		}
		tr += '<td><a href="javascript:pickCalendario(\''+tipo+'\', '+ (i-1) +'); ">'+i+'</a></td>';
		dia_semanal++;
		if (dia_semanal > 7) {
			tr += '</tr>';
			Element.insert(llegada_dias, tr);
			tr = '';
		}
	}
	if (tr != '')
	{
		tr += '</tr>';
		Element.insert(llegada_dias, tr);
		tr = '';
	}


	// copiar a select hermano
	sel_mes = $('fecha_mes_'+tipo);
	sel_mes2 = $('fecha_mes2_'+tipo);
	for (i=0;i<sel_mes.options.length;i++)
	{
		if (sel_mes2.options[i].value == mes)
			sel_mes2.selectedIndex = i;
		if (sel_mes.options[i].value == mes)
			sel_mes.selectedIndex = i;
	}

	fixFechas(tipo);

}



function Mes(numero, dias, nombre, dia_semanal) {
	this.numero = numero;
	this.dias = dias;
	this.nombre = nombre;
	this.dia_semanal = dia_semanal;
}

function sendCalendario() {
	var estadoFecha = fechaSerial();
	if (estadoFecha == 3)
	{
		alert(lang.menFechaNoSecuencial);
		return false;
	} else if(estadoFecha == 2)
	{
		alert(lang.menFechaPasado);
		return false;
	}

}

function fechaSerial(mes_salida) {
	if (!mes_salida || mes_salida == '') {
		mes_salida = 'fecha_mes_salida';
    }
    var mSal = parseInt($F(mes_salida));
    var mEnt = parseInt($F('fecha_mes_llegada'));
    var dSal = parseInt($F('fecha_dia_salida'));
    var dEnt = parseInt($F('fecha_dia_llegada'));
    if ( mEnt < mSal || (mEnt == mSal && dEnt < dSal))
    {
        if ((mEnt == mesAct && dEnt >= diaAct) || mEnt > mesAct)
        {
            return true;
        } else {
            return 2; //pasado
        }
    } else {
        return 3; //salida ant. a llegada
    }
}

function fixFechas(tipo) {
	if (fechaSerial('fecha_mes_salida') == 3 || fechaSerial('fecha_mes2_salida') == 3)
	{

		$('fecha_mes_salida').selectedIndex = $('fecha_mes_llegada').selectedIndex;
		$('fecha_mes2_salida').selectedIndex = $('fecha_mes_llegada').selectedIndex;
		if ($('fecha_dia_salida').options.length > $('fecha_dia_llegada').selectedIndex + 1)//si dia_salida no esta inicializado por alguna razon
		{
			$('fecha_dia_salida').selectedIndex = $('fecha_dia_llegada').selectedIndex + 1;
			if (tipo == 'llegada')
			{

				loadCalendario($('fecha_mes_salida').options[$('fecha_mes_salida').selectedIndex].value, 'salida');
			}
		}
		/*dbgNumeroFixes++;
		jsDebug(dbgNumeroFixes);*/
	}
}


function habitacionCheckSubmit(form) {
	for(i=0;i<form.habitacion.length;i++)
	{
		if (form.habitacion[i].checked)
			return true;
	}
/*	alert('!Debe seleccionar una habitación.');*/
	return true;
}


var CalendarioMejorado = Class.create({
    initialize: function(element, calendarioPrimario) {
        var instancia = this;
        this.element = element;
        this.calendarioPrimario = calendarioPrimario;
        if (calendarioPrimario !== null) {
            calendarioPrimario.setCalendarioSecundario(this);
            this.isCalendarioSecundario = true;//element.hasClassName('EndDate');
        }
        this.calendarioSecundario = null;
        this.isCalendarioPrimario = false;
        this.diaMarcado = null;

        this.sheetContainer = element.select('div.CalendarioMejoradoCalendarios')[0];

        if (element.hasClassName('EffectPopUp')) {
            this.effectType = 'EffectPopUp';
            var offset = element.select('div.CalendarioMejoradoTop')[0].getHeight()
                + element.select('div.CalendarioMejoradoTop')[0].positionedOffset()[1];
            this.sheetContainer.setStyle({
                position: 'absolute',
                top: offset+'px',
                width: (parseInt(element.getWidth()) - 2)+'px',
                height: 'auto'
            });
            if (navigator.userAgent.indexOf('MSIE 6.0') != -1) {
                /* IE6 always displays select elements on top.
                   We hide all visible select elements that are not descendant of our calendar, or our primary calendar.
                   We also tag them with a classname so that later we only reenable those *we* have hidden. */
                this.onPopup = function() {
                    var selects = $$('select');
                    for(var i = 0; i < selects.length; i++) {
                        if (selects[i].visible() && !selects[i].descendantOf(element)
                            && (calendarioPrimario === null || !selects[i].descendantOf(calendarioPrimario.element))) {
                            selects[i].hide();
                            selects[i].addClassName('CalendarioHiddenSelect');
                        }
                    }
                };
                this.onPopout = function() {
                    var selects = $$('select.CalendarioHiddenSelect');
                    for(var i = 0; i < selects.length; i++) {
                        selects[i].show();
                    }
                };
            }
        } else {
            this.effectType = 'EffectSlideDown';
        }

        this.toggleButton = new Element('button', {
            'type': 'button',
            'class': 'ToggleCalendarioButton'
        });
        this.toggleButton.update(new Element('img', {
            'src': 'images/pc/date.png',
            'alt': '[&darr;]'
        }));
        Event.observe(this.toggleButton, 'click', function() {instancia.showCalendario();});
        var topRightDiv = element.select('div.CalendarioMejoradoTopRight')[0];
        topRightDiv.update(this.toggleButton);

        this.daySelect = element.select('select.DaySelect')[0];

        this.monthSelect = element.select('select.MonthSelect')[0];

        this.sheets = element.select('.CalendarioMejoradoCalendarios table');
        for (var i = 0; i < this.sheets.length; i++) {
            this.sheets[i].dayNodes = this.sheets[i].select('td.Dia');
            this.sheets[i].days = new Array();
            for (var j = 0; j < this.sheets[i].dayNodes.length; j++) {
                // the td element will have a property called dayNumber, so we don't lose track inside the onclick event
                this.sheets[i].dayNodes[j].dayNumber = parseInt(this.sheets[i].dayNodes[j].innerHTML);
                if (this.sheets[i].dayNodes[j].dayNumber != 'NaN' && this.sheets[i].dayNodes[j].dayNumber > 0) {
                    Event.observe(this.sheets[i].dayNodes[j], 'click', function() {
                        if (this.hasClassName('Conflicto')) {
                            return;
                        }
                        instancia.selectDay(this.dayNumber, this);
                    });
                }
                this.sheets[i].days[j] = this.sheets[i].dayNodes[j].dayNumber;
            }
        }

        this.nextButton = new Element('button', {
            'type': 'button',
            'class': 'PrevNextButton',
            'style': 'display:none'
        });
        this.nextButton.update(new Element('img', {
            'src': 'templates/'+lang.plantilla+'/images/flechas/go-next.png',
            'alt': '>'
        }));
        Event.observe(this.nextButton, 'click', function() {instancia.nextMonth();});
        topRightDiv.insert(this.nextButton);

        this.prevButton = new Element('button', {
            'type': 'button',
            'class': 'PrevNextButton',
            'style': 'display:none'
        });
        this.prevButton.update(new Element('img', {
            'src': 'templates/'+lang.plantilla+'/images/flechas/go-previous.png',
            'alt': '<'
        }));
        Event.observe(this.prevButton, 'click', function() {instancia.prevMonth();});
        element.select('div.CalendarioMejoradoTopLeft')[0].insert(this.prevButton);

        this.sheetContainer = element.select('div.CalendarioMejoradoCalendarios')[0];

        Event.observe(this.monthSelect, 'change', function() {instancia.selectMonth();});
    },

    onPopup: function() {},
    onPopout: function() {},


    showOnlySelectedMonth: function() {
        for (var i = 0; i < this.sheets.length; i++) {
            if (i != this.monthSelect.selectedIndex) {
                this.sheets[i].hide();
            } else {
                this.sheets[this.monthSelect.selectedIndex].show();

                if (this.isCalendarioSecundario) {
                    if (this.calendarioPrimario.monthSelect.selectedIndex == this.monthSelect.selectedIndex) {
                        var day = parseInt(this.calendarioPrimario.daySelect.options[this.calendarioPrimario.daySelect.selectedIndex].value);
                        for(var dni = 0; dni < this.sheets[i].dayNodes.length; dni++) {
                            if (this.sheets[i].dayNodes[dni].dayNumber <= day) {
                                this.sheets[i].dayNodes[dni].addClassName('Conflicto');
                            } else {
                                this.sheets[i].dayNodes[dni].removeClassName('Conflicto');
                            }
                        }
                    }
                }
            }
        }
    },

    showCalendario: function() {
        this.toggleButton.hide();
        this.daySelect.hide();

        this.nextButton.show();
        this.prevButton.show();
        this.showOnlySelectedMonth();

        if (this.calendarioPrimario !== null) {
            this.calendarioPrimario.hideCalendario();
        }
        if (this.calendarioSecundario !== null) {
            this.calendarioSecundario.hideCalendario();
        }
        if (this.effectType == 'EffectPopUp') {
            this.onPopup();
            new Effect.Parallel([
                new Effect.Appear(this.sheetContainer, { sync: true, from: 0.5, transition: Effect.Transitions.linear }),
                new Effect.SlideDown(this.sheetContainer, { sync: true, transition: Effect.Transitions.spring })
            ], {
                duration: 0.5
            });
        } else {
            Effect.SlideDown(this.sheetContainer, {
                duration: 0.5,
                transition: Effect.Transitions.spring
            });
        }
    },

    hideCalendario: function() {
        if (this.toggleButton.visible()) {
            return;
        }
        this.toggleButton.show();
        this.daySelect.show();
        this.nextButton.hide();
        this.prevButton.hide();

        if (this.effectType == 'EffectPopUp') {
            this.onPopout();
            new Effect.Parallel([
                new Effect.Fade(this.sheetContainer, { sync: true }),
                new Effect.SlideUp(this.sheetContainer, { sync: true })
            ], {
                duration: 0.5
            });
        } else {
            Effect.SlideUp(this.sheetContainer, {
                duration: 0.2
            });
        }
    },

    selectDay: function(day, dayNode) {
        this.daySelect.selectedIndex = 0;
        for (var i = 0; i < this.daySelect.options.length; i++) {
            if (day == this.daySelect.options[i].value) {
                this.daySelect.selectedIndex = i;
                break;
            }
        }

        if (this.calendarioSecundario !== null) {
            this.calendarioSecundario.setMinimumDate(day+1, this.monthSelect.selectedIndex);
        }
        if (this.diaMarcado !== null) {
            this.diaMarcado.removeClassName('Marcado');
        }
        dayNode.addClassName('Marcado');
        this.diaMarcado = dayNode;
        this.hideCalendario();
    },

    nextMonth: function() {
        if (this.monthSelect.length - 1 > this.monthSelect.selectedIndex) {
            this.monthSelect.selectedIndex++;
        }
        this.showOnlySelectedMonth();
    },

    prevMonth: function() {
        if (this.monthSelect.selectedIndex > 0) {
            this.monthSelect.selectedIndex--;
        }
        this.showOnlySelectedMonth();
    },

    getinstanciaIfNotSecondary: function() {
        return this.isCalendarioSecundario ? null : this;
    },

    setCalendarioSecundario: function(calendarioSecundario) {
        this.calendarioSecundario = calendarioSecundario;
        this.isCalendarioPrimario = true;
    },

    selectMonth: function() {
        this.showOnlySelectedMonth();
    },

    setMinimumDate: function(day, monthIndex) {
        if (this.monthSelect.selectedIndex < monthIndex) {
            this.monthSelect.selectedIndex = monthIndex;
        }
        if (this.monthSelect.selectedIndex == monthIndex) {
            if (this.sheets[monthIndex].days[this.sheets[monthIndex].days.length-1] < day) {
                this.monthSelect.selectedIndex = monthIndex + 1;
                this.daySelect.selectedIndex = 0;
            } else if (this.daySelect.options[this.daySelect.selectedIndex].value <= day) {
                for (var i = 0; i < this.daySelect.options.length; i++) {
                    if (this.daySelect.options[i].value == day) {
                        this.daySelect.selectedIndex = i;
                        break;
                    }
                }
            }
        }
        this.showOnlySelectedMonth();
    }
});

/*^^^^^^^^^ CALENDARIO ^^^^^^^^^*//*^^^^^^^^^ CALENDARIO ^^^^^^^^^*//*^^^^^^^^^ CALENDARIO ^^^^^^^^^*/




/********** CARRITO **********//********** CARRITO **********//********** CARRITO **********/

function anadirCarrito(id, selects, opciones) {

	var opciones_seleccionadas = [];
	if (opciones && selects) {
		for(var i=0;i<selects.length;i++) {
			opciones_seleccionadas.push(opciones[selects[i].value]);
		}
		var opciones_get = opciones_seleccionadas.toJSON();
	} else {
		var opciones_get = '';
	}
	if (typeof id == 'undefined' || !id || id == 0) {
		return false;
	}

	carritoLoading(true);

	new Ajax.Request('modulos/carrito.php?anadir='+id+'&opciones='+opciones_get+'&'+Math.random(),
	{
		method: 'get',
		onSuccess: leerCesta
    });
}
function verCarrito() {
	new Ajax.Request('modulos/carrito.php?'+Math.random(), {
    	method: 'get',
		onSuccess: leerCesta
	});
}
function eliminarCarrito(id, element) {
	if (!confirm(txtSeguroEliminar))
		return false;
	if (isNaN(id))
		return false;

    Element.setOpacity(element, 0.2);
    Element.setStyle({'backgroundColor': '#f77'});
    new Ajax.Request('modulos/carrito.php?eliminar='+id+'&'+Math.random(), {
    	method: 'get',
		onSuccess: function(transport) {
			//element.style.display = 'none'; /* ni pare ni none ni na */
			leerCesta(transport);
		}
	});
}

function actualizarCarrito(form) {
	var inputs = $$('input.cantidades');
	for(i=0;i<inputs.length;i++)
	{
		if (inputs[i].value <= 0)
			inputs[i].value = 1;
	}
	var cantidades = $(form).serialize();
	$('carrito').update('<img src="images/flechas_animadas.gif" alt="Cargando..." />');
    new Ajax.Request('modulos/carrito.php?actualizar=true&'+Math.random(),
	{
		method: 'get',
		parameters: cantidades,
		onSuccess: leerCesta
	});
}

function leerCesta(transport) {
	var retorno = transport.responseText.evalJSON(true);
	if (retorno.modulo && $('carrito')) {
		$('carrito').update(retorno.modulo);
		carritoLoading(false);
	}

	if (retorno.cesta && $('cesta_productos'))
		$('cesta_productos').update(retorno.cesta);
	if ($('total') && retorno.total != 'undefined') {
		$('total').update(numeroEuropeo(retorno.total));
	}
	if ($('subtotal') && retorno.subtotal != 'undefined') {
		$('subtotal').update(numeroEuropeo(retorno.subtotal));
	}
	if ($('total_iva') && retorno.iva != 'undefined') {
		$('total_iva').update(numeroEuropeo(retorno.iva));
	}

	if (!retorno.vacia) {
		if ($('boton_paypal'))
			$('boton_paypal').disabled = false;
		if ($('boton_actualizar'))
			$('boton_actualizar').disabled = false;
	} else {
   		if ($('boton_lista'))
			$('boton_lista').onclick = null;
		if ($('boton_paypal'))
			$('boton_paypal').disabled = true;
		if ($('boton_actualizar'))
			$('boton_actualizar').disabled = true;
	}

}

function carritoLoading(cargando) {
	if (cargando) {
		$('carrito_cargando').show();
		$('carrito_cargando').clonePosition($('carrito'));
		$('carrito').hide();
	} else {
		$('carrito_cargando').hide();
		$('carrito').show();

	}
}


function numeroEuropeo(nStr)
{
    nStr = (nStr+'').replace(',','.');
    var euroStr = parseFloat(nStr).toFixed(2);
    euroStr = (euroStr+'').replace('.',',');
    try {
        if (!simbolo_moneda || simbolo_moneda == null || simbolo_moneda == 'undefined') {
            simbolo_moneda = '';
        }
        return euroStr + ' ' + simbolo_moneda;
    } catch (e) {
        return euroStr;
    }
}

function consolajs(msg) {
	$('consolajs').insert('<div>'+msg+'</div>');
}


function enviarPedido(el, enviar) {
	if (!enviar)
	{
		Effect.BlindDown('email');
		el.disabled = true;
		Effect.BlindUp(el);
		$('input_email').observe('click', seleccionaTodo);
		$('input_email').select();
	}
}

function formularioPedido(img, operacion, texto) {
	Effect.DropOut('operaciones');
	Effect.BlindDown('email');
	$('fakeform').action += operacion;
	$('fakeform_button_img').src = img;
	$('fakeform_button_texto').update(texto);
}

function seleccionaTodo(event) {
	var el = event.element();
	el.activate();
}



function categoria(titulo, texto, orden, id, op, tabla) {
	if (!op || op == undefined || op == null || op == "")
		op = "";
	if (op == "delete")
	{
		if (!confirm('¿Está seguro que quiere borrar la categoría?'))
			return 0;
	}
	new Ajax.Updater('categorias', 'categorias.php?seccion='+tabla+'&id='+id+'&op='+op+'&'+Math.random(),
	{
		method: 'get',
		insertion: Insertion.Bottom,
		onComplete: function() {
	  }
    });

	if (op == "delete")
	{
		$('categorias').removeChild($('categoria_'+id));
	}

}

function nuevaCategoria(el_id) {
	new Ajax.Updater(el_id, 'categorias.php?op=crear&'+Math.random(),
	{
		method: 'get',
		insertion: Insertion.Bottom,
		onComplete: function() {
	  }
    });

}

function subircategoria(id) {
	el = $('categoria_'+id);
	if (!el)
		return 1;

	if (!el.previous() || el.previous().className != "categoria")
		return 1;
	for (var i=0;i<idiomas.length;i++)
		tinyMCE.execCommand('mceRemoveControl',false,'p_texto_'+idiomas[i]+'_'+id);
	el.parentNode.insertBefore(el, el.previous());
	for (var i=0;i<idiomas.length;i++)
		tinyMCE.execCommand('mceAddControl',false,'p_texto_'+idiomas[i]+'_'+id);
}
function bajarcategoria(id) {
	el = $('categoria_'+id);
	if (!el)
		return 1;

	next = el.next();
	if (!next || next.className != "categoria")
		return 1;

	for (var i=0;i<idiomas.length;i++)
		tinyMCE.execCommand('mceRemoveControl',false,'p_texto_'+idiomas[i]+'_'+id);
	next.insert({after: el});
	for (var i=0;i<idiomas.length;i++)
		tinyMCE.execCommand('mceAddControl',false,'p_texto_'+idiomas[i]+'_'+id);
}

/*** IMAGENES ***/
function recargaFotos(id, tabla) {
	new Ajax.Updater('listaImagenes', 'imagenes.php', {
	  method: 'get',
	  parameters: { random: Math.random(), id: id, tabla: tabla },
/*	  insertion: Insertion.Bottom,	*/
	  onSuccess: function() {
	  	setTimeout('hacerSortable('+id+', "'+tabla+'")', 1000);
	  }
	});

}

/* del panel ? */
function hacerSortable(idCosa, tablaCosa) {
	orden = Sortable.create("listaImagenes",
		 {tag:'div',only:'imagenDeLista',constraint:'horizontal',containment:["listaImagenes"],constraint:false});
	Droppables.add('papelera', {
		accept: 'imagenDeLista',
		onDrop: function (element) {
			if (confirm('¿Está seguro que quiere borrar la foto?'))
			{
				new Ajax.Updater('listaImagenes', 'imagenes.php', {
				  method: 'post',
				  parameters: { random: Math.random(), id: idProducto, id_foto: element.id, tabla: nombreTabla, op: 'delete' },
				  onSuccess: function() {
				  	setTimeout('hacerSortable('+idProducto+', "'+nombreTabla+'")', 10);
				  }
				});
				element.parentNode.removeChild(element);
			}
		}
	} );
}

function EVaMayusculas() {
	this.value = this.value.toUpperCase();
	if ($('ref_ok'))
		$('ref_ok').value = 0;
}



/*^^^^^^^^^ CARRITO ^^^^^^^^^*//*^^^^^^^^^ CARRITO ^^^^^^^^^*//*^^^^^^^^^ CARRITO ^^^^^^^^^*/


/* readcookie: from quirksmode. Used to set text zoom in client cookie */
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function zoomBaseText(className, id) {
    var element = $(id);
    if (typeof element == 'undefined' || element == null) {
        element = document.body;
        Element.extend(element);
    }

    element.removeClassName('font_size_small');
    element.removeClassName('font_size_normal');
    element.removeClassName('font_size_large');

    element.addClassName(className);

    document.cookie = 'foliocms_fontsize='+className+'; path=/';

    return false;
}

function desplazar(id) {
    Effect.ScrollTo(id, {duration: 0.5});
}



// Tabla ayuda a cambiar los campos segun filtro seleccionado
var Tabla = Class.create(
{
  initialize: function(tablaId, anyoInicio, anyoFin, string_del, string_al) {
    this.tablaId = tablaId;
    this.anyoInicio = anyoInicio;
    this.anyoFin = anyoFin;
    this.selectElement = $(this.tablaId+'_filtro');
    this.camposElement = $(this.tablaId+'_campos');
    this.string_del = string_del;
    this.string_al = string_al;
  },
  makeTextInput: function(tipo) {
      var el = new Element('input', {
          'type': 'text',
          'name': 'filtros[\''+tipo+'\']'
      });
      return el;
  },
  makeFechaInput: function(num) {
      if (typeof num == 'undefined') {
          nombre = 'fecha';
          post_array = false;
      } else {
          nombre = 'rango_fechas';
          post_array = true;
      }
      var el = new Element('span', {
          'class': 'fechaInput'
      });

      var el_dia = new Element('select', {'name': 'filtros[\''+nombre+'\'][0]'+(post_array?'[]':'')});
      for(var i = 1; i < 32; i++) {
          el_dia.insert(new Element('option', {'value': i+''}).update(i+''));
      }

      var el_mes = new Element('select', {'name': 'filtros[\''+nombre+'\'][1]'+(post_array?'[]':'')});
      for(var i = 1; i < 13; i++) {
          el_mes.insert(new Element('option', {'value': i+''}).update(i+''));
      }

      var el_anyo = new Element('select', {'name': 'filtros[\''+nombre+'\'][2]'+(post_array?'[]':'')});
      for(var i = this.anyoInicio; i <= this.anyoFin; i++) {
          el_anyo.insert(new Element('option', {'value': i+''}).update(i+''));
      }
      if (lang.g_fecha_americana == 1) {
          el.insert(el_mes);
          el.insert(el_dia);
      } else {
          el.insert(el_dia);
          el.insert(el_mes);
      }
      el.insert(el_anyo);
      return el;
  },
  cambiaFiltro: function(el) {
    if (typeof el.options == 'undefined') {
        el = this;
    }
    this.tipoFiltro = el.options[el.selectedIndex].value;
    if (this.tipoFiltro == 'fecha') {
        this.camposElement.update(this.makeFechaInput());
    } else if (this.tipoFiltro == 'rango_fechas') {
        this.camposElement.update(new Element('span', {'class': 'separadorFechas'}).update(this.string_del));
        this.camposElement.insert(this.makeFechaInput(1));
        this.camposElement.insert(new Element('span', {'class': 'separadorFechas'}).update(this.string_al));
        this.camposElement.insert(this.makeFechaInput(2));
    } else {
        this.camposElement.update(this.makeTextInput(this.tipoFiltro));
    }
  }
});

function cambiaFiltro(el) {
    if (typeof el.options == 'undefined') {
        el = this;
    }
    tabla.cambiaFiltro(el);
}
/******** fin TABLA **************/

function inputClear(el, defaultValue) {
    if (el.value == defaultValue) {
        el.value = '';
        return false;
    }
    return true;
}
function checkNotEmptyAndClearDefault(del, defaultValue) {
    return inputClear(el, defaultValue) && el.value != '';
}


/* FolioForm.js */
var regex=/^[A-Z]+$/;
var regex2=/^[a-z]+$/;
var lockup = 'TRWAGMYFPDXBNJZSQVHLCKE';

function esNumerico(cadena) {
    var checkOK = "0123456789";
    var cadenaNumerica = true;

    for (i=0; i < cadena.length; i++)
    {
        var caracterNumerico = false;
        for (j=0; j < checkOK.length; j++)
        {
            if (checkOK.charAt(j) == cadena.charAt(i))
            {
                caracterNumerico = true;
                break;
            }
        }
        if (!caracterNumerico)
        {
            return false;
        } else {
            cadenaNumerica = true;
        }
    }
    return cadenaNumerica;
}

function cambiaFormato(e, formato) {
    if (!formato && e)
        formato = this.options[$('tipodoc').selectedIndex].value;
    if (formato == 'dni')
    {
        $('formato').innerHTML = formato_dni;
    } else if (formato == 'nie')
    {
        $('formato').innerHTML = formato_nie;
    } else if (formato == 'pas')
    {
        $('formato').innerHTML = formato_pas;
    }
    checkFormato(null, $('documento'));
}

function checkFormato(e, el) {
    if (!el)
        el = this;
    var formato = $('tipodoc').value;
    var numero = el.value;
    var correcto = true;



    /* quitamos basurilla */
    if (numero)
    {
        numero = numero.toUpperCase();
        el.value = numero;
    }

    if (numero == "")
    {
        correcto = false;
    } else if (formato == 'dni')
    {
        if (numero && numero.length == 9)
        {
            for(i=0;i<numero.length;i++)
            {
                if(isNaN(numero.charAt(i)) && i < 8)
                {
                    correcto = false;
                    break;
                } else if (i > 8)
                {
                    correcto = false;
                    break;
                } else if (i == 8 && !regex.test(numero.charAt(i)))
                {
                    correcto = false;
                    break;
                }
            }
        } else {
            correcto = false;
        }
    } else if (formato == 'nie')
    {
        if (numero && numero.length == 9 && numero.charAt(0) == 'X')
        {
            for(i=1;i<numero.length;i++)
            {
                if(isNaN(numero.charAt(i)) && i < 8)
                {
                    correcto = false;
                    break;
                } else if (i > 8)
                {
                    correcto = false;
                    break;
                } else if (i == 8 && !regex.test(numero.charAt(i)))
                {
                    correcto = false;
                    break;
                }
            }
        } else {
            correcto = false;
        }
    } else if (formato == 'pas')
    {
        nif_start = -1;
        if(numero.length < 6)
            correcto = false;
    } else {

    }


    if (!correcto)
    {
        Element.addClassName(el, 'erroneo');
        $('nif').value = "";
    }
    else
    {
        Element.removeClassName(el, 'erroneo');
        if (formato == 'dni')
            $('nif').value = numero.substr(0,8)+lockup.charAt(numero.substr(0,8) % 23);
        else if (formato == 'nie')
        {
            var nif = numero.substr(1,7)+lockup.charAt(numero.substr(1,7) % 23);
            if ('X'+nif != numero)
                alert('Su NIE no parece tener la letra correcta, compruébe que tanto los números como la letra son correctos.');
            else
                $('nif').value = '0'+nif;
        }
        else
            $('nif').value = "";
    }
}

function cambiaProvincias(paisId) {
    $('provincia_div').style.display = 'none';
    new Ajax.Updater('provincia', 'modulos/a_provincias.php', {
        parameters: {pais: paisId, seleccionado: provincia_seleccionada},
        onComplete: function() {
            Effect.Appear('provincia_div');
            //$('provincia_div').style.display = 'block';
            setTimeout("noCero($('provincia'))", 1000);
            provincia_seleccionada = 0;
        }
    });
}

function checkMinimo(el, minlength, carPermitidos) {
    if (!minlength)
        minlength = 0;
    if (el.value.length > minlength)
    {

        Element.removeClassName(el, 'erroneo');
    }
    else
        Element.addClassName(el, 'erroneo');
}

function checkTarjeta(e) {
    var code;
    if (!e) var e = window.event;
    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which;
    //var character = String.fromCharCode(code);
    //alert('Character was ' + code);

    var numero = this.value.toString();
    var correcto = true;

       if (code == 8 && this.value.length == 0)
    {
        for(i=1;i<4;i++)
        {
            if (this.id.endsWith(i.toString()))
            {
                antId = $(this.id.replace(i.toString(), (i-1).toString()));
                if (antId)
                {
                    if (antId.setSelectionRange) {
                        antId.focus();
                        antId.setSelectionRange(4,4);
                    }
                    else if (antId.createTextRange) {
                        var range = antId.createTextRange();
                        range.collapse(true);
                        range.moveEnd('character', 4);
                        range.moveStart('character', 4);
                        range.select();
                    }
                    break;
                }
            }
        }
    }
    else if (code == 39)
    {
        for(i=0;i<3;i++)
        {
            if (this.id.endsWith(i.toString()))
                $(this.id.replace(i.toString(), (i+1).toString())).focus();
        }
    }

    if (numero.length != 4)
    {
        correcto = false;
    } else
    {
        for(i=0;i<numero.length;i++)
        {
            if(isNaN(numero.charAt(i)))
            {
                correcto = false;
                break;
            }
        }
    }
    if (!correcto)
        Element.addClassName(this, 'erroneo');
    else
    {
        Element.removeClassName(this, 'erroneo');
           if (this.value.length == 4 && code != 8)
        {
            for(i=0;i<3;i++)
            {
                if (this.id.endsWith(i.toString()))
                    $(this.id.replace(i.toString(), (i+1).toString())).focus();
            }
        }

    }
}

function checkCad() {
    var numero = this.value.toString();
    var correcto = true;

    if (numero.length != 2)
        correcto = false;
    else
    {
        for(i=0;i<numero.length;i++)
        {
            if(isNaN(numero.charAt(i)))
            {
                correcto = false;
                break;
            }
        }
    }
    if (!correcto)
        Element.addClassName(this, 'erroneo');
    else
        Element.removeClassName(this, 'erroneo');
}

function noCero(el) {
    if (el.options && el.options.length > 0 && el.options[el.selectedIndex].value != 0)
        Element.removeClassName(el, 'erroneo');
    else
        Element.addClassName(el, 'erroneo');
}

/* not good at all */
function checkFormValido(el) {
    return true;
}

function toggleNumeroTarjeta(cb) {
    cb.disabled = true;
    if (cb.checked) {
        Effect.BlindDown('datos_tarjeta');
    } else {
        Effect.BlindUp('datos_tarjeta');
    }
    setTimeout("$('cb').disabled = false;", 1000);
}



var NewsItem = {
	id: 0,
	vote: function(e) {
	    var element = Event.element(e);
	    
	    var value = 0;
	    var parent = element;
	    while(parent != null && parent.tagName.toUpperCase() == "SPAN") {
	    	value++;
	    	parent = parent.up();
	    }
	    
	    if (isNaN(value) || value < 1) {
	        return false;
	    } else if (value > 5) {
	    	value = 5;
	    }
	    $('votarInfo').update(lang.w_votar_enviando);
	    new Ajax.Request('modulos/votar.php', {
	        method: 'post',
	        parameters: {votar: value, noticia: NewsItem.id},
	        onSuccess: function(transport) {
	            if (transport.responseText.match(/OK/)) {
	                $('votarInfo').update(lang.w_votar_ok);
	                try {
		                element.descendants().each(function(child) {
		                	child.removeClassName("active");
		                	element.stopObserving('click');
		                });
		                var parent = element;
		                while(parent != null && parent.tagName.toUpperCase() == "SPAN") {
		                	parent.addClassName("active");
		                	parent = parent.up();
		                }
		                if (parent != null) {
		                	parent.stopObserving('click');
		                }
	                } catch (e) {
	                	FolioConsoleLog(e);
	                }
	            } else if (transport.responseText.match(/REPETICION/)) {
	                $('votarInfo').update(lang.w_votar_repeticion);
	            } else {
	                $('votarInfo').update(lang.w_votar_error);
	            }
	        },
	        onFailure: function() {
	            $('votarInfo').update(lang.w_votar_error);
	        }
	    });	
	},
	addView: function(id) {
		if (typeof id == 'undefined' || parseInt(id) == 'NaN') {
			return;
		}
		// make a silent XHR. It doesn't matter if it fails.
		new Ajax.Request('modulos/votar.php', {
		        method: 'post',
		        parameters: {noticia: id}
	    });
	},
	addImageFooters: function(images) {
		var imgs = $$('#TEXTO_NOTICIA img');
		
		for(var i = 0; i < images.length; i++) {
			var img = null;// = $('IMAGEN_INSERTADA_'+images[i].id);
			for(var ii = 0; ii < imgs.length; ii++) {
				var src = "upload/img/periodico/img_"+images[i].id+"."+images[i].ext;
				if (imgs[ii].readAttribute("src") == src) {
					img = imgs[ii];
					break;
				}
			}
			
	        if (img === null) {
	            continue;
	        }
	        
	        img.writeAttribute("title", images[i].titulo);
	        if (!img.complete || (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0)) {
	        	Event.observe(img, 'load', NewsItem.addFooter);
	        } else {
	        	NewsItem.addFooter(img);
	        }
		}
	},
	addFooter: function(img) {
		if (typeof img.tagName == 'undefined') {
			var img = this;
		}
		
		var wrapper = Element.extend(document.createElement('div'));
		var dimensions = Element.getDimensions(img);
		wrapper.setStyle({
			position: 'relative',
			width: dimensions.width+"px",
			height: dimensions.height+"px"
		});
		Element.insert(img, {before: wrapper});
		
		if (img.hasClassName('RichTextAlignLeft')) {
            var alignClassName = 'RichTextAlignLeft';
        } else if (img.hasClassName('RichTextAlignRight')) {
            var alignClassName = 'RichTextAlignRight';
        } else {
            var alignClassName = 'RichTextAlignCenter';
        }
        img.removeClassName(alignClassName);
        wrapper.addClassName(alignClassName);
		
		wrapper.insert(img);
		var footer = Element.extend(document.createElement('div'));
		footer.update(Element.extend(document.createElement('cite')).update(img.title));
		footer.addClassName('pieDeFoto');
		wrapper.insert(footer);
	}
};


var Helpers = {
    load: function() {
        // *:focus for IE6
        if (typeof enfoca != 'undefined') {
            focos = $$('.foco');
            for(i=0;i<focos.length;i++)    {
            	Event.observe(focos[i], 'focus', enfoca);
                Event.observe(focos[i], 'blur', desenfoca);
            }
        }
        // target_blank
        var anchors_blank = $$('a.target_blank');
        for (var i = 0; i < anchors_blank.length; i++) {
            anchors_blank[i].writeAttribute('target', '_blank');
        }
        // tamanyo texto
        var cookie = readCookie('foliocms_fontsize');
        if (cookie) {
            Element.extend(document.body);
            if (cookie == 'font_size_small') {
                document.body.addClassName('font_size_small');
            } else if (cookie == 'font_size_large') {
                document.body.addClassName('font_size_large');
            }
        }
        // check logo - test stability before releasing
        /*Event.observe(window, 'load', function() {
	        var poweredby = $('poweredby');
	        if (!Helpers.isVisible(poweredby)) {
	        	Helpers.forceLogo();
	        }
        });*/
    },
    isVisible: function(element) {
    	/* check if hidden by style
    	 * Checked in FF, WK, IE8
    	 */
    	if (typeof element == 'undefined' || !element || element.style.visibility == 'hidden'
    			|| element.style.display == 'none' || element.getHeight() == 0 || element.getWidth() == 0
    			|| element.getOpacity() != '1') {
    		return false;
    	}
    	
    	/* check if it is covered by another element
    	 * Checked in FF, WK, IE8
    	 * Skip if we cannot find any element at position
    	 */
    	/* This is NOT reliable AT ALL
    	if (document.elementFromPoint) {
    		var pos = element.cumulativeOffset();
    		pos.left = Math.floor(pos.left+(element.getWidth()/2));
    		pos.top = Math.floor(pos.top+(element.getHeight()/2));
    		try {
		    	var elementAtPosition = document.elementFromPoint(pos.left, pos.top);
		    	if (elementAtPosition != element && elementAtPosition.id != element.id
		    		&& !Element.descendantOf(elementAtPosition, element)) {
		    		alert(elementAtPosition.innerHTML);
		    		return false;
		    	}
    		} catch (e) { }
    	}*/
    	/* check if inside body */
    	var bodyPos = Element.cumulativeOffset(document.body);
    	bodyPos.right = bodyPos.left + (document.body.scrollWidth > document.documentElement.scrollWidth ? document.body.scrollWidth : document.documentElement.scrollWidth);
    	bodyPos.bottom = bodyPos.top + (document.body.scrollHeight > document.documentElement.scrollHeight ? document.body.scrollHeight : document.documentElement.scrollHeight);
    	var elPos = element.cumulativeOffset();
    	elPos.right = elPos.left + element.getWidth();
    	elPos.bottom = elPos.top + element.getHeight();
    	if (elPos.left < bodyPos.left || elPos.right > bodyPos.right
    			|| elPos.top < bodyPos.top || elPos.bottom > bodyPos.bottom) {
    		return false;
    	}
    	return true;
    },
    forceLogo: function() {
    	
    	var info = new Element('a');
    	info.insert('Powered By FOLIOePRESS');
    	info.writeAttribute('title', 'To remove this notice, place or uncomment the following snippet in pie.php: {$powered_by}, or contact us if you need to remove it permanently');
    	info.setStyle({
    		display: 'block',
    		padding: '4px',
    		margin: '10px auto',
    		color: '#999',
    		font: '16px bold Arial,sans-serif',
    		backgroundColor: '#fff',
    		width: '970px'
    	});
    	info.writeAttribute('href', 'http://folioserver.com');
    	document.body.appendChild(info);
    }
};

var VideoPlayers = {
    load: function() {
        var youtubes = $$('dl.youtube_player');
        for(var i = 0; i < youtubes.length; i++) {
            var dds = youtubes[i].getElementsByTagName('dd');
            var videoId = dds[0].innerHTML.strip();
            var elementId = dds[1].innerHTML.strip();
            var width = dds[2].innerHTML.strip();
            var height = dds[3].innerHTML.strip();
            var tipo = dds[4].innerHTML.strip();
            dds[5].id = elementId; // htmlpurifier removes id tags
            if (tipo == 'YOUTUBE') {
                var url = 'http://www.youtube.com/v/'+videoId;
            } else if (tipo == 'GOOGLEVIDEO') {
                var url = 'http://video.google.es/googleplayer.swf?docid='+videoId+'&hl=es&fs=true';
            } else if (tipo == 'VIMEO') {
                var url = 'http://vimeo.com/moogaloop.swf?clip_id='+videoId+'&server=vimeo.com&show_title=1&show_byline=1&show_portrait=0&color=&fullscreen=1';
            }
            var expressInstall = null;
            if (width >= 310 && height >= 137) {
            	expressInstall = 'libs/js/expressInstall.swf';
            }
            swfobject.embedSWF(url,
                elementId,
                width,
                height,
                '8',
                expressInstall,
                null,
                { allowScriptAccess: 'always', allowFullScreen: 'true' },
                null,
                VideoPlayers.onLoad
            );
        }
    },
    onLoad: function(e) {
        if (!e.success) {
            $($(e.id).parentNode).addClassName('error');
            FolioConsoleLog('Error cargando video: '+e.id, e);
        }
    },
    loadHtml5: function(src, parent) {
    	parent.innerHTML = '';
    	var std = document.createElement("source");
    	std.src = src;
    	var video = document.createElement('video');
    	video.src = src;
    	video.style.width = '100%';
    	video.style.height = '100%';
    	video.appendChild(std);
    	parent.appendChild(video);
    }
};

var Suscribir = {
    load: function (event) {
        var a_suscribir = $('a_suscribir');
        if (a_suscribir) {
            if (a_suscribir.getAttribute('href').endsWith('#')) {
                Event.observe(a_suscribir, 'click', Suscribir.toggle);
            } else {
            }
        //} else {
        }
    },
    /* this method can be called as javascript:Suscribir.toggle(this), or used as event handler */
    toggle: function (arg) {
        if (arg) {
            try {
                Event.stop(arg);
            } catch (e) {
                FolioConsoleLog(e);
            }
        }
        if (!$('cab_suscribir').visible()) {
            if (this.update) {
                this.update(lang.g_buscar);
            } else {
                Element.update(arg, lang.g_buscar);
            }
            var effects = [
                new Effect.SlideDown('cab_suscribir', { sync: true }),
                new Effect.BlindUp('cab_buscador', { sync: true })
            ];
        } else {
            if (this.update) {
                this.update(lang.g_suscribirse);
            } else {
                Element.update(arg, lang.g_suscribirse);
            }
            var effects = [
                new Effect.BlindDown('cab_buscador', { sync: true }),
                new Effect.SlideUp('cab_suscribir', { sync: true })
            ];
        }
        new Effect.Parallel(effects, {
            duration: 0.25,
            queue: { position: 'end', scope: 'suscribirScope', limit: 1 }
        });
    }
};


var Galeria = {
    load: function () {
        var as = $('pelicula').childElements();
        for(var i = 0; i < as.length; i++) {
            Event.observe(as[i], 'click', Galeria.peliculaClick);
        }
        $('ventana').setStyle({ overflow: 'hidden'});

        $('btn_atras').observe('click', Galeria.adelanteClick);
        $('btn_adelante').observe('click', Galeria.atrasClick);
    },
    peliculaClick: function (event) {
        var a = Event.findElement(event, 'a');
        var imagenes = $('imagen_galeria').childElements();
        for(var i = 0; i < imagenes.length; i++) {
            if (imagenes[i].id == a.readAttribute('rel')) {
                imagenes[i].show();
            } else if (imagenes[i].visible()) {
                imagenes[i].hide();
            }
        }
        Event.stop(event);return false;
    },
    atrasClick: function (event) {
        var left = $('pelicula').positionedOffset()[0];
        if (left > 662 - $('pelicula').getWidth()) {
            new Effect.Move('pelicula', { x: -104, mode: 'relative', duration: 0.1, transition: Effect.Transitions.sinoidal, queue: { position: 'end', scope: 'pelicula', limit: 0 } });
        }
        Event.stop(event);
    },
    adelanteClick: function (event) {
        var left = $('pelicula').positionedOffset()[0];
        if (left < 16) {
            new Effect.Move('pelicula', { x: 104, mode: 'relative', duration: 0.1, transition: Effect.Transitions.sinoidal, queue: { position: 'end', scope: 'pelicula', limit: 0 } });
        }
        Event.stop(event);
    }
};

var Lomas = {
    load: function() {
        var anchors_lomas = $$('#BANNER_LOMAS .tabs a');
        for (var i = 0; i < anchors_lomas.length; i++) {
            Event.observe(anchors_lomas[i], 'click', Lomas.click);
        }
    },
    click: function(e) {
        this.blur();
        if (this.hasClassName('activa')) {
            return;
            Event.stop(e);
        }
        var activeTabId = null;
        var anchors_lomas = $$('#BANNER_LOMAS .tabs a');
        for (var i = 0; i < anchors_lomas.length; i++) {
            if (anchors_lomas[i] != this && anchors_lomas[i].hasClassName('activa')) {
                anchors_lomas[i].removeClassName('activa');
                activeTabId = anchors_lomas[i].id;
                break;
            }
        }
        this.addClassName('activa');

        Lomas.switchTab(this.id, activeTabId);
    },
    switchTab: function(newActiveTabName, currentActiveTabName) {
        var currentTab = $(Lomas.getPanelIdFromTabId(currentActiveTabName));
        currentTab.parentNode.appendChild(currentTab);
        new Effect.Parallel([
            new Effect.SlideUp(currentTab, {sync: true}),
            new Effect.BlindDown(Lomas.getPanelIdFromTabId(newActiveTabName), {sync: true})
        ], {
            duration: 0.5,
            queue: { position: 'end', scope: 'lomasClick', limit: 0 }
        });
    },
    getPanelIdFromTabId: function(tabId) {
        if (tabId == 'lomas_anchor_visto') {
            return 'lomas_visto';
        } else if (tabId == 'lomas_anchor_votado') {
            return 'lomas_votado';
        } else if (tabId == 'lomas_anchor_comentado') {
            return 'lomas_comentado';
        }
    }
};

function cambiaTitulos(id) {
    Effect.Appear('imagenes_titulos', {from: 0.5, duration: 0.5});
    new Ajax.Updater('imagenes_titulos', 'imagenes.php', {
            method: 'post',
            parameters: {titulos: id},
            onSuccess: function() {
        }
    });
}


var InputStyler = {
    plantilla: '',
    spriteSize: 16,
    initOnWindowLoad: function(plantilla, spriteSize) {
        InputStyler.plantilla = plantilla;
        if (spriteSize > 0) {
            InputStyler.spriteSize = spriteSize;
        }
        Event.observe(window, "load", function() { InputStyler.init(); });
    },
    init: function () {
        InputStyler.image = 'templates/'+InputStyler.plantilla+'/images/inputstyles/'+'overlay.png';
        InputStyler.blankImage = 'templates/'+InputStyler.plantilla+'/images/inputstyles/'+'blank.gif';
        var inputs = $$('input[type=radio],input[type=checkbox]');
        for(var i = 0; i < inputs.length; i++) {
            InputStyler.applyStylesToElement(inputs[i]);
        }
    },
    applyStylesToElement: function(element) {
        if (element.getAttribute("type") != "radio" && element.getAttribute("type") != "checkbox") {
            return;
        }
        element.overlay = new Element('img', {'src': InputStyler.blankImage});
        element.overlay.setStyle({
            backgroundImage: 'url('+InputStyler.image+')',
            backgroundPosition: '0px 0px',
            backgroundRepeat: 'no-repeat',
            width: (InputStyler.spriteSize+2)+'px',
            height: InputStyler.spriteSize+'px',
            cursor: 'pointer'
        });
        element.parentNode.insertBefore(element.overlay, element);

        InputStyler.hideElement(element);

        Event.observe(element, 'click', InputStyler.inputOnClick);
        Event.observe(element.overlay, 'click', function() { InputStyler.inputOnClick(element); });
        InputStyler.inputOnClick(element);

        if (element.getAttribute("type") == "checkbox") {
            element.overlay.setStyle({
                backgroundPosition: '0px '+(InputStyler.spriteSize * -2)+'px'
            });
        }
    },
    hideElement: function(element) {
        element.setOpacity(0);
        var elementWidth = element.getWidth();
        /* The element must stay at its place, be invisible, and must not take up any space.
           We will set its opacity to zero and set its right margin to minus its width.
           To get its width is tricky: if it is hidden or inside a hidden element, we put a placeholder at the
           element's position for later, store some style properties, make it absolutely positiones so the page doesn't
           flicker, show it, and move it to the body.
           At this point element.getWidth() should work, we then replace the placeholder with element and reset it's
           styles.
        */
        if (elementWidth == 0) {
            // keep track of element's setup
            var parent = element.parentNode;
            var dummy = new Element('span');
            element.parentNode.insertBefore(dummy, element);
            var originalStyle = {
                position: element.getStyle('position') != null ? element.getStyle('position') : 'relative',
                top: element.getStyle('top') != null ? element.getStyle('top') : 'auto',
                display: element.getStyle('display') != null ? element.getStyle('display') : 'inline',
                width: 'auto'
            };
            // show it at body
            element.setStyle({position: 'absolute', top: '-100px', display: 'inline'});
            document.body.appendChild(element);
            elementWidth = element.getWidth();
            // restore element
            parent.replaceChild(element, dummy);
            element.setStyle(originalStyle);
            // if we still don't succeed, give up.
            if (elementWidth == 0) {
                elementWidth = '15';
            }
        }
        element.setStyle({
            cursor: 'pointer',
            margin: '0',
            marginRight: '-'+elementWidth+'px'
        });
    },
    // arg: may be an element, of an event, in which case we will use "this" as element.
    inputOnClick: function(arg) {
        if (arg.type && arg.type == "click") {
            arg = this;
        }
        if (!arg.overlay) {
            return;
        }
        if (arg.getAttribute("type") == "radio") {
            if (!this.checked && arg.getAttribute("checked") != "checked") {
                return;
            }
            var backgroundPositions = {on: '0px '+(InputStyler.spriteSize * -1)+'px', off: '0px 0px'};
            arg.overlay.setStyle({
                backgroundPosition: backgroundPositions.on
            });
            // siblings are actually radiobuttons of the same group (they are grouped by the "name" attribute)
            var siblings = $$('input[name='+arg.name+']');
            for(var i = 0; i < siblings.length; i++) {
                if (siblings[i] == arg || !siblings[i].overlay) {
                    continue;
                }
                siblings[i].overlay.setStyle({
                    backgroundPosition: backgroundPositions.off
                });
            }
        } else if (arg.getAttribute("type") == "checkbox") {
            var backgroundPositions = {on: '0px '+(InputStyler.spriteSize * -3)+'px', off: '0px '+(InputStyler.spriteSize * -2)+'px'};
            arg.overlay.setStyle({
                backgroundPosition: arg.checked ? backgroundPositions.on : backgroundPositions.off
            });
        }

    }
};


FolioCaptcha = {
    initOnWindowLoad: function() {
        Event.observe(window, 'load', FolioCaptcha.init);
    },
    init: function(e) {
        FolioCaptcha.captcha = $('captcha');
        if (!FolioCaptcha.captcha) {
            FolioConsoleLog('Captcha not found!');
            return;
        }
        Event.observe(FolioCaptcha.captcha, 'load', FolioCaptcha.captchaOnload);
        if (!FolioCaptcha.captcha.visible()) {
            FolioCaptcha.captchaOnload();
        }
    },
    captchaOnload: function(e) {
        if (!FolioCaptcha.captcha) {
            return;
        }
        new Effect.Appear(FolioCaptcha.captcha, {
            duration: 0.5,
            queue: {position: 'end', scope: 'captcha_scope', limit: 1}
        });
    }
};


FolioFormHandler = {
    initOnWindowLoad: function(id, message) {
        FolioFormHandler.message = message;
        Event.observe(window, 'load', function() {
            FolioFormHandler.form = $(id);
            FolioFormHandler.inputs = FolioFormHandler.form.getElementsByClassName("obligatorio");
            Event.observe($(id), 'submit', FolioFormHandler.onSubmit);
        });
    },
    onSubmit: function(e) {
        var error = false;
        var errores = FolioFormHandler.form.getElementsByClassName('error_msg');
        for (i=0;i<errores.length;i++) {
            errores[i].remove();
        }

        for(i = 0; i < FolioFormHandler.inputs.length; i++) {
            Element.extend(FolioFormHandler.inputs[i]);
            if (FolioFormHandler.inputs[i].value.length < 3) {
                FolioFormHandler.formError(FolioFormHandler.inputs[i], FolioFormHandler.message, !error); // ASI SOLO SALTA AL PRIMER ERROR
                error = true;
            }
        }

        if (error === true) {
            Event.stop(e);
            return false;
        }
    },
    formError: function(el, msg, jump) {
        var siguiente = el.next();
        if (!siguiente || siguiente == null || typeof siguiente == 'undefined') {
            var siguiente = el.up().next();
        }
        if (!siguiente || siguiente == null || typeof siguiente == 'undefined') {
            var siguiente = el.up().up().next();
        }
        if (!siguiente || siguiente == null || typeof siguiente == 'undefined') {
            var siguiente = el.up().up();
        }

        if (el.parentNode.className == 'select_load') {
            //Element.extend(el.parentNode.parentNode);

            var span = new Element('span', {'class': 'error_msg'}).update(msg);
            el.parentNode.parentNode.appendChild(span);
            span.className = 'error_msg';
        } else {
            //Element.extend(el.parentNode);
            /* IE solo quiere ver la clase si la asignamos despues de insertar en DOM */
            var span = new Element('span', {'class': 'error_msg'}).update(msg);
            el.parentNode.appendChild(span);
            span.className = 'error_msg';
        }
        if (jump) {
            if (el.previous()) {
                new Effect.ScrollTo(el.previous());
            } else {
                new Effect.ScrollTo(el);
            }
        }
    }
};

/**
 *  Agenda helper. Load previous/next month with AJAX
 */
FolioAgenda = {
    prevMonth: function() {
        FolioAgenda.changeMonth(-1);
    },
    nextMonth: function() {
        FolioAgenda.changeMonth(1);
    },
    changeMonth: function(dir) {
        var agenda = $('AGENDA');
        agenda.setOpacity(0.25);
        new Ajax.Updater(agenda, 'modulos/agenda.php', {
            method: 'get',
            parameters: { meses: dir },
            onComplete: function() {
                agenda.setOpacity(1.0);
            }
        });
        return false;
    }
};

/**
 *  Reads documents stylesheet, rules and rules properties.
 *  Must-Do: read *specific* stylesheet, not just the first one.
 *  getAudioPlayerStyles() parses the styles used for the audioplayer plugin thingy.
 */
StyleSheetReader = {
    getStyle: function (selector, property, asHex) {
        if (document.styleSheets[0].cssRules) {
            rules = document.styleSheets[0].cssRules;
        } else if (document.styleSheets[0].rules) {
            rules = document.styleSheets[0].rules;
        }
        for (var i = 0; i < rules.length; i++){
            if (rules[i].selectorText.toLowerCase() == selector.toLowerCase()) {
                if (property) {
                    return asHex ? StyleSheetReader.rgbStringToHex(rules[i].style[property]) : rules[i].style[property];
                }
                return rules[i];
            }
        }
        return null;
    },
    rgbStringToHex: function(string) {
        var parts = string.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
        if (parts == null) {
            if (string.charAt(0) == '#') {
                return string.substr(1);
            }
            return string;
        }
        for (var i = 1; i <= 3; ++i) {
            parts[i] = parseInt(parts[i]).toString(16);
            if (parts[i].length == 1) {
                parts[i] = '0' + parts[i];
            }
        }
        return parts[1]+parts[2]+parts[3];
    },
    getAudioPlayerStyles: function() {
        var styles = {
            bg: StyleSheetReader.getStyle('.AudioPlayer_Main', 'backgroundColor', true),
            text: StyleSheetReader.getStyle('.AudioPlayer_Main', 'color', true),
            leftbg: StyleSheetReader.getStyle('.AudioPlayer_Left', 'backgroundColor', true),
            lefticon: StyleSheetReader.getStyle('.AudioPlayer_Left', 'color', true),
            rightbg: StyleSheetReader.getStyle('.AudioPlayer_Right', 'backgroundColor', true),
            righticon: StyleSheetReader.getStyle('.AudioPlayer_Right', 'color', true),
            rightbghover: StyleSheetReader.getStyle('.AudioPlayer_Right:hover', 'backgroundColor', true),
            righticonhover: StyleSheetReader.getStyle('.AudioPlayer_Right:hover', 'color', true),
            loader: StyleSheetReader.getStyle('.AudioPlayer_Loader', 'backgroundColor', true),
            skip: StyleSheetReader.getStyle('.AudioPlayer_Skip', 'color', true),
            volslider: StyleSheetReader.getStyle('.AudioPlayer_Volume', 'color', true),
            voltrack: StyleSheetReader.getStyle('.AudioPlayer_Volume', 'backgroundColor', true)
        };
        return styles;
    }
};

UserUpload = {
    maxImages: 5,
    fileUploads: [],
    initOnWindowLoad: function() {
        Event.observe(window, "load", function() { UserUpload.init(); });
    },
    init: function() {
        UserUpload.multiUploadElement = $('multiUpload');
        UserUpload.userImagesElement = $('userImages');
        UserUpload.userImages = UserUpload.userImagesElement.childElements();
        UserUpload.multiUpload = $('multiUpload');

        if (UserUpload.userImages.length > 0) {
            UserUpload.makeSortable();
        }

        UserUpload.addUploadInput();
    },
    addUploadInput: function() {
        if (UserUpload.userImages.length >= (5 - UserUpload.fileUploads.length)) {
            FolioConsoleLog('User has set 5 images ('+UserUpload.userImages.length+' present, '+UserUpload.fileUploads.length+' new)');
            return false;
        }
        for(var i = 0; i < UserUpload.fileUploads.length; i++) {
            if (!UserUpload.fileUploads[i].setByUser) {
                FolioConsoleLog('Found unset element.');
                return false;
            }
        }

        var uploadInputBlock = new Element('div', {
            'style': 'display: none'
        });

        var uploadInputElement = new Element('input', {
            'type': 'file',
            'name': 'images[]'
        });
        uploadInputElement.observe('change', function() {
            uploadInputElement.setByUser = true;
            UserUpload.addUploadInput();
        });
        uploadInputBlock.insert(uploadInputElement);

        var uploadInputCancel = new Element('button', {
            'type': 'button'
        });
        uploadInputCancel.insert(new Element('img', { 'src': 'templates/'+lang.plantilla+'/images/iconos_cabecera/cross.png'}));
        uploadInputCancel.observe('click', function() {
            UserUpload.removeUploadInput(uploadInputBlock);
        });
        uploadInputBlock.insert(uploadInputCancel);

        UserUpload.fileUploads.push(uploadInputElement);
        UserUpload.multiUpload.insert(uploadInputBlock);
        Effect.Appear(uploadInputBlock, {
            afterFinish: UserUpload.resetMultiUploadHeight
        });
        return true;
    },
    removeUploadInput: function(uploadInputBlock) {
        UserUpload.multiUpload.setStyle({
            height: UserUpload.multiUpload.getHeight()+'px'
        });
        Effect.DropOut(uploadInputBlock, {
            afterFinish: function() {
                uploadInputBlock.remove();
                for(var i = 0; i < UserUpload.fileUploads.length; i++) {
                    if (UserUpload.fileUploads[i] === uploadInputBlock.firstDescendant()) {
                        UserUpload.fileUploads.splice(i, 1);
                    }
                }

                if (!UserUpload.addUploadInput()) {
                    UserUpload.resetMultiUploadHeight();
                }
            }
        });
    },
    resetMultiUploadHeight: function() {
        UserUpload.multiUpload.setStyle({
            height: 'auto'
        });
    },
    makeSortable: function() {
        if (typeof Sortable == 'undefined') {
            FolioConsoleLog('Sortable not loaded');
            return;
        }
        Sortable.create(UserUpload.userImagesElement, {
            tag: 'div',
            constraint: false,
            snap: true,
            overlap: 'horizontal'
        });
        for(var i = 0; i < UserUpload.userImages.length; i++) {
            UserUpload.userImages[i].style.cursor = 'move';
        }
    }
};


FilmGallery = {
	step: 100,
	position: 0,
	anchura: 0,
	frequency: 0.5,
	mouseOver: false,
	initOnWindowLoad: function() {
		Event.observe(window, "load", FilmGallery.init);
	},
	init: function() {
		// fade in big image on load
		FilmGallery.bigImage = $('imagen_grande');
		FilmGallery.bigImage.observe('load', FilmGallery.fadeInBigImage);
		
		// show thumb in big image
		var anchors = $$('#rollo a');
		for(var i=0;i<anchors.length;i++) {
			Event.observe(anchors[i], 'click', FilmGallery.thumbClick);
		}
		
		// film
		FilmGallery.thumbs = $$('#rollo img');
		FilmGallery.ventanaTira = $('ventana_tira');
		if (FilmGallery.thumbs.length > 4 && FilmGallery.ventanaTira) {
		    FilmGallery.ventanaTira.setStyle({overflow: 'hidden', height: '120px'});
		    var buttonLeft = $('b_iz');
		    var buttonRight = $('b_de');
		    buttonLeft.show();
		    buttonRight.show();
		    FilmGallery.anchura = $('rollo').getWidth();
            ventana_tira_width = FilmGallery.ventanaTira.getWidth();
            
            buttonLeft.observe('mouseover', FilmGallery.scrollRight); // yes.
            buttonLeft.observe('mouseout', FilmGallery.scrollStop);
            buttonRight.observe('mouseover', FilmGallery.scrollLeft);
            buttonRight.observe('mouseout', FilmGallery.scrollStop);
        }
	},
	thumbClick: function(e) {
		$('imagen_grande').hide();
		$('imagen_grande').src = this.href;
		this.blur();
		Event.stop(e);
	},
	scrollLeft: function() {
		FilmGallery.mouseOver = true;
		FilmGallery.scrollFilm(true);
	},
	scrollRight: function() {
		FilmGallery.mouseOver = true;
		FilmGallery.scrollFilm(false);
	},
	scrollFilm: function(izq, repeat) {
		if (izq) {
			distancia = FilmGallery.step * -1;
		} else {
			distancia = FilmGallery.step;
		}
		if (FilmGallery.mouseOver) {
			if (FilmGallery.anchura + FilmGallery.position + distancia < ventana_tira_width) {
				distancia = (FilmGallery.anchura + FilmGallery.position - ventana_tira_width) * -1;
				if (distancia >= 0) {
					return false;
				}
			} else if (FilmGallery.position + distancia >= 0) {
				distancia = FilmGallery.position * -1;
				if (distancia <= 0) {
					return false;
				}
			}
			new Effect.Move('rollo', {
				x: distancia,
				mode: 'relative',
				duration: FilmGallery.frequency,
				transition: Effect.Transitions.linear,
				queue: {
					position: 'end',
					scope: 'rollo',
					limit: 0
				},
				afterFinish: function() { FilmGallery.scrollFilm(izq); }
			});
			FilmGallery.position += distancia;
			//setTimeout("FilmGallery.scrollGaleria("+izq+")", (FilmGallery.frequency * 1000)+1);
		}
	},
	scrollStop: function() {
		FilmGallery.mouseOver = false;
	},
	fadeInBigImage: function(e) {
		Effect.Appear(FilmGallery.bigImage, {queue: {scope: 'foto_grande', position: 'end', limit: 0}});
	}
};


CategoriasRecursivas = {
	despliegaSubmenu: function(el) {
		Element.extend(el);
		if (!el.next()) {
			return false;
		}
		if (!el._CategoriasRecursivasScopeName) {
			el._CategoriasRecursivasScopeName = 'CategoriasRecursivasScopeName_'+(Math.random()*1000);
		}
		Effect.toggle(el.next(), 'blind', {
			duration: 0.2,
			queue: {
				scope: el._CategoriasRecursivasScopeName,
				limit: 1
			}
		});
	}
};

Popup = {
	POPUP_TYPE_IMAGE: 1,
	POPUP_TYPE_FLASH: 2,
	POPUP_TYPE_HTML: 0,
	domTreeReadyCallback: null,
	setup: function(content, timeout, type, width, height, url) {
		Popup.content = content;
		Popup.timeout = timeout;
		Popup.type = type;
		Popup.width = width;
		Popup.height = height;
		Popup.url = url;
	},
	open: function(e) {
		Element.extend(document.body);
		document.body.addClassName('fpopup_showing');
		document.body.parentNode.style.overflow = 'hidden';
		
		Popup.fpopup = new Element('div', {id: 'fpopup'});
		var viewportDimensions = document.viewport.getDimensions();
		Popup.fpopup.setStyle({
			width: viewportDimensions.width+'px',
			height: viewportDimensions.height+'px'
		});
		Event.observe(window, 'resize', Popup.resize);
		
		var fpopup_head = new Element('div', {id: 'fpopup_head'});
		Popup.fpopup.insert(fpopup_head);
		var fpopup_head_title = new Element('h2', {id: 'fpopup_title'});
		fpopup_head_title.insert(lang.g_titulo);
		fpopup_head.insert(fpopup_head_title);
		var fpopup_head_close = new Element('a', {href: 'javascript:void(0)', id: 'fpopup_close'});
		fpopup_head_close.insert(lang.w_popup_close);
		fpopup_head_close.observe('click', Popup.close);
		fpopup_head.insert(fpopup_head_close);
		
		document.body.appendChild(Popup.fpopup);
		var headerHeight = fpopup_head.getHeight();
		Popup.fpopup.setStyle({
			display: 'none',
			top: document.viewport.getScrollOffsets()[1]+'px'
		});

		var fpopup_container = new Element('table');
		fpopup_container.setStyle({
			width: '100%',
			verticalAlign: 'middle',
			textAlign: 'center',
			height: (Popup.fpopup.getHeight() - headerHeight)+'px'
		});
		
		var fpopup_container_inner = new Element('td');
		fpopup_container.insert(new Element('tbody').insert(new Element('tr').insert(fpopup_container_inner)));
		fpopup_container_inner.insert(Popup.getContent());
		Popup.fpopup.insert(fpopup_container);
		
		if (Popup.domTreeReadyCallback != null) {
			Popup.domTreeReadyCallback();
		}

		Effect.Appear(Popup.fpopup, {
			duration: 0.6
		});
		if (Popup.timeout > 0) {
			setTimeout(Popup.close, Popup.timeout);
		}
	},
	getContent: function() {
		if (Popup.type == Popup.POPUP_TYPE_FLASH) {
			var videoContainer = new Element('div', {id: 'fpopup_flashcontainer'});
			Popup.domTreeReadyCallback = function() {
				swfobject.embedSWF(Popup.content,
					'fpopup_flashcontainer',
					Popup.width,
					Popup.height,
		            '8',
		            null,
		            {clickTag: Popup.url},
		            { allowScriptAccess: 'always', allowFullScreen: 'false' },
		            null,
		            Popup.swfOnLoad
		        );
			};
			return videoContainer;
		} else {
			return Popup.content;
		}
	},
	close: function(e) {
		Effect.Fade(Popup.fpopup, {
			duration: 0.2,
			afterFinish: function(ef) {
				Event.stopObserving(window, 'resize', Popup.resize);
				document.body.removeClassName('fpopup_showing');
				document.body.parentNode.style.overflow = 'auto';
				document.body.removeChild(Popup.fpopup);
				Popup.fpopup = null;
			}
		});
	},
	swfOnLoad: function() {
		// swf has been loaded
	},
	resize: function(e) {
		var viewportDimensions = document.viewport.getDimensions();
		Popup.fpopup.setStyle({
			width: viewportDimensions.width+'px',
			height: viewportDimensions.height+'px'
		});
	}
};

HighSlideHelper = {
	load: function() {
		if (typeof hs == 'undefined')  {
			return;
		}
		hs.graphicsDir = 'libs_oss/'+hs.graphicsDir;
		hs.showCredits = false;
		
		/*if (!document.getElementsByTagName){ return; }
		var anchors = document.getElementsByTagName('a');

		// loop through all anchor tags
		for (var i=0; i<anchors.length; i++){
			var anchor = anchors[i];

			var relAttribute = String(anchor.getAttribute('rel'));

			// use the string.match() method to catch 'lightbox' references in the rel attribute
			if (anchor.getAttribute('href') && (relAttribute.toLowerCase().match('lightbox'))){
				anchor.onclick = function() {
					return hs.expand(this);
				}
			}
		}*/
	}
};
