//================================================\\
//                  start add-ons                 \\
//================================================\\

// ==============================================================
// Crossbrowser Get computed styles 
// (c)2004 Sergi Meseguer http://zigotica.com/ under CC license:
// http://creativecommons.org/licenses/by-sa/2.0/
// ==============================================================
var  CSS = {
	setStyle : function(node,rule,value){
		if(typeof(node)=="string")  node = document.getElementById(node);
		node.style[rule] = value;
	},
	
	getStyle : function(node,rule){
		if(typeof(node)=="string")  node = document.getElementById(node);
		if(rule=="width") return CSS.getW(node);
		else if(rule=="height") return CSS.getH(node);
		else {
			if (window.getComputedStyle) return window.getComputedStyle(node, null)[rule];
			else return node.currentStyle[rule];
		}
	},

	getH : function(node){
		if(typeof(node)=="string")  node = document.getElementById(node);
		return node.offsetHeight;
	},

	getW : function(node){
		if(typeof(node)=="string")  node = document.getElementById(node);
		return node.offsetWidth;
	}
}

var Extras = {

	daSource : "",
	showtxt : "",
	hidetxt : "",
	
	popup : function(where,w,h,t,l) {
		if (!t) t=0;
		if (!l) l=0;
		window.open( where, 'popupwindow', 'width='+w+', height='+h+', top='+t+', left='+l+', scrollbars=no, resizable=no'); 
	},

	// Events methods by Scott Andrew (www.scottandrew.com):
	addEvent : function(obj, evType, fn, useCapture){
		if (obj.addEventListener){
			obj.addEventListener(evType, fn, useCapture);
			return true;
		} 
		else if (obj.attachEvent){
			var r = obj.attachEvent("on"+evType, fn);
			return r;
		} 
		else {
			return false;
		}
	}, 
	
	removeEvent : function(obj, evType, fn, useCapture){
		if (obj.removeEventListener){
			obj.removeEventListener(evType, fn, useCapture);
			return true;
		} 
		else if (obj.detachEvent){
			var r = obj.detachEvent("on"+evType, fn);
			return r;
		} 
		else {
			return false;
		}
	},

	// Function adapted from Dan Pupius (pupius.co.uk):
	getElementsByClass : function(className,node) {
		if(!node) node=document;
		var refTags = document.all ? document.all : node.getElementsByTagName("*");
		var retVal = new Array();
		for(var i=0;i<refTags.length;i++) {
			if(refTags[i].className == className) 
			retVal.push(refTags[i]);
		}
		return retVal; 
	},

	// adds line numbers to code sections:
	numberCodeTags : function(){
		var PRE = document.getElementsByTagName('pre'); 
		var nl = /\n+/mg;
		for (var i = 0; i < PRE.length; i++) {
			var t = PRE[i].innerHTML;
			//mozilla/ff cannot select all lines of a code element that is inside a pre element:
			if(document.addEventListener && !window.opera) {
				Extras.getCodeText(PRE[i]);
			}
			
			//will only work in mozilla+op (IE replaces \n by a space so its useless):
			var NL = Extras.getMatchArray(t,nl);
			if(NL) {
				var numeros = "";
				for (var lineas = 1; lineas < NL; lineas++) numeros += lineas +"\n";
				PRE[i].innerHTML += "<div class='lines'>"+numeros+"</div>";
			}
		}
	},
	
	// matches a regexp to a string, returns array
	getMatchArray : function(myString,myRegExp){
		return myString.match(myRegExp).length;
	},

	// FF  hack to make easier select all lines of a code element that is inside a pre element:
	getCodeText : function(obj){
		var color = CSS.getStyle(obj.firstChild,"color");
		var bgcolor = CSS.getStyle(obj.firstChild,"backgroundColor");
		if(bgcolor=="transparent") bgcolor="white";
		obj.onmouseover = function(){
			obj.firstChild.style.color = bgcolor;
			obj.firstChild.style.backgroundColor = color;
		}
		obj.onmouseout = function(){
			obj.firstChild.style.color = color;
			obj.firstChild.style.backgroundColor = bgcolor;
		}
	},

	// Links to Cites from BlockQuotes, modified from http://simon.incutio.com
	extractCites: function() {
		var url = location.href;
		if(url.indexOf("/eng/") != -1) {
			Extras.daSource = "(Source)";
		}
		else {
			Extras.daSource = "(Fuente)";
		}
		var quotes = document.getElementsByTagName('blockquote'); 
		for (var i = 0; i < quotes.length; i++) {
			var cite = quotes[i].getAttribute("cite");
			if (typeof cite == "string" && cite !="") {
				newspan = document.createElement("span");
				newspan.appendChild(document.createTextNode(" "));
				newspan.className = "source";
					source = document.createElement("a");
					source.setAttribute("href", cite);
					source.setAttribute("title", cite);
					source.appendChild(document.createTextNode(Extras.daSource));
				newspan.appendChild(source);
				quotes[i].lastChild.appendChild(newspan);
			}
		}
	},
	
	reTarget : function(){ 
		var external = document.getElementsByTagName("a"); 
		for (var k=0; k<external.length; k++){
			if (external[k].href) {
			var url = external[k].href; 
				if (url.indexOf(document.domain) == -1 && url.indexOf("javascript:") == -1 && url.indexOf("mailto:") == -1) 
				{
					var ExternalTxt = "(External link / Enlace externo)";
					external[k].target = "_blank";
					external[k].title += " " + ExternalTxt;
					//external[k].innerHTML += " <img src='external.gif' alt='"+ExternalTxt+"' />";
				}
			}
		}
	},
	
	blurAll : function(){ 
		var lincs = document.getElementsByTagName("a"); 
		function doBlur(e)  { this.blur(); } 
		for (var k=0; k<lincs.length; k++){
			lincs[k].onfocus = doBlur;
		}
	},
	
	displayGalleries : function(){ 
		var url = location.href;
		if(url.indexOf("/eng/") != -1) {
			Extras.showtxt = "Show all thumbnails of this gallery";
			Extras.hidetxt = "Hide all thumbnails of this gallery";
		}
		else {
			Extras.showtxt = "Muestra todas las miniaturas de esta galería";
			Extras.hidetxt = "Esconde todas las miniaturas de esta galería";
		}
	
		var gals = Extras.getElementsByClass('pregallery');
		for (var i = 0; i < gals.length; i++) {
			daparent = gals[i].parentNode;
			where = gals[i];
			if(!where.id) where.id = "toggle"+i;
			var galid = where.id;
			var linkgalid = "link"+where.id;
			where.style.display = "block";
			daparent.innerHTML += "<div class=\"toggle\"><a id=\""+linkgalid+"\" href=\"#\" onclick=\"Extras.toggleGalleries('"+galid+"','"+linkgalid+"');return false\">"+Extras.hidetxt+"</a></div>";
			if(Cookie.get("meddle_v3_galery")=="n")  Extras.toggleGalleries(galid,linkgalid);
		}
	},
	
	toggleGalleries : function(id,link) { 
		elm = document.getElementById(id);
		lnk = document.getElementById(link);
		if(elm.style.display == "block") {
			elm.style.display = "none";
			lnk.innerHTML = Extras.showtxt;
		}
		else {
			elm.style.display = "block";
			lnk.innerHTML = Extras.hidetxt;
		}
	}
}


