/**
 * Crea una cookie - nombre [valor] [duracion (s)] [ruta] [dominio] [segura (bool)]
 *
 * Notas:
 * - Si no se indica duración (o se establece a false) la cookie se borra al salir
 * - Si no se indica una ruta se asigna la del documento donde ejecutamos el script
 */
function escribirCookie(nombre, valor, duracion, ruta, dominio, segura){ // v2010-03-26
	if(duracion){
		var expires = new Date();
		expires.setUTCMilliseconds(expires.getUTCMilliseconds() + 1000*duracion);
	}

	document.cookie = escape(nombre) + "=" + (valor? escape(valor) : "") +
		(expires ? "; expires=" + expires.toGMTString() : "") +
		(ruta    ? "; path="    + escape(ruta) : "") +
		(dominio ? "; domain="  + escape(dominio) : "") +
		(segura  ? "; secure" : "");
}


/**
 * Devuelve el valor de la cookie indicada o null si no existe
 */
function leerCookie(nombre){ // v2010-03-26
	var re = new RegExp("^(" + escape(nombre) + ")=(.*)$", "i");
	var c = document.cookie.split(/;\s*/);

	for(var i in c){
		if(re.test(c[i])){
			return unescape(re.exec(c[i])[2]);
		}
	}
	return null;
}



/*
 * Precarga de imágenes
 */
function precarga(){ // v2005-05-22
	var argv=precarga.arguments;
	var argc=precarga.arguments.length
	if(!document.precarga_img){
		document.precarga_img=new Array();
	}

	for(var i=0; i<argc; i++){
		var j=document.precarga_img.length;
		document.precarga_img[j]=new Image();
		document.precarga_img[j].src=argv[i];
	}
}


/*
 * Memoriza la opción "Abrir enlaces externos en ventana nueva"
 */
function cambiar_blank(campo){
	if(campo.checked){
		escribirCookie('blank', '1', 86400*365*10, '/');
	}else{
		escribirCookie('blank', '0', 86400*365*10, '/');
	}
	enlaces_externos();
}


/*
 * Procesamos enlaces externos
 */
function enlaces_externos(primera_ejecucion){ // v2009-02-20
	if(!document.getElementsByTagName){
		return;
	}

	var icono='<img class="external" src="/_/img/icono-external.png" alt="[Enlace externo]" title="">';
	var blank=(leerCookie('blank')==null || leerCookie('blank')=='1');

	var enlaces=document.getElementsByTagName('a');
	for(var i=0; i<enlaces.length; i++){
		var a=enlaces[i];
		if(a.getAttribute('href') && a.getAttribute('rel')=='external'){
			a.className='external';

			if(primera_ejecucion){
				a.innerHTML+=icono;
			}

			if(blank){
				a.target='_blank';
				a.title='Enlace externo (nueva ventana)';
			}else{
				a.target='';
				a.title='Enlace externo';
			}
		}
	}
}


/*
 * Memoriza la opción "Ajuste de línea en recortes de código"
 */
function cambiar_overflow(campo){
	if(campo.checked){
		escribirCookie('overflow', '1', 86400*365*10, '/');
	}else{
		escribirCookie('overflow', '0', 86400*365*10, '/');
	}
	ajuste_de_linea();
}


/*
 * Procesamos los cuadros con recortes de código
 */
function ajuste_de_linea(primera_ejecucion){ // v2005-03-13
	if(!document.getElementsByTagName){
		return;
	}

	var overflow=(leerCookie('overflow')==null || leerCookie('overflow')=='1');

	var recortes=document.getElementsByTagName('div');
	for(var i=0; i<recortes.length; i++){
		var obj=recortes[i];
		if(obj.className=='src'){
			if(primera_ejecucion){
				obj.style.height=(obj.offsetHeight+10)+'px'; // Para IE
			}

			if(overflow){
				obj.style.whiteSpace='normal';
				obj.style.overflow='visible';
			}else{
				obj.style.whiteSpace='nowrap';
				obj.style.overflow='auto';
			}
		}
	}
}


/*
 * Construye un URL de tipo mailto a prueba de robots cazadirecciones
 * y redirige a él para que se abra el cliente de correo
 *
 * Argumentos:
 *     string dirección - Con # en lugar de @
 *     string asunto (opcional)
 *     string cuerpo (opcional)
 *
 * Ejemplo:
 *     <a href="javascript:correo('webmaster#demogracia.com', 'Prueba de asunto', 'Cuerpo del mensaje')">Escribir</a>
 *
 */
function correo(direccion, asunto, cuerpo){ // v2005-03-14
	var url="mailto:"+direccion.replace(/#/, '@');

	if(asunto){
		url+="?subject="+escape(asunto);
	}
	if(cuerpo){
		url+="&body="+escape(cuerpo);
	}
	window.location=url;
}


/*
 * Superfish 1.4.8
 */
// hoverIntent.js 
(function(a){a.fn.hoverIntent=function(k,j){var l={sensitivity:7,interval:100,timeout:0};l=a.extend(l,j?{over:k,out:j}:k);var n,m,h,d;var e=function(f){n=f.pageX;m=f.pageY};var c=function(g,f){f.hoverIntent_t=clearTimeout(f.hoverIntent_t);if((Math.abs(h-n)+Math.abs(d-m))<l.sensitivity){a(f).unbind("mousemove",e);f.hoverIntent_s=1;return l.over.apply(f,[g])}else{h=n;d=m;f.hoverIntent_t=setTimeout(function(){c(g,f)},l.interval)}};var i=function(g,f){f.hoverIntent_t=clearTimeout(f.hoverIntent_t);f.hoverIntent_s=0;return l.out.apply(f,[g])};var b=function(q){var o=(q.type=="mouseover"?q.fromElement:q.toElement)||q.relatedTarget;while(o&&o!=this){try{o=o.parentNode}catch(q){o=this}}if(o==this){return false}var g=jQuery.extend({},q);var f=this;if(f.hoverIntent_t){f.hoverIntent_t=clearTimeout(f.hoverIntent_t)}if(q.type=="mouseover"){h=g.pageX;d=g.pageY;a(f).bind("mousemove",e);if(f.hoverIntent_s!=1){f.hoverIntent_t=setTimeout(function(){c(g,f)},l.interval)}}else{a(f).unbind("mousemove",e);if(f.hoverIntent_s==1){f.hoverIntent_t=setTimeout(function(){i(g,f)},l.timeout)}}};return this.mouseover(b).mouseout(b)}})(jQuery);
// superfish.js
(function(b){b.fn.superfish=function(k){var g=b.fn.superfish,j=g.c,f=b(['<span class="',j.arrowClass,'"> &#187;</span>'].join("")),i=function(){var c=b(this),l=d(c);clearTimeout(l.sfTimer);c.showSuperfishUl().siblings().hideSuperfishUl()},e=function(){var c=b(this),m=d(c),l=g.op;clearTimeout(m.sfTimer);m.sfTimer=setTimeout(function(){l.retainPath=(b.inArray(c[0],l.$path)>-1);c.hideSuperfishUl();if(l.$path.length&&c.parents(["li.",l.hoverClass].join("")).length<1){i.call(l.$path)}},l.delay)},d=function(c){var l=c.parents(["ul.",j.menuClass,":first"].join(""))[0];g.op=g.o[l.serial];return l},h=function(c){c.addClass(j.anchorClass).append(f.clone())};return this.each(function(){var c=this.serial=g.o.length;var m=b.extend({},g.defaults,k);m.$path=b("li."+m.pathClass,this).slice(0,m.pathLevels).each(function(){b(this).addClass([m.hoverClass,j.bcClass].join(" ")).filter("li:has(ul)").removeClass(m.pathClass)});g.o[c]=g.op=m;b("li:has(ul)",this)[(b.fn.hoverIntent&&!m.disableHI)?"hoverIntent":"hover"](i,e).each(function(){if(m.autoArrows){h(b(">a:first-child",this))}}).not("."+j.bcClass).hideSuperfishUl();var l=b("a",this);l.each(function(n){var o=l.eq(n).parents("li");l.eq(n).focus(function(){i.call(o)}).blur(function(){e.call(o)})});m.onInit.call(this)}).each(function(){var c=[j.menuClass];if(g.op.dropShadows&&!(b.browser.msie&&b.browser.version<7)){c.push(j.shadowClass)}b(this).addClass(c.join(" "))})};var a=b.fn.superfish;a.o=[];a.op={};a.IE7fix=function(){var c=a.op;if(b.browser.msie&&b.browser.version>6&&c.dropShadows&&c.animation.opacity!=undefined){this.toggleClass(a.c.shadowClass+"-off")}};a.c={bcClass:"sf-breadcrumb",menuClass:"sf-js-enabled",anchorClass:"sf-with-ul",arrowClass:"sf-sub-indicator",shadowClass:"sf-shadow"};a.defaults={hoverClass:"sfHover",pathClass:"overideThisToUse",pathLevels:1,delay:800,animation:{opacity:"show"},speed:"normal",autoArrows:true,dropShadows:true,disableHI:false,onInit:function(){},onBeforeShow:function(){},onShow:function(){},onHide:function(){}};b.fn.extend({hideSuperfishUl:function(){var e=a.op,d=(e.retainPath===true)?e.$path:"";e.retainPath=false;var c=b(["li.",e.hoverClass].join(""),this).add(this).not(d).removeClass(e.hoverClass).find(">ul").hide().css("visibility","hidden");e.onHide.call(c);return this},showSuperfishUl:function(){var e=a.op,d=a.c.shadowClass+"-off",c=this.addClass(e.hoverClass).find(">ul:hidden").css("visibility","visible");a.IE7fix.call(c);e.onBeforeShow.call(c);c.animate(e.animation,e.speed,function(){a.IE7fix.call(c);e.onShow.call(c)});return this}})})(jQuery);
// supersubs.js
(function(a){a.fn.supersubs=function(b){var c=a.extend({},a.fn.supersubs.defaults,b);return this.each(function(){var d=a(this);var e=a.meta?a.extend({},c,d.data()):c;var f=a('<li id="menu-fontsize">&#8212;</li>').css({padding:0,position:"absolute",top:"-999em",width:"auto"}).appendTo(d).width();a("#menu-fontsize").remove();$ULs=d.find("ul");$ULs.each(function(l){var k=$ULs.eq(l);var j=k.children();var g=j.children("a");var m=j.css("white-space","nowrap").css("float");var h=k.add(j).add(g).css({"float":"none",width:"auto"}).end().end()[0].clientWidth/f;h+=e.extraWidth;if(h>e.maxWidth){h=e.maxWidth}else{if(h<e.minWidth){h=e.minWidth}}h+="em";k.css("width",h);j.css({"float":m,width:"100%","white-space":"normal"}).each(function(){var n=a(">ul",this);var i=n.css("left")!==undefined?"left":"right";n.css(i,h)})})})};a.fn.supersubs.defaults={minWidth:9,maxWidth:25,extraWidth:0}})(jQuery);


function prepararMenuDesplegable(){
	$('#menu ul.sf-menu').superfish({
		delay: 800,
		speed: 0, // Otro valor genera un horrible mate negro en IE7
		autoArrows: false,
		dropShadows: false
	}).find("li:has(ul)").addClass("con-submenu");
	$("#menu ul.sf-menu li ul li a").wrapInner("<span></span>");
	
	precarga(
		"/_/img/menu-res.png",
		"/_/img/menu-sub-fondo.png",
		"/_/img/menu-flecha-der.gif",
		"/_/img/menu-sub-res.png",
		"/_/img/menu-visitado.gif"
	);
}


$(function() { 
	enlaces_externos(true);
	ajuste_de_linea(true);
	$(function(){
		if(document.location.hash!=""){
			$(document.location.hash).addClass("target");
		}
	});
}); 