// extending Array, by Aaron Boodman (youngpup.net):
Array.prototype.indexOf = function(foo) { 
	for (var i = 0; i < this.length; i++)  
	if (foo == this[i]) return i;  
	return -1;  
}

// adds 1 or more elements to an array (IE only)
// by Dave Schontzler, www.stilleye.com
if(!Array.prototype.push)
{
	Array.prototype.push =  function()
	{
		var i;
		for(i=0; j=arguments[i]; i++) this[this.length] = j;
		return this.length;
	}
}


// ==============================================================
// TOC generator, 01/07/2004 - 4h before speech at OFFF :)
// (c)2004 Sergi Meseguer (http://zigotica.com/)
// ==============================================================
var TOC = {
	NODE_ELEMENT : 1,
	NODE_ATTRIBUTE : 2,
	NODE_TEXT : 3,
	NODE_CDATA_SECTION : 4,
	NODE_ENTITY_REFERENCE : 5,
	NODE_ENTITY : 6,
	NODE_PROCESSING_INSTRUCTION : 7,
	NODE_COMMENT : 8,
	NODE_DOCUMENT : 9,
	NODE_DOCUMENT_TYPE : 10,
	NODE_DOCUMENT_FRAGMENT : 11,
	NODE_NOTATION : 12,

	arrcounter : 0,
	counter : 0,
	contenedor : [], //{tagname, level, id, text} 
	
	init : function() 
	{
		var ALL = document.getElementById("content").getElementsByTagName("*");
		for (var k=0; k<ALL.length; k++) { 
			switch(ALL[k].nodeType) {
					case TOC.NODE_ELEMENT:
						if(ALL[k].tagName.toUpperCase()=="H2" 
						|| ALL[k].tagName.toUpperCase()=="H3" 
						|| ALL[k].tagName.toUpperCase()=="H4" 
						|| ALL[k].tagName.toUpperCase()=="H5" 
						|| ALL[k].tagName.toUpperCase()=="H6") {
							if(!ALL[k].id) {ALL[k].id = "toc" + TOC.counter;TOC.counter++}
							TOC.contenedor.push([ALL[k].tagName, ALL[k].tagName.substring(1,2), ALL[k].id, ALL[k].childNodes[0].nodeValue]);
						};
						break;
					default:
						//alert("unknown nodetype: " + ALL[k].nodeType);
				}
		}
		//alert(TOC.contenedor)
		if(TOC.contenedor.length > 0) {
			var main = document.getElementsByTagName( 'body' ).item( 0 );
			var contenido = document.getElementById("content");
			var toc = document.createElement("div");
			toc.id = "TOC";
			
			var url = location.href;
			if(url.indexOf("/eng/") != -1) toctxt = "Table of contents";
			else toctxt = "Tabla de contenidos";
			toc.innerHTML = "<h2>"+toctxt+"</h2>";
			
			var buffer = "<ul>";
			for (var i=0; i<TOC.contenedor.length; i++) { 
				if(i>0 && TOC.contenedor[i][1] < TOC.contenedor[i-1][1]) {//Si H < H level-1 cerrar ul+li
					var m = parseInt(TOC.contenedor[i][1]) + 1;
					for(var n=0;n<(TOC.contenedor[i-1][1]-TOC.contenedor[i][1]);n++) buffer += "</li></ul>";
					buffer += "<li>";
				}
				else if(i>0 && TOC.contenedor[i][1] > TOC.contenedor[i-1][1]) {//Si H > H level-1 abrir ul+li
					buffer += "<ul><li>";
				}
				else if(i>0) {
					buffer += "</li><li>";
				}
				else {
					buffer += "<li>";
				}
				buffer += "<a href='#"+TOC.contenedor[i][2]+"'>"  + TOC.contenedor[i][3] + "</a>";
			}
			buffer += "</li></ul>";
			toc.innerHTML += buffer;
			document.body.insertBefore(toc,document.getElementById("content"));
		}
	}	

}


/*************************************************************
* Extension allows validation of form before sending to server 
* Strongly based on the excellent article by Simon Willison at
* http://www.sitepoint.com/article/simple-tricks-usable-forms/
**************************************************************/
VALID = {
	
	tieFormEvents : function() {
		var url = location.href;
		if(url.indexOf("/eng/") != -1) {
		VALID.compulsory = "you need to fill in all compulsory fields";
		VALID.goodemail = "you need to provide a correct address: name@domain.ext\nPlease correct the email field"
		VALID.goodphone = "you need to provide a correct phone number: only numbers are allowed\nPlease correct the phone field"
		}
		if(url.indexOf("/esp/") != -1) {
		VALID.compulsory = "rellene todos los campos obligatorios";
		VALID.goodemail = "se requiere un correo válido: nombre@dominio.ext\nPor favor corrija el formato"
		VALID.goodphone = "se requiere un teléfono válido: solo se permiten números\nPor favor corrija el formato"
		}

		var areas = document.getElementsByTagName('textarea');
		for (var a = 0; (area = areas[a]); a++) {
			Extras.addEvent(area, 'blur', VALID.bluring, false);
		}
		var inputs = document.getElementsByTagName('input');
		for (var a = 0; (input = inputs[a]); a++) {
			if(input.type == "text") {
				Extras.addEvent(input, 'blur', VALID.bluring, false);			
			}
		}
		var forms = document.getElementsByTagName('form');
		for (var a = 0; (form = forms[a]); a++) {
			form.onsubmit = VALID.checkForm;
		}
	},

	checkForm : function(e) {
		// hacking IE events:
		var e = e || window.event;
		var target = e.target || e.srcElement;

		var remaining = [];
		var requireds = Extras.getElementsByClass('required problem');
		for (var i = 0; i < requireds.length; i++) {
			valor = requireds[i].innerHTML;
			valor = valor.replace(/: \(\*\)/i, ""); 
			remaining.push("\r\n"+valor)
		}
		var requireds = Extras.getElementsByClass('required');
		for (var i = 0; i < requireds.length; i++) {
			valor = requireds[i].innerHTML;
			valor = valor.replace(/: \(\*\)/i, ""); 
			remaining.push("\r\n"+valor)
		}
		
		if(remaining.length > 0) {
			alert(VALID.compulsory+":\n" + remaining);
			return false; // stop submission!
		}
		else return true; // do submit
	},

	bluring : function(e) {
		// hacking IE events:
		var e = e || window.event;
		var target = e.target || e.srcElement;

		var label;
		var labels = document.getElementsByTagName('label');
		for (var i = 0; i < labels.length; i++) {
			if (labels[i].htmlFor == target.id) {
				label =  labels[i];
			}
		}
		
		// probably better as an external method also called onsubmit (inside checkForm)
		if (target.value.length == 0 && label.className.indexOf("required") != -1) {
			label.className = 'required problem';
		} 
		else if (target.value.length != 0 && target.value != "<p></p>" && label.className.indexOf("required") != -1) {
			label.className = 'required completed';
		}
		else if (target.value.length != 0 && label.className.indexOf("required") == -1) {
			label.className = 'completed';
		}
		else if (target.value.length == 0 && label.className.indexOf("required") == -1) {
			label.className = '';
		}
		
    		// Regular Expression matching http://
    		var urlRegExp = /http:\/\//i;
    		if(target.id == "url" && target.value.length != 0 && !urlRegExp.test(target.value)) {
			target.value = "http://"+target.value;
	    	}
    		// Regular Expression matching phone number
    		var phoneRegExp = /[a-zA-Z_]/i;
    		if(target.id == "phone" && target.value.length != 0 && phoneRegExp.test(target.value)) {
			target.value = target.value.replace(/[a-zA-Z_]/gi,"-");
			alert(VALID.goodphone);
	    	}

    		// Regular Expression matching from
		// http://regexlib.com/UserPatterns.aspx?authorId=1758
    		var emailRegExp = /^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/i;
    		if(target.id == "email" && target.value.length != 0 && emailRegExp.test(target.value)) {
			if (label.className.indexOf("required") != -1) {
				label.className = 'required completed';
			} 
			else label.className = 'completed';
	    	}
	    	else if(target.id == "email" && target.value.length != 0 && !emailRegExp.test(target.value)) {
			if (label.className.indexOf("required") != -1) {
				label.className = 'required problem';
			} 
	    		else label.className = 'problem';
	    		alert(VALID.goodemail);
	    	}
	}
	
}

// Cookie namespace, by Dave Schontzler, www.stilleye.com
Cookie = {
	set : function(name,value,days,path)
	{
		var ex = "";
		if(days)
		{
			var d = new Date();
			d.setTime(d.getTime()+(days*24*60*60*1000));
			ex = "; expires="+d.toGMTString();
		}
		path = path ? path : "/";
		document.cookie = name + "=" + escape(value) + ex + "; path=" + path;
	},
	
	get : function(name)
	{
		var c = document.cookie.split(';');
		var wh = name + '=';
		for(i=0;(j=c[i]);i++)
		{
			while(j.charAt(0)==' ') j = j.substring(1, j.length);
			if(j.indexOf(wh)==0) return unescape(j.substring(wh.length));
		}
		return null;
	},
	
	kill : function(name) { Cookie.set(name,'',-1); }
}

if (document.getElementsByTagName) { 
	Extras.addEvent(window, "load", Extras.extractCites, false);
	Extras.addEvent(window, "load", VALID.tieFormEvents, false);
	if(Cookie.get("meddle_v3_toc")!="n") Extras.addEvent(window, "load", TOC.init, false);
	Extras.addEvent(window, "load", Extras.displayGalleries, false);
}
if (document.getElementsByTagName && !window.opera) { 
	if(Cookie.get("meddle_v3_retarget")!="n") Extras.addEvent(window, "load", Extras.reTarget, false);
	Extras.addEvent(window, "load", Extras.blurAll, false);
}

// Mozilla on Linux doesnt seem to like opcities that are set through CSS (#listilla li a{-moz-opacity:0.6;})
// Using the fantastic behaviours port made by dean edwards's (http://dean.edwards.name/moz-behaviors/) we
// had the problem that opacity wasnt set onload, only onhover. 
// We left CSS commented so that you can check if you want: moz-behaviors.xml + opacity.htc
// The following is the easiest, lightest solution:
if (document.getElementsByTagName && document.addEventListener && !window.opera && navigator.userAgent.toLowerCase().indexOf('linux') != -1) { 
        document.styleSheets[0].insertRule("#listilla li a{-moz-opacity:0.999;}",document.styleSheets[0].cssRules.length);
}


// Add code line numbers:
if (document.addEventListener) Extras.addEvent(window, "load", Extras.numberCodeTags, false);



//================================================\\
//                  end add-ons                   \\
//================================================\\