Object.extend = function(dest, source, replace) {
	for(var prop in source) {
		if(replace == false && dest[prop] != null) { continue; }
		dest[prop] = source[prop];
	}
	return dest;
};

Object.extend(Function.prototype, {
	apply: function(o, a) {
		var r, x = "__fapply";
		if(typeof o != "object") { o = {}; }
		o[x] = this;
		var s = "r = o." + x + "(";
		for(var i=0; i<a.length; i++) {
			if(i>0) { s += ","; }
			s += "a[" + i + "]";
		}
		s += ");";
		eval(s);
		delete o[x];
		return r;
	},
	bind: function(o) {
		if(!Function.__objs) {
			Function.__objs = [];
			Function.__funcs = [];
		}
		var objId = o.__oid;
		if(!objId) {
			Function.__objs[objId = o.__oid = Function.__objs.length] = o;
		}

		var me = this;
		var funcId = me.__fid;
		if(!funcId) {
			Function.__funcs[funcId = me.__fid = Function.__funcs.length] = me;
		}

		if(!o.__closures) {
			o.__closures = [];
		}

		var closure = o.__closures[funcId];
		if(closure) {
			return closure;
		}

		o = null;
		me = null;

		return Function.__objs[objId].__closures[funcId] = function() {
			return Function.__funcs[funcId].apply(Function.__objs[objId], arguments);
		};
	}
}, false);

Object.extend(Array.prototype, {
	push: function(o) {
		this[this.length] = o;
	},
	addRange: function(items) {
		if(items.length > 0) {
			for(var i=0; i<items.length; i++) {
				this.push(items[i]);
			}
		}
	},
	clear: function() {
		this.length = 0;
		return this;
	},
	shift: function() {
		if(this.length == 0) { return null; }
		var o = this[0];
		for(var i=0; i<this.length-1; i++) {
			this[i] = this[i + 1];
		}
		this.length--;
		return o;
	}
}, false);

Object.extend(String.prototype, {
	trimLeft: function() {
		return this.replace(/^\s*/,"");
	},
	trimRight: function() {
		return this.replace(/\s*$/,"");
	},
	trim: function() {
		return this.trimRight().trimLeft();
	},
	endsWith: function(s) {
		if(this.length == 0 || this.length < s.length) { return false; }
		return (this.substr(this.length - s.length) == s);
	},
	startsWith: function(s) {
		if(this.length == 0 || this.length < s.length) { return false; }
		return (this.substr(0, s.length) == s);
	},
	split: function(c) {
		var a = [];
		if(this.length == 0) return a;
		var p = 0;
		for(var i=0; i<this.length; i++) {
			if(this.charAt(i) == c) {
				a.push(this.substring(p, i));
				p = ++i;
			}
		}
		a.push(s.substr(p));
		return a;
	}
}, false);

Object.extend(String, {
	format: function(s) {
		for(var i=1; i<arguments.length; i++) {
			s = s.replace("{" + (i -1) + "}", arguments[i]);
		}
		return s;
	},
	isNullOrEmpty: function(s) {
		if(s == null || s.length == 0) {
			return true;
		}
		return false;
	}
}, false);

if(typeof addEvent == "undefined")
	addEvent = function(o, evType, f, capture) {
		if(o == null) { return false; }
		if(o.addEventListener) {
			o.addEventListener(evType, f, capture);
			return true;
		} else if (o.attachEvent) {
			var r = o.attachEvent("on" + evType, f);
			return r;
		} else {
			try{ o["on" + evType] = f; }catch(e){}
		}
	};
	
if(typeof removeEvent == "undefined")
	removeEvent = function(o, evType, f, capture) {
		if(o == null) { return false; }
		if(o.removeEventListener) {
			o.removeEventListener(evType, f, capture);
			return true;
		} else if (o.detachEvent) {
			o.detachEvent("on" + evType, f);
		} else {
			try{ o["on" + evType] = function(){}; }catch(e){}
		}
	};
//esta es una copia del core de ajax, con la solucion del problema de javascript en ontimeout
//si en futuras versiones de ajax se corrige, ya no sera necesario

Object.extend(Function.prototype, {
    getArguments: function() {
        var args = [];
        var argLength = this.arguments.length;
        for (var i = 0; i < argLength; i++) {
            args.push(this.arguments[i]);
        }
        return args;
    }
}, false);

var MS = {"Browser":{}};

Object.extend(MS.Browser, {
	isIE: navigator.userAgent.indexOf('MSIE') != -1,
	isFirefox: navigator.userAgent.indexOf('Firefox') != -1,
	isOpera: window.opera != null
}, false);

var AjaxPro = {};

AjaxPro.IFrameXmlHttp = function() {};
AjaxPro.IFrameXmlHttp.prototype = {
	onreadystatechange: null, headers: [], method: "POST", url: null, async: true, iframe: null,
	status: 0, readyState: 0, responseText: null,
	abort: function() {
	},
	readystatechanged: function() {
		var doc = this.iframe.contentDocument || this.iframe.document;
		if(doc != null && doc.readyState == "complete" && doc.body != null && doc.body.res != null) {
			this.status = 200;
			this.statusText = "OK";
			this.readyState = 4;
			this.responseText = doc.body.res;
			this.onreadystatechange();
			return;
		}
		setTimeout(this.readystatechanged.bind(this), 10);
	},
	open: function(method, url, async) {
		if(async == false) {
			alert("Synchronous call using IFrameXMLHttp is not supported.");
			return;
		}
		if(this.iframe == null) {
			var iframeID = "hans";
			if (document.createElement && document.documentElement &&
				(window.opera || navigator.userAgent.indexOf('MSIE 5.0') == -1))
			{
				var ifr = document.createElement('iframe');
				ifr.setAttribute('id', iframeID);
				ifr.style.visibility = 'hidden';
				ifr.style.position = 'absolute';
				ifr.style.width = ifr.style.height = ifr.borderWidth = '0px';

				this.iframe = document.getElementsByTagName('body')[0].appendChild(ifr);
			}
			else if (document.body && document.body.insertAdjacentHTML)
			{
				document.body.insertAdjacentHTML('beforeEnd', '<iframe name="' + iframeID + '" id="' + iframeID + '" style="border:1px solid black;display:none"></iframe>');
			}
			if (window.frames && window.frames[iframeID]) {
				this.iframe = window.frames[iframeID];
			}
			this.iframe.name = iframeID;
			this.iframe.document.open();
			this.iframe.document.write("<"+"html><"+"body></"+"body></"+"html>");
			this.iframe.document.close();
		}
		this.method = method;
		this.url = url;
		this.async = async;
	},
	setRequestHeader: function(name, value) {
		for(var i=0; i<this.headers.length; i++) {
			if(this.headers[i].name == name) {
				this.headers[i].value = value;
				return;
			}
		}
		this.headers.push({"name":name,"value":value});
	},
	getResponseHeader: function(name, value) {
		return null;
	},
	addInput: function(doc, form, name, value) {
		var ele;
		var tag = "input";
		if(value.indexOf("\n") >= 0) {
			tag = "textarea";
		}
		
		if(doc.all) {
			ele = doc.createElement("<" + tag + " name=\"" + name + "\" />");
		}else{
			ele = doc.createElement(tag);
			ele.setAttribute("name", name);
		}
		ele.setAttribute("value", value);
		form.appendChild(ele);
		ele = null;
	},
	send: function(data) {
		if(this.iframe == null) {
			return;
		}
		var doc = this.iframe.contentDocument || this.iframe.document;
		var form = doc.createElement("form");
		
		doc.body.appendChild(form);
		
		form.setAttribute("action", this.url);
		form.setAttribute("method", this.method);
		form.setAttribute("enctype", "application/x-www-form-urlencoded");
		
		for(var i=0; i<this.headers.length; i++) {
			switch(this.headers[i].name.toLowerCase()) {
				case "content-length":
				case "accept-encoding":
				case "content-type":
					break;
				default:
					this.addInput(doc, form, this.headers[i].name, this.headers[i].value);
			}
		}
		this.addInput(doc, form, "data", data);
		form.submit();
		
		setTimeout(this.readystatechanged.bind(this), 0);
	}
};

var progids = ["Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
var progid = null;

if(typeof ActiveXObject != "undefined") {
	var ie7xmlhttp = false;
	if(typeof XMLHttpRequest == "object") {
		try{ var o = new XMLHttpRequest(); ie7xmlhttp = true; }catch(e){}
	}
	if(typeof XMLHttpRequest == "undefined" || !ie7xmlhttp) {
		XMLHttpRequest = function() {
			var xmlHttp = null;
			if(!AjaxPro.noActiveX) {
				if(progid != null) {
					return new ActiveXObject(progid);
				}
				for(var i=0; i<progids.length && xmlHttp == null; i++) {
					try {
						xmlHttp = new ActiveXObject(progids[i]);
						progid = progids[i];

					}catch(e){}
				}
			}
			if(xmlHttp == null && MS.Browser.isIE) {
				return new AjaxPro.IFrameXmlHttp();
			}
			return xmlHttp;
		};
	}
}

Object.extend(AjaxPro, {
	noOperation: function() {},
	onLoading: function() {},
	onError: function() {},
	onTimeout: function() { return true; },
	onStateChanged: function() {},
	cryptProvider: null,
	queue: null,
	token: "",
	version: "7.7.31.1",
	ID: "AjaxPro",
	noActiveX: false,
	timeoutPeriod: 15*1000,
	queue: null,
	noUtcTime: false,
	regExDate: function(str,p1, p2,offset,s) {
        str = str.substring(1).replace('"','');
        var date = str;
        
        if (str.substring(0,7) == "\\\/Date(") {
            str = str.match(/Date\((.*?)\)/)[1];                        
            date = "new Date(" +  parseInt(str) + ")";
        }
        else { // ISO Date 2007-12-31T23:59:59Z                                     
            var matches = str.split( /[-,:,T,Z]/);        
            matches[1] = (parseInt(matches[1],0)-1).toString();                     
            date = "new Date(Date.UTC(" + matches.join(",") + "))";         
       }                  
        return date;
    },
    parse: function(text) {
		// not yet possible as we still return new type() JSON
//		if (!(!(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
//		text.replace(/"(\\.|[^"\\])*"/g, '')))  ))
//			throw new Error("Invalid characters in JSON parse string.");                 

        var regEx = /(\"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}.*?\")|(\"\\\/Date\(.*?\)\\\/")/g;
        text = text.replace(regEx,this.regExDate);      

        return eval('(' + text + ')');    
    },
	m : {
		'\b': '\\b',
		'\t': '\\t',
		'\n': '\\n',
		'\f': '\\f',
		'\r': '\\r',
		'"' : '\\"',
		'\\': '\\\\'
	},
	toJSON: function(o) {	
		if(o == null) {
			return "null";
		}
		var v = [];
		var i;
		var c = o.constructor;
		if(c == Number) {
			return isFinite(o) ? o.toString() : AjaxPro.toJSON(null);
		} else if(c == Boolean) {
			return o.toString();
		} else if(c == String) {
			if (/["\\\x00-\x1f]/.test(o)) {
				o = o.replace(/([\x00-\x1f\\"])/g, function(a, b) {
					var c = AjaxPro.m[b];
					if (c) {
						return c;
					}
					c = b.charCodeAt();
					return '\\u00' +
						Math.floor(c / 16).toString(16) +
						(c % 16).toString(16);
				});
            }
			return '"' + o + '"';
		} else if (c == Array) {
			for(i=0; i<o.length; i++) {
				v.push(AjaxPro.toJSON(o[i]));
			}
			return "[" + v.join(",") + "]";
		} else if (c == Date) {
//			var d = {};
//			d.__type = "System.DateTime";
//			if(AjaxPro.noUtcTime == true) {
//				d.Year = o.getFullYear();
//				d.Month = o.getMonth() +1;
//				d.Day = o.getDate();
//				d.Hour = o.getHours();
//				d.Minute = o.getMinutes();
//				d.Second = o.getSeconds();
//				d.Millisecond = o.getMilliseconds();
//			} else {
//				d.Year = o.getUTCFullYear();
//				d.Month = o.getUTCMonth() +1;
//				d.Day = o.getUTCDate();
//				d.Hour = o.getUTCHours();
//				d.Minute = o.getUTCMinutes();
//				d.Second = o.getUTCSeconds();
//				d.Millisecond = o.getUTCMilliseconds();
//			}
			return AjaxPro.toJSON("/Date(" + new Date(Date.UTC(o.getUTCFullYear(), o.getUTCMonth(), o.getUTCDate(), o.getUTCHours(), o.getUTCMinutes(), o.getUTCSeconds(), o.getUTCMilliseconds())).getTime() + ")/");
		}
		if(typeof o.toJSON == "function") {
			return o.toJSON();
		}
		if(typeof o == "object") {
			for(var attr in o) {
				if(typeof o[attr] != "function") {
					v.push('"' + attr + '":' + AjaxPro.toJSON(o[attr]));
				}
			}
			if(v.length>0) {
				return "{" + v.join(",") + "}";
			}
			return "{}";		
		}
		return o.toString();
	},
	dispose: function() {
		if(AjaxPro.queue != null) {
			AjaxPro.queue.dispose();
		}
	}
}, false);

addEvent(window, "unload", AjaxPro.dispose);

AjaxPro.Request = function(url) {
	this.url = url;
	this.xmlHttp = null;
};

AjaxPro.Request.prototype = {
	url: null,
	callback: null,
	onLoading: AjaxPro.noOperation,
	onError: AjaxPro.noOperation,
	onTimeout: AjaxPro.noOperation,
	onStateChanged: null,
	args: null,
	context: null,
	isRunning: false,
	abort: function() {
		if(this.timeoutTimer != null) {
			clearTimeout(this.timeoutTimer);
		}
		if(this.xmlHttp) {
			this.xmlHttp.onreadystatechange = AjaxPro.noOperation;
			this.xmlHttp.abort();
		}
		if(this.isRunning) {
			this.isRunning = false;
			this.onLoading(false);
		}
	},
	dispose: function() {
		this.abort();
	},
	getEmptyRes: function() {
		return {
			error: null,
			value: null,
			request: {method:this.method, args:this.args},
			context: this.context,
			duration: this.duration
		};	
	},
	endRequest: function(res) {
		this.abort();
		if(res.error != null) {
			this.onError(res.error, this);
		}

		if(typeof this.callback == "function") {
			this.callback(res, this);
		}
	},
	mozerror: function() {
		if(this.timeoutTimer != null) {
			clearTimeout(this.timeoutTimer);
		}
		var res = this.getEmptyRes();
		res.error = {Message:"Unknown",Type:"ConnectFailure",Status:0};
		this.endRequest(res);
	},
	doStateChange: function() {
		this.onStateChanged(this.xmlHttp.readyState, this);
		if(this.xmlHttp.readyState != 4 || !this.isRunning) {
			return;
		}
		this.duration = new Date().getTime() - this.__start;
		if(this.timeoutTimer != null) {
			clearTimeout(this.timeoutTimer);
		}
		var res = this.getEmptyRes();
		if(this.xmlHttp.status == 200 && this.xmlHttp.statusText == "OK") {
			res = this.createResponse(res);
		} else {
			res = this.createResponse(res, true);
			res.error = {Message:this.xmlHttp.statusText,Type:"ConnectFailure",Status:this.xmlHttp.status};
		}
		
		this.endRequest(res);
	},
	createResponse: function(r, noContent) {
		if(!noContent) {
			if(typeof(this.xmlHttp.responseText) == "unknown") {
				r.error = {Message: "XmlHttpRequest error reading property responseText.", Type: "XmlHttpRequestException"};
				return r;
			}
		
			var responseText = "" + this.xmlHttp.responseText;

			if(AjaxPro.cryptProvider != null && typeof AjaxPro.cryptProvider.decrypt == "function") {
				responseText = AjaxPro.cryptProvider.decrypt(responseText);
			}

			if(this.xmlHttp.getResponseHeader("Content-Type") == "text/xml") {
				r.value = this.xmlHttp.responseXML;
			} else {
				if(responseText != null && responseText.trim().length > 0) {
					r.json = responseText;
					var v = null;
					v = AjaxPro.parse(responseText);
					if(v != null) {
						if(typeof v.value != "undefined") r.value = v.value;
						else if(typeof v.error != "undefined") r.error = v.error;
					}
				}
			}
		}
		/* if(this.xmlHttp.getResponseHeader("X-" + AjaxPro.ID + "-Cache") == "server") {
			r.isCached = true;
		} */
		return r;
	},
	timeout: function() {
		this.duration = new Date().getTime() - this.__start;
		var r = this.onTimeout(this.duration, this);
		if(typeof r == "undefined" || r != false) {
			this.abort();
		} else {
			this.timeoutTimer = setTimeout(this.timeout.bind(this), AjaxPro.timeoutPeriod);
		}
	},
	invoke: function(method, args, callback, context) {
		this.__start = new Date().getTime();

		// if(this.xmlHttp == null) {
			this.xmlHttp = new XMLHttpRequest();
		// }

		this.isRunning = true;
		this.method = method;
		this.args = args;
		this.callback = callback;
		this.context = context;
		
		var async = typeof(callback) == "function" && callback != AjaxPro.noOperation;
		
		if(async) {
			if(MS.Browser.isIE) {
				this.xmlHttp.onreadystatechange = this.doStateChange.bind(this);
			} else {
				this.xmlHttp.onload = this.doStateChange.bind(this);
				this.xmlHttp.onerror = this.mozerror.bind(this);
			}
			this.onLoading(true);
		}
		
		var json = AjaxPro.toJSON(args) + "";
		if(AjaxPro.cryptProvider != null && typeof AjaxPro.cryptProvider.encrypt == "function") {
			json = AjaxPro.cryptProvider.encrypt(json);
		}
		
		this.xmlHttp.open("POST", this.url, async);
		this.xmlHttp.setRequestHeader("Content-Type", "text/plain; charset=utf-8");
		this.xmlHttp.setRequestHeader("X-" + AjaxPro.ID + "-Method", method);
		
		if(AjaxPro.token != null && AjaxPro.token.length > 0) {
			this.xmlHttp.setRequestHeader("X-" + AjaxPro.ID + "-Token", AjaxPro.token);
		}

		/* if(!MS.Browser.isIE) {
			this.xmlHttp.setRequestHeader("Connection", "close");
		} */

		this.timeoutTimer = setTimeout(this.timeout.bind(this), AjaxPro.timeoutPeriod);

		try{ this.xmlHttp.send(json); }catch(e){}	// IE offline exception

		if(!async) {
			return this.createResponse({error: null,value: null});
		}

		return true;	
	}
};

AjaxPro.RequestQueue = function(conc) {
	this.queue = [];
	this.requests = [];
	this.timer = null;
	
	if(isNaN(conc)) { conc = 2; }

	for(var i=0; i<conc; i++) {		// max 2 http connections
		this.requests[i] = new AjaxPro.Request();
		this.requests[i].callback = function(res) {
			var r = res.context;
			res.context = r[3][1];

			r[3][0](res, this);
		};
		this.requests[i].callbackHandle = this.requests[i].callback.bind(this.requests[i]);
	}
	
	this.processHandle = this.process.bind(this);
};

AjaxPro.RequestQueue.prototype = {
	process: function() {
		this.timer = null;
		if(this.queue.length == 0) {
			return;
		}
		for(var i=0; i<this.requests.length && this.queue.length > 0; i++) {
			if(this.requests[i].isRunning == false) {
				var r = this.queue.shift();

				this.requests[i].url = r[0];
				this.requests[i].onLoading = r[3].length >2 && r[3][2] != null && typeof r[3][2] == "function" ? r[3][2] : AjaxPro.onLoading;
				this.requests[i].onError = r[3].length >3 && r[3][3] != null && typeof r[3][3] == "function" ? r[3][3] : AjaxPro.onError;
				this.requests[i].onTimeout = r[3].length >4 && r[3][4] != null && typeof r[3][4] == "function" ? r[3][4] : AjaxPro.onTimeout;
				this.requests[i].onStateChanged = r[3].length >5 && r[3][5] != null && typeof r[3][5] == "function" ? r[3][5] : AjaxPro.onStateChanged;

				this.requests[i].invoke(r[1], r[2], this.requests[i].callbackHandle, r);
				r = null;
			}
		}
		if(this.queue.length > 0 && this.timer == null) {
			this.timer = setTimeout(this.processHandle, 0);
		}
	},
	add: function(url, method, args, e) {
		this.queue.push([url, method, args, e]);
		if(this.timer == null) {
			this.timer = setTimeout(this.processHandle, 0);
		}
		// this.process();
	},
	abort: function() {
		this.queue.length = 0;
		if (this.timer != null) {
			clearTimeout(this.timer);
		}
		this.timer = null;
		for(var i=0; i<this.requests.length; i++) {
			if(this.requests[i].isRunning == true) {
				this.requests[i].abort();
			}
		}
	},
	dispose: function() {
		for(var i=0; i<this.requests.length; i++) {
			var r = this.requests[i];
			r.dispose();
		}
		this.requests.clear();
	}
};

AjaxPro.queue = new AjaxPro.RequestQueue(2);	// 2 http connections

AjaxPro.AjaxClass = function(url) {
	this.url = url;
};

AjaxPro.AjaxClass.prototype = {
	invoke: function(method, args, e) {
	
		if(e != null) {
			if(e.length != 6) {
				for(;e.length<6;) { e.push(null); }
			}
			if(e[0] != null && typeof(e[0]) == "function") {
				return AjaxPro.queue.add(this.url, method, args, e);
			}
		}
		var r = new AjaxPro.Request();
		r.url = this.url;
		return r.invoke(method, args);
	}
};


var addNamespace = function(ns) {
	var nsParts = ns.split(".");
	var root = window;
	for(var i=0; i<nsParts.length; i++) {
		if(typeof root[nsParts[i]] == "undefined") {
			root[nsParts[i]] = {};
		}
		root = root[nsParts[i]];
	}
};

Object.extend(window, {
	$: function() {
		var elements = [];
		for(var i=0; i<arguments.length; i++) {
			var e = arguments[i];
			if(typeof e == 'string') {
				e = document.getElementById(e);
			}
			if(arguments.length == 1) {
				return e;
			}
			elements.push(e);
		}
		return elements;
	},
	Class: {
		create: function() {
			return function() {
				if(typeof this.initialize == "function") {
					this.initialize.apply(this, arguments);
				}
			};
		}
	}
}, false);

addNamespace("MS.Debug");
MS.Debug = {};		// has been removed to debug version of core.ashx

addNamespace("MS.Position");

Object.extend(MS.Position, {
	getLocation: function(ele) {
		var x = 0;
		var y = 0;
		var p;
		for(p=ele; p; p=p.offsetParent) {
			// if(p.style.position == "relative" || p.style.position == "absolute") break;
			if(p.offsetLeft && p.offsetTop) {
				x += p.offsetLeft;
				y += p.offsetTop;
			}
		}
		return {left:x,top:y};
	},
	getBounds: function(ele) {
		var offset = MS.Position.getLocation(ele);
		var width = ele.offsetWidth;
		var height = ele.offsetHeight;
		return {left:offset.left,top:offset.top,width:width,height:height};
	},
	setLocation: function(ele, loc) {
		ele.style.position = "absolute";
		ele.style.left = loc.left + "px";
		ele.style.top = loc.top + "px";
	},
	setBounds: function(ele, rect) {
		if(rect.left && rect.top) {
			MS.Position.setLocation(ele, rect);
		}
		ele.style.width = rect.width + "px";
		ele.style.height = rect.height + "px";
	}
}, false);

addNamespace("MS.Keys");

Object.extend(MS.Keys, {
	TAB: 9,
	ESC: 27,
	KEYUP: 38,
	KEYDOWN: 40,
	KEYLEFT: 37,
	KEYRIGHT: 39,
	SHIFT: 16,
	CTRL: 17,
	ALT: 18,
	ENTER: 13,
	getCode: function(e) {
		e = MS.getEvent(e);
		if(e != null) { return e.keyCode; }
		return -1;
	}
}, false);

Object.extend(MS, {
	setText: function(ele, text) {
		if(ele == null) { return; }
		if(document.all) {
			ele.innerText = text;
		} else {
			ele.textContent = text;
		}
	},
	setHtml: function(ele, html) {
		if(ele == null) { return; }
		ele.innerHTML = html;
	},
	cancelEvent: function(e) {
		e = MS.getEvent(e);
		if(window.event) {
			e.returnValue = false;
		} else if(e) {
			e.preventDefault();
			e.stopPropagation();
		}
	},
	getEvent: function(e) {
		if(window.event) { return window.event; }
		if(e) { return e; }
		return null;
	},
	getTarget: function(e) {
		e = MS.getEvent(e);
		if(window.event) { return e.srcElement; }
		if(e) { return e.target; }
	}
}, false);

var StringBuilder = function() {
	this.v = [];
};

Object.extend(StringBuilder.prototype, {
	append: function(s) {
		this.v.push(s);
	},
	appendLine: function(s) {
		this.v.push(s + "\r\n");
	},
	clear: function() {
		this.v.clear();
	},
	toString: function() {
		return this.v.join("");
	}
}, true);
if(typeof Wke == "undefined") Wke={};
if(typeof Wke.Presentation == "undefined") Wke.Presentation={};
if(typeof Wke.Presentation.WebControls == "undefined") Wke.Presentation.WebControls={};
Wke.Presentation.WebControls.PageControl_class = function() {};
Object.extend(Wke.Presentation.WebControls.PageControl_class.prototype, Object.extend(new AjaxPro.AjaxClass(), {
	VerifyLanguage: function(hash) {
		return this.invoke("VerifyLanguage", {"hash":hash}, this.VerifyLanguage.getArguments().slice(1));
	},
	VerifySession: function(href, url, idType) {
		return this.invoke("VerifySession", {"href":href, "url":url, "idType":idType}, this.VerifySession.getArguments().slice(3));
	},
	CloseNavigator: function() {
		return this.invoke("CloseNavigator", {}, this.CloseNavigator.getArguments().slice(0));
	},
	url: '/ajaxpro/Wke.Presentation.WebControls.PageControl,Wke.Presentation.ashx'
}));
Wke.Presentation.WebControls.PageControl = new Wke.Presentation.WebControls.PageControl_class();


//control de cierre de ventana en ie
var myclose=false;

window.onbeforeunload = function() 
{
if(window.event)
{
var n = window.event.screenX - window.screenLeft;
var b = n > document.documentElement.scrollWidth-20;
if(b && window.event.clientY < 0 || window.event.altKey)
{
    if(window.opener==null)
        myclose=true;
    return HandleOnClose();
     
}
}
}

 function HandleOnClose(){	
 if (myclose==true) var res=Wke.Presentation.WebControls.PageControl.CloseNavigator();	
 }	



function PageLoad(target, method)
{  
    var obj = new Object();
    obj.url = window.location.href;
    AjaxCachePageControl_load(target, method, obj);
}


//Funcion que nos permite saltar a enlaces externos. Esta aqui de forma temporal
function SaltoExt(url)
{
 window.open(url);
}


function getInternetExplorerVersion()
{
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}


function checkVersion(version, messanger) 
{
    var ver = getInternetExplorerVersion();
    var hash = new Object();
    if ( ver > -1 )
    {
        if ( ver < version) {
            popup.OpenGenericPopup("GenericPopup.aspx?labelCodeText=htmlAlertUpdateIExplorer&amp;needUpdIE=true&amp;idType=23", 'no', 300, 200, 'px', 'yes', '', '', '', 23);          
          hash.flag = true;
        }
    }
}
/**************************************************************************/
var opacityDisableControl = 40;
var functionResize = "SetBodyHeight();";
var functionsOnLoad = "";

function GetDate() {
  var this_month = new Array(12);
  this_month[0] = fmtmes1; //"Enero";
  this_month[1] = fmtmes2; //"Febrero";
  this_month[2] = fmtmes3; //"Marzo";
  this_month[3] = fmtmes4; //"Abril";
  this_month[4] = fmtmes5; //"Mayo";
  this_month[5] = fmtmes6; //"Junio";
  this_month[6] = fmtmes7; //"Julio";
  this_month[7] = fmtmes8; //"Agosto";
  this_month[8] = fmtmes9; //"Septiembre";
  this_month[9] = fmtmes10; //"Octubre";
  this_month[10] = fmtmes11; //"Noviembre";
  this_month[11] = fmtmes12; //"Diciembre";

  var this_day_e = new Array(7);
  this_day_e[0] = fmtdia1; //"Domingo";
  this_day_e[1] = fmtdia2; //"Lunes";
  this_day_e[2] = fmtdia3; //"Martes";
  this_day_e[3] = fmtdia4; //"Mi&eacute;rcoles";
  this_day_e[4] = fmtdia5; //"Jueves";
  this_day_e[5] = fmtdia6; //"Viernes";
  this_day_e[6] = fmtdia7; //"S&aacute;bado";

  var today = new Date();
  var day   = today.getDate();
  var month = today.getMonth();
  var year  = today.getYear();
  var dia = today.getDay();
    if (year < 1000) {
       year += 1900; }
  document.write (this_day_e[dia] + " " + day + " de " + this_month[month] + " " + year);
}

/**********************************************************************************************/
/*                 Funciones para Exportar, imprimir y enviar a un amigo                      */
/**********************************************************************************************/
//Nos devuelve el texto que hayamos seleccionado de un documento.
function GetSelectedText()
{
	if (window.getSelection){
		return window.getSelection() + "";
	}
	else if (document.getSelection){
		return document.getSelection() + "";
	}
	else if (document.selection){
		return document.selection.createRange().text + "";
	}
	else{
		return "";
	}
}

/**********************************************************************************************/
/*                 Funcion para Validar Correo                                                */
/**********************************************************************************************/
function ValidateMail(mail)
{
    if(mail.search('^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$')){
        return false;
    }
    return true;
}


/**********************************************************************************************/
/*                Funciones para deshabilitar funcionalidad por permisos                      */
/**********************************************************************************************/

function Warning(errorToShow)  
{
    //htmlNoPermissions se crea en el web control PageControl
    //alert(htmlNoPermissions);
    // eval(htmlNoPermissions); antes
    eval (errorToShow);
    return false;
}

function DisableControl(id) 
{
    var obj = document.getElementById(id);
    if (navigator.appName == "Microsoft Internet Explorer"){
        DisableControlsRecursive(obj);
    }
    else{
        obj.style.opacity = (opacityDisableControl / 100);
        obj.style.MozOpacity = (opacityDisableControl / 100);
        obj.style.KhtmlOpacity = (opacityDisableControl / 100);
        obj.style.filter = "alpha(opacity=" + opacityDisableControl + ")"; 
    }
} 

function DisableControlsRecursive(obj)
{
    if (obj.hasChildNodes()){
        var children = obj.childNodes;
        var i = 0;
        
        while (i < children.length){
            if (children[i].style != null){
                children[i].style.opacity = (opacityDisableControl / 100);
                children[i].style.MozOpacity = (opacityDisableControl / 100);
                children[i].style.KhtmlOpacity = (opacityDisableControl / 100);
                children[i].style.filter = "alpha(opacity=" + opacityDisableControl + ")"; 
            }
            else {
                if (children[i].parentNode.style != null){
                    var parent = children[i].parentNode;
                    parent.style.opacity = (opacityDisableControl / 100);
                    parent.style.MozOpacity = (opacityDisableControl / 100);
                    parent.style.KhtmlOpacity = (opacityDisableControl / 100);
                    parent.style.filter = "alpha(opacity=" + opacityDisableControl + ")"; 
                }
            }
            DisableControlsRecursive(children[i]);            
            i++;
        };
    }    
}

/**********************************************************************************************/
/*                Funciones para redimensionar el body del portal                             */
/**********************************************************************************************/
function OnLoadPortal() {
	// Soluciona Explorer 6.0 para crear objetos despues de cargar la pagina   
	// Debe estar al inicio de este método. La razón es que si existe alguna de las funciones js que se buscan aquí, realiza el
	// return y ya no sigue ejecutando.
	eval(functionsOnLoad);
	
	//document.forms[0].onsubmit= function () {return validate_swlogin();};
	document.forms[0].onsubmit= function () {
	    if (typeof(validate_swlogin) == "function"){
	        return validate_swlogin();
	    }        
	};
	if (typeof (OnLoadCache) == "function") {
	    OnLoadCache();
	}	
	if (typeof (SetBodyHeight) != "undefined") {
	    setTimeout('SetBodyHeight()', 1);
	}
    if (typeof (gotoanchorid) != "undefined") {
    setTimeout('GotoAnchor(gotoanchorid)',1);
    }
    //SetBodyHeight();
   
    //si existe una funcion con este nombre la llamaremos
    if (typeof(OnLoadPortalByProduct) == "function"){
      return OnLoadPortalByProduct();    }

    //para el extrano caso de los 1024 volvemos a llamar al gotoanchor
    if (typeof (gotoanchorid) != "undefined") {
        return GotoAnchorAux();
    }
}

function GotoAnchorAux() {
    setTimeout('GotoAnchor(gotoanchorid)', 500);
    return true;
}


function SetBodyHeight(){
    var redimension = true;
    if (typeof(pagesNoRedimension) != 'undefined' && pagesNoRedimension != "") {
        var pages = pagesNoRedimension.split("|");
        var i = 0;
        var url = window.location.href;
        url = url.substr(0, url.indexOf(".aspx") + 5);
      
        while (i < pages.length && redimension) {
            if (url.indexOf(pages[i]) != -1) {
                redimension = false;
            }
            if (url.indexOf('='+pages[i]) != -1) { //este cambio es para las url friendly
                redimension = true;
            }
            i++;
        }
    }

    if (redimension) {   
        //Si se tiene que redimensionar la capa central que tendra scroll   
        var height = document.getElementById("cContainer").offsetHeight;
        if (document.getElementById("cHead") != null){
	        height -= document.getElementById("cHead").offsetHeight;
	    
	    } else if(document.getElementById("cEmbeddedHead") != null){
	        //CRC (09/07/2008): Para contenidos que se muestran embebidos
	        // en un Iframe, la cabecera embebida, se llama cEmbeddedHead 
	        height -= document.getElementById("cEmbeddedHead").offsetHeight;
	    }
    	
	    if (document.getElementById("cFooter") != null){
	         height -= document.getElementById("cFooter").offsetHeight;
	    }
	    else if (document.getElementById("cFooterHome") != null){
	         height -= document.getElementById("cFooterHome").offsetHeight;
	    }

        if(height > 0){
            if (typeof(wcPage_body) != 'undefined' && wcPage_body !=null && document.getElementById(wcPage_body) != null){
                document.getElementById(wcPage_body).style.height = height + "px";
            }  
	        if (document.getElementById("cCx") != null){
                document.getElementById("cCx").style.height = height + "px";  
            }
            if (document.getElementById("cCn") != null){
                document.getElementById("cCn").style.height = height + "px";  
            }
        }
    } 
    else
    {   
	    var height = document.documentElement.clientHeight;
	    if (document.getElementById("cHead") != null){
	        height -= document.getElementById("cHead").offsetHeight;
	    } 
	    else if(document.getElementById("cEmbeddedHead") != null){
	        //CRC (09/07/2008): Para contenidos que se muestran embebidos
	        // en un Iframe, la cabecera embebida, se llama cEmbeddedHead 
	        height -= document.getElementById("cEmbeddedHead").offsetHeight;
	    }
    	
	    if (document.getElementById("cFooter") != null){
            height -= document.getElementById("cFooter").offsetHeight;
	    }
	    else if (document.getElementById("cFooterHome") != null){
            height -= document.getElementById("cFooterHome").offsetHeight;
	    }
    	
        if (document.getElementById(wcPage_body).offsetHeight < height){
            document.getElementById(wcPage_body).style.height = height + "px";
        }              
    }
    
    if (typeof (gotoanchorid) != "undefined") {
        setTimeout('GotoAnchor(gotoanchorid)', 1);
    }
}

//En la redimension de la ventana se ejecutan todas las funciones javascript
//que hayamos introducido en esta variable
window.onresize = function() {
    eval(functionResize);
}


/**********************************************************************************************/
/*                                  Funciones para video EMG                                  */
/**********************************************************************************************/
function AC_AddExtension(src, ext){
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs) { 
  var str = '<object ';
  for (var i in objAttrs)
    str += i + '="' + objAttrs[i] + '" ';
  str += '>';
  for (var i in params)
    str += '<param name="' + i + '" value="' + params[i] + '" /> ';
  str += '<embed ';
  for (var i in embedAttrs)
    str += i + '="' + embedAttrs[i] + '" ';
  str += ' ></embed></object>';

  document.write(str);
}

function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "id":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}

////////////////////////////////////////
function EscribeProyectorFlash(URL_SWF,Ancho,Alto,URL_Video){
	movie = URL_SWF.split(".swf");
	var flVars = "urlVideo="+URL_Video+"&ancho="+Ancho+"&alto="+Alto;
	AC_FL_RunContent(
		'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0',
		'width', Ancho,
		'height', Alto,
		'src', URL_SWF,
		'quality', 'high',
		'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
		'align', 'middle',
		'play', 'true',
		'loop', 'true',
		'scale', 'showall',
		'wmode', 'transparent',
		'devicefont', 'false',
		'id', 'proyector',
		'name', 'proyector',
		'movie', movie[0],
		'salign', '',
		'FlashVars',flVars);
}

////////////////////////////////////////
// Funcion para ir a un producto del catalogo de la web Corporativa
function mostrarSugerencia(Producto) {
    msgWindow=window.open("http://es.sitestat.com/wkes/elconsultor/s?esclickout.externallink&amp;ns_type=clickout&amp;ns_url=[http://tienda.wke.es/cgi-bin/wke.storefront/SP/product/"+Producto+"?wn%3D0]","Producto","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=600,height=400");
}
var opacity = 30;
var imageSrc = "../Img/popup_close.gif";
var popup = new CPopup("generic", "popup");
var PutItCenter = "";

var popup2 = new CPopup("generic2", "popup2");


/**
 * Clase que encapsula un contenedor de la pagina web.
 */
function CPopup(nombre, nombrePopup)
{
    this.nombre = nombre;
    this.content = null;
    this.main = null;
    this.header = null;
    this.titlediv = null;
    this.closeButton = null;
    this.contentDiv = null; 
    this.request = false;    
    this.width = null;
    this.height = null; 
    this.onLoadFunction = "";
    this.onUnloadFunction = "";
    this.enterFunction = "";
    this.nombrePopup = nombrePopup;
}


CPopup.prototype.Create = function CPopup_Create()
{
    this.main = document.getElementById(this.nombre);    
    if (this.main == null)
    {     
        // Configurar las propiedades del contenedor   
        // Crear el div contenedor que constituye el popup y aniadirlo al documento
        this.main = document.createElement('div');       
        this.main.className = 'popupContainer';
        this.main.id = this.nombre;         
        this.main.container = this;
        // Insertar el contenedor en la pagina
        document.body.appendChild(this.main);
        
        // Aniadir los dos divs (cabecera y contenido)
        this.header = document.createElement('div');
        this.header.id = this.main.id + '_header';
        this.header.className = 'popupHeader';
        // Asignar los eventos de movimiento a la cabecera.       
        this.header.onmousedown = this.BeginMove;
        this.header.onmouseup = this.EndMove;
        this.header.container = this;
        this.header.lastMouseX = -1;
        this.header.lastMouseY = -1;         
        this.main.appendChild(this.header); 
           
        this.titlediv = document.createElement('div');
        this.titlediv.id = this.main.id + '_divTitle'; 
        this.titlediv.className = 'divTitle'; 
        this.header.appendChild(this.titlediv); 
        
        //Crear el boton de cierre del popup
        this.closeButton = document.createElement('img');   
        this.closeButton.src = imageSrc;     
        this.closeButton.container = this;
        this.closeButton.alt = "X";
        this.closeButton.style.cursor = "pointer";
        this.header.appendChild(this.closeButton);           
        
        //Crear la capa que tendra el contenido del popup
        this.contentDiv = document.createElement('div');
        this.contentDiv.container = this;
        this.contentDiv.id = this.nombre + '_containerDivId';
        this.main.appendChild(this.contentDiv);       
        this.contentDiv.className = 'popupContent';          
    }   
    this.CreateRequest();
    return this.main;
}

CPopup.prototype.Delete = function CPopup_Delete()
{
    window.parent.focus();    
    this.main.parentNode.removeChild(this.main);
}

function GetEvent(e)
{
		if(window.event) 
				return window.event;
	  else
	  		return e;	  		
}


//Calcula el ancho del area funcional dentro del navegador
CPopup.prototype.GetBodyWidth = function CPopup_GetBodyWidth()
{
    return document.body.offsetWidth;
};

//Calcula el alto del area funcional dentro del navegador
CPopup.prototype.GetBodyHeight = function CPopup_GetBodyHeight()
{
    var height = document.all ? document.documentElement.clientHeight :  window.innerHeight;

    //en el caso de ser un IE que se ha producido una recarga de pagina
    //la funcion anterior devuelve 0, si se quiere poner en el centro.
    if(height==0 && document.all && PutItCenter=="yes")
    {
        return document.body.offsetHeight;
    }
    return height;
};

//Calcula el ancho del area funcional dentro del navegador
CPopup.prototype.GetAbsoluteBodyWidth = function CPopup_GetAbsoluteBodyWidth()
{
    return document.body.offsetWidth;
};

//Calcula el alto del area funcional dentro del navegador
CPopup.prototype.GetAbsoluteBodyHeight = function CPopup_GetAbsoluteBodyHeight()
{
    
    var iebody = (document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body;
    var dsoctop = document.all? iebody.scrollTop : pageYOffset;
    var absoluteHeight = dsoctop + this.GetBodyHeight();   
    return absoluteHeight;
};

//Recupera la coordenada X para centrar el popup
CPopup.prototype.GetPopupXCenter = function CPopup_GetPopupXCenter()
{
    var bodyWidth = this.GetBodyWidth();
    return (bodyWidth - this.width)/2;
};
 
//Recupera la coordenada Y para centrar el popup
CPopup.prototype.GetPopupYCenter = function CPopup_GetPopupYCenter()
{
    var bodyHeight = this.GetBodyHeight();    
    return (bodyHeight - this.height)/2;
};

//Redimensiona el popup
CPopup.prototype.ResizeTo = function CPopup_ResizeTo(width, height)
{
    if (width > 0)
    {
        this.width = width;
        this.main.style.width = width + "px";
    }
    if (height > 0)
    {
        this.height = height;
        this.main.style.height = height + "px";
    }
};

//Mueve el popup a las coordenadas indicadas
CPopup.prototype.MoveTo = function CPopup_MoveTo(x, y)
{
    this.main.style.top = y + "px";
    this.main.style.left = x + "px";
};

//MOVIMIENTO
CPopup.prototype.BeginMove = function CPopup_BeginMove(e)
{          
    e = GetEvent(e);
    
    if (this.container)
    {          
        document.onselectstart = new Function("return false")
        if (window.sidebar){
            document.onmousedown = function (e){return false;}
            document.onclick = function (e){return true;}
        }
        currentWindow = this.container.main;   
        currentWindow.lastMouseX = e.clientX - parseInt(currentWindow.style.left);
        currentWindow.lastMouseY = e.clientY - parseInt(currentWindow.style.top);
        document.container = this.container;
        document.onmousemove = this.container.HandleMouseMove;       
        document.onmouseup = this.container.EndMove;   
    }   
};

CPopup.prototype.HandleMouseMove = function CPopup_HandleMouseMove(e)
{   
    e = GetEvent(e);
     
    moveXBy = e.clientX - currentWindow.lastMouseX;
    moveYBy = e.clientY - currentWindow.lastMouseY;
    
    var bodyWidth = this.container.GetAbsoluteBodyWidth();
    var bodyHeight = this.container.GetAbsoluteBodyHeight();
    
    if (bodyWidth > moveXBy + this.container.width && 0 < moveXBy)
    {
		currentWindow.container.left = moveXBy;
		currentWindow.style.left = moveXBy + 'px'; 
    }
    else if (0 > moveXBy)
    {
		currentWindow.container.left = 0;
		currentWindow.style.left = '0px'; 
    }
    else if (bodyWidth < moveXBy + this.container.width)
    {
		maxim = bodyWidth - this.container.width - 3;
		currentWindow.container.left = maxim;
		currentWindow.style.left = (maxim) + 'px'; 
    }
    
    if (bodyHeight > moveYBy + this.container.height && 0 < moveYBy)
    {
		currentWindow.container.top = moveYBy;
		currentWindow.style.top = moveYBy + 'px'; 
    } 
    else if (0 > moveYBy)
    {
		currentWindow.container.top = 0;
		currentWindow.style.top = '0px'; 
    }
    else if (bodyHeight < moveYBy + this.container.height)
    {
		maxim = bodyHeight - this.container.height - 2;
		currentWindow.container.top = maxim;
		currentWindow.style.top = (maxim) + 'px'; 
    }         
};

CPopup.prototype.EndMove = function CPopup_EndMove(e)
{       
    document.onselectstart = new Function("return true")
    if (window.sidebar){
        document.onmousedown = function (e){return true;}
        //document.onclick = function (e){return false;}
    }
    document.onmousemove = null;
};

//url : url a la que tiene que llamar
//scrollbars : si queremos que el popup tenga barras de scroll
//widthPopup : ancho que le asigna al popup
//heightPopup : alto que le asigna al popup
//unit : unidad en la que se pasa el width y el height del popup (px, %)
//center: si queremos que el popup se muestre centrado en la pantalla
CPopup.prototype.OpenGenericPopup = function CPopup_OpenGenericPopup(url, scrollbars, widthPopup, heightPopup, unit, center, onLoadFunction, onUnloadFunction, titleHeader, idType) {

    // primero comprobamos si existe session y en caso afirmativo registramos estadisticas si estan activas.
    if (url.toLowerCase().indexOf("<") != -1 && url.toLowerCase().indexOf(">") != -1) {
        //Caso de que sea HTML y no URL
        var res = Wke.Presentation.WebControls.PageControl.VerifySession(document.location.href, document.location.href, idType);
    }
    else {//Caso de que sea URL
        var res = Wke.Presentation.WebControls.PageControl.VerifySession(document.location.href, url, idType);
    }

    if (res.value == "true") {
        //Si es la primera vez que se abre un popup, se debera crear dicho popup
        if (this.main == null) {
            this.Create();
        }

        // si el popup ya esta abierto creamos uno nuevo para abrir dos
        if (this.main.style.visibility == "visible") {

            
            popup2.Create();
            popup2.SettingsPopup(scrollbars, widthPopup, heightPopup, unit, center, onLoadFunction, onUnloadFunction, titleHeader);
            popup2.OpenPopup(url);
        }
        else 
        {
            this.SettingsPopup(scrollbars, widthPopup, heightPopup, unit, center, onLoadFunction, onUnloadFunction, titleHeader);
            this.OpenPopup(url);
        }
        
        
    }
    else {
        window.location.href = res.value;
    }

};

//Abrir el popup
CPopup.prototype.OpenPopup = function CPopup_OpenPopup(url)
{			
    this.main.style.visibility = "visible";	
    this.DisableWindow();
    this.LoadPopup(url);    		
};

//Cerrar el popup
CPopup.prototype.ClosePopup = function CPopup_ClosePopup() {
    if (this.nombrePopup == "popup") {
 
        if (this.onUnloadFunction != "") {
            eval(this.onUnloadFunction);
        }
        if (this.container != null) {
            popup = this.container;
        }
        else {
            popup = this;
        }
        popup.main.style.visibility = "hidden";
        popup.EnableWindow();
        if (typeof (enable_logout) == "function")
            enable_logout();

    }
    else {

        // en el caso de que sea el segundo popup
        if (this.onUnloadFunction != "") {
            eval(this.onUnloadFunction);
        }
        if (this.container != null) {
            popup2 = this.container;
        }
        else {
            popup2 = this;
        }
        popup2.main.style.visibility = "hidden";
        popup2.EnableWindow();
        if (typeof (enable_logout) == "function")
            enable_logout();
    }

};

//Asigna las propiedades al popup
CPopup.prototype.SettingsPopup = function CPopup_SettingsPopup(scrollbars, widthPopup, heightPopup, unit, center, onLoadFunction, onUnloadFunction, titleHeader) {
    PutItCenter = center;
    var bodyWidth = this.GetBodyWidth();
    var bodyHeight = this.GetBodyHeight();

    if (unit == "%") //Si es en % lo pasamos a pixeles
    {
        widthPopup = (widthPopup * bodyWidth) / 100;
        heightPopup = (heightPopup * bodyHeight) / 100;
    }

    var iebody = (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
    var dsoctop = document.all ? iebody.scrollTop : pageYOffset;

    this.GetAbsoluteBodyHeight();
    var heightContentPopup = heightPopup - 20;
    var left = center == "yes" ? (bodyWidth - widthPopup) / 2 : 1;
    var top = center == "yes" ? dsoctop + ((bodyHeight - heightPopup) / 2) : 1;
    this.main.style.width = widthPopup + "px";
    this.main.style.height = heightPopup + "px";
    this.width = widthPopup;
    this.height = heightPopup;
    this.PutTitle(titleHeader);
    this.contentDiv.height = heightContentPopup + "px";
    this.main.style.top = top + "px";
    this.main.style.left = left + "px";

    if (scrollbars == "yes") {
        this.contentDiv.style.overflow = "auto";
    }
    this.onLoadFunction = onLoadFunction;
    this.onUnloadFunction = onUnloadFunction;

    var funcionCerrar = this.nombrePopup + ".ClosePopup();"
    this.closeButton.onclick = function() { eval(funcionCerrar); }
};

//Coloca el titulo a mostrar en la cabecera del popup
CPopup.prototype.PutTitle = function CPopup_PutTitle(title)
{
    this.titlediv.innerHTML = title;
};

//Habilita la ventana principal una vez que el popup se cierra
CPopup.prototype.EnableWindow = function CPopup_EnableWindow() {

    var div = document.getElementById("disableDiv");
    if (div != null) {
        // si lo hace el popup dos no tenemos que esconder la capa sino llevarla atras
        if (this.nombrePopup == "popup2") {
            div.style.zIndex = 100000;

        }
        else {
            document.body.removeChild(div)
        }
    }
};

//Deshabilita la ventana principal mientras el popup estÃ© abierto
CPopup.prototype.DisableWindow = function CPopup_DisableWindow() {
   
    var div = document.getElementById("disableDiv");
    if (div == null) {
        div = document.createElement("div");
        div.style.opacity = (opacity / 100);
        div.style.MozOpacity = (opacity / 100);
        div.style.KhtmlOpacity = (opacity / 100);
        div.style.filter = "alpha(opacity=" + opacity + ")";
        div.id = "disableDiv";
        div.className = "disableDiv";
        document.body.appendChild(div);
        
        }

        // si esta funcion la llama el popup 2 hay que desabilitar el popup 1.
        if (this.nombrePopup == "popup2") {
            div.style.zIndex = 100002;
        
    }
    div.style.height = document.getElementById("cContainer").offsetHeight + "px";
};

//Crea el objeto XMLHttpRequest para realizar la peticion de la pagina a cargar en el popup
CPopup.prototype.CreateRequest = function CPopup_CreateRequest()
{
    try 
    {
        this.request = new XMLHttpRequest();
    } 
    catch (trymicrosoft) 
    {
        try 
        {
            this.request = new ActiveXObject("Msxml2.XMLHTTP");
        } 
        catch (othermicrosoft) 
        {
            try 
            {
                this.request = new ActiveXObject("Microsoft.XMLHTTP");
               } 
            catch (failed) 
            {
                this.request = false;
            }
        }
    }
}

//Realiza la peticion de la pagina a cargar en el popup
CPopup.prototype.LoadPopup = function CPopup_LoadPopup(content) {
    if (!this.request) {
        alert("ERROR AL INICIALIZAR!");
    }
    else {
        if (content.toLowerCase().indexOf("<") != -1 && content.toLowerCase().indexOf(">") != -1)
        //Caso en el que nos llega html.
        {
            this.contentDiv.innerHTML = '<p style="margin-top: 200px;text-align:center;"><img src="../Img/popup_load.gif" /></p>';
            this.contentDiv.innerHTML = content
        }
        else //Caso de que el contenido sea una url.
        {
            if ((content.toLowerCase().indexOf(".gif") != -1) || (content.toLowerCase().indexOf(".jpg") != -1) || (content.toLowerCase().indexOf(".png") != -1)) {
                this.contentDiv.innerHTML = '<img src="' + content + '" />';
            }
            else {
                this.contentDiv.innerHTML = '<p style="margin-top: 200px;text-align:center;"><img src="../Img/popup_load.gif" /></p>';
                this.request.open("GET", content);
                //this.request.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" );
                var popupAux = this;
                this.request.onreadystatechange = function() {
                if (popupAux.request.readyState == 4) {
                        //popup.contentDiv.innerHTML = popup.request.responseText;
                        popupAux.contentDiv.innerHTML = popupAux.request.responseText;
                        popupAux.enterFunction = RecoverEnterFunction(popupAux.request.responseText);
                        if (popupAux.onLoadFunction != "") {
                            eval(popupAux.onLoadFunction);
                        }
                    }
                }
                this.request.send(null);
            }
        }
    }
};

document.onkeydown = function (e) {
    var div = document.getElementById("disableDiv");
    if (div != null)
    {     
        //solamente controlamos este evento cuando esté abierto el popup   
        e = e?e:event;		   
        if (e.keyCode == 27)
        {
            window.close();
        }
        else if (e.keyCode == 116)
        {
            return false;
        }
        else if (e.keyCode == 13)
        {
            eval(popup.enterFunction);
        }
    }
};

function RecoverEnterFunction(text)
{
    var textToFind = "var functionEnter = \"";
    var firstPos = text.indexOf(textToFind);
    var enterFunction = "";
    if (firstPos != -1)
    {
        firstPos += textToFind.length;
        var lastPos = text.indexOf("\";", firstPos + 1);
        enterFunction = text.substr(firstPos, lastPos - firstPos);
        enterFunction = enterFunction.replace(";","");
    } 
    return enterFunction;
}

function genericClosePopup() {

    if (popup2.main!=null &&  popup2.main.style.visibility == "visible") {
        popup2.ClosePopup();
    }
    else {
        popup.ClosePopup();
    }
}

ï»¿function AddOrRemoveNewsletterSubscription(newsletter, obj, typeAlert) {
    var hash = new Object();
    hash.newsletter = newsletter;
    hash.typeAlert = typeAlert;

    if (obj.checked) {
        hash.operation = 'add';
    }
    else {
        hash.operation = 'delete';
    }

    var res = Wke.Presentation.WebControls.NewsletterListControl.AddOrDeleteSubscription(hash);

    // Tratar error
    if (res.value.error != "") {
        alert(response.value.error);
    }
}



function preparar_formulario(node){
  if (node) {
    var info_rtf = node.children;
    //var img_dir = unescape(info_rtf['rtfdir'].src);
    var img_dir = "/o8/img/sp.gif";
    img_dir = img_dir.replace(/sp\.gif$/,"");
    var rtf_dir = img_dir.replace(/img/,"rtf");
    var src = info_rtf['ID'].innerText;
    var newTxt = "";
    newTxt = newTxt + "<div align=right><IMG ";
    newTxt = newTxt + "SRC='" + img_dir + "editor_form.gif' ";
    newTxt = newTxt + "style=cursor:hand onclick='lanzarFormulario(\"" + rtf_dir + "\", \"" + src + "\")'";
    newTxt = newTxt + "></div>";
    //node.outerHTML = newTxt;
    document.write (newTxt);
  }
}

function lanzarFormulario(path, id){

  //var dst = "/o8/rtf/lector.html?http://rtfs.wke.es/" + id.substring(8, 9) + "/" + id.substring(9, 10) + "/" + id.substring(10, 11) + "/" + id.substring(11, 12) + "/" + id.toUpperCase() + ".RTF";
  var dst = "/o8/rtf/lector.html?" + rtfsRepository + "/" + id.substring(8, 9) + "/" + id.substring(9, 10) + "/" + id.substring(10, 11) + "/" + id.substring(11, 12) + "/" + id.toUpperCase() + ".RTF";
  var ventana = window.open(dst, "_blank", "fullscreen=1,titlebar=0,directories=0,location=no,menubar=0,resizable=0,scrollbars=no,status=0,toolbar=0");
}

function VolverDocumento(){
  window.close();
}

function definirControl(loc) {
    // loc es el objeto window.location
    var theSearch = loc.search;
    var theHref = loc.href;

    // Quitamos el resto de parametros. Seran IDD y Version(se quitan pq sino el OCX no abre el documento) 
    theSearch = theSearch.split("&")[0];
    theHref = theHref.split("&")[0];
    
  var txt =  "<OBJECT " + estilo() + classID() + nombre() + " >"
//        + parametro( "titulo"  , " ESTE ES EL TITULO DEL FORMULARIO" )
          + parametro( "titulo"  , " " )
          + parametro("caption", theSearch.substring(theSearch.lastIndexOf("/") + 1, theSearch.lastIndexOf(".")))
          + parametro("documento", unescape(theHref))
          + "<table width='100%' border=0 cellpadding=0 cellspacing=0 ><tr><td height='15%'>&nbsp;</td></tr><tr><td align='left' width='5'></td><td><table border=0 cellpadding=0 cellspacing=0 width='500'><TR><TD valign=top height=10 align=right></TD></TR><TR><TD valign=top height=78 align=right><A HREF='http://www.laleydigital.es'><IMG SRC=../img/logo_laleydigital.jpg border=0 valign='middle'></A></TD></TR><TR><TD valign=top height=10 align=right></TD></TR></table><table align=center border=0 cellpadding=0 cellspacing=0 width=500><tr><td align=center><p align='center' style='font-family:Arial,Helvetica,sans-serif;color:steelblue;font-size:18px;font-weight:bold;text-decoration:none;'>Download OCX</p><p align=justify style='font-family:Arial,Helvetica,sans-serif;'>Para poder ejecutar el visualizador de ficheros RTF, es necesario tener instalado un componente. Desde esta página, usted se lo puededescargar e instalar en su ordenador.</p><p align=justify style='font-family:Arial,Helvetica,sans-serif;'>Pulse aqui para <a  style='font-family:Arial,Helvetica,sans-serif;color:steelblue;font-weight:bold;text-decoration:none;cursor:hand' href='../"+pathOcx+"/formularios.msi'>bajarse el visualizador (winXP 0 2000)</a></p><p align=justify style='font-family:Arial,Helvetica,sans-serif;'>Pulse aqui para <a style='font-family:Arial,Helvetica,sans-serif;color:steelblue;font-weight:bold;text-decoration:none;cursor:hand' href='../"+pathOcx+"/formularios.exe'>bajarse el visualizador (resto de versiones)</a></p><p align=justify style='font-family:Arial,Helvetica,sans-serif;'>Una vez iniciada la descarga, puede cerrar esta ventana haciendo click <a href='#' onclick ='window.close();' style='font-family:Arial,Helvetica,sans-serif;color:steelblue;font-weight:bold;text-decoration:none;cursor:hand'>aquí</a>.</p></td></tr></table></td></tr></table>"
          + "</OBJECT>"
          + "<SCRIPT LANGUAGE='javascript' FOR='objFormWKE' EVENT='OnBack'>VolverDocumento();</SCRIPT>"
          ;
  document.write( txt );
}


function estilo(){
  return "style='position:absolute;top:0;left:0; "
       + "height:expression(document.body.clientHeight);width:expression(document.body.clientWidth);' "
       ;
}

function classID(){
  return "CLASSID='clsid:C6A4F684-E9E5-4D45-BEC5-9529033F2AEE' ";
}

function nombre(){
  return "id='objFormWKE' "
}

function eventoVolver(){
  return "<SCRIPT LANGUAGE='javascript' FOR='objFormWKE' EVENT='OnBack'>VolverDocumento();</SCRIPT>";
}

function parametro( nombre, valor ){
  return "<PARAM"
         + " name ='" + nombre + "'"
         + " value='" + valor  + "'"
         + "></PARAM>"
         ;
}

if(typeof Wke == "undefined") Wke={};
if(typeof Wke.Presentation == "undefined") Wke.Presentation={};
if(typeof Wke.Presentation.WebControls == "undefined") Wke.Presentation.WebControls={};
Wke.Presentation.WebControls.HtmlViewerControl_class = function() {};
Object.extend(Wke.Presentation.WebControls.HtmlViewerControl_class.prototype, Object.extend(new AjaxPro.AjaxClass(), {
	LoadInnerHtml: function(hash) {
		return this.invoke("LoadInnerHtml", {"hash":hash}, this.LoadInnerHtml.getArguments().slice(1));
	},
	Redirect: function(hash) {
		return this.invoke("Redirect", {"hash":hash}, this.Redirect.getArguments().slice(1));
	},
	GetLinkCommentsDocument: function(idd, version, verifyDocType) {
		return this.invoke("GetLinkCommentsDocument", {"idd":idd, "version":version, "verifyDocType":verifyDocType}, this.GetLinkCommentsDocument.getArguments().slice(3));
	},
	url: '/ajaxpro/Wke.Presentation.WebControls.HtmlViewerControl,Wke.Presentation.ashx'
}));
Wke.Presentation.WebControls.HtmlViewerControl = new Wke.Presentation.WebControls.HtmlViewerControl_class();


//Despliega todas las carpetas hasta llegar al documento que se ha pulsado para mostrar
function OpenFoldersViewer(nodeId,tdcoption) 
{
    if ((tdcoption != "") || (tdcoption != null)) {
        if (document.getElementById(tdcoption) != null) {
            document.getElementById(tdcoption).onclick();
            if (document.getElementById(nodeId).nodeName != 'DFN') {
                ExpandNode(nodeId);
            }
            else {
                var node = document.getElementById(nodeId);
                LoadingViewer(node.parentNode.id, nodeId);
                ExpandNode(nodeId);
            }
        }
        else {
            if (document.getElementById(nodeId).nodeName != 'DFN') {
                ExpandNode(nodeId);
            }
            else {
                var node = document.getElementById(nodeId);
                LoadingViewer(node.parentNode.id, nodeId);
                ExpandNode(nodeId);
            }
        }
    } 
}

function GotoAnchor(id)
{   
    var obj = document.getElementById(id);
    if (obj)
    {
        obj.scrollIntoView(true);
    }
}

//Esta funcion es obsoleta ya que la que se encuentra en uso esta en el EbookControl.js
//function RedirectionEBOOK(node, filename, verifyDocType, redirectPage, repositoryPath, bdeFormat) {
//    var nodeaux=this;
//    if (node!= null){document.getElementById("htmlViewer_Node").value = node.parentNode.id;}
//    else{document.getElementById("htmlViewer_Node").value = "";}
//    if (filename!= null){document.getElementById("htmlViewer_Filename").value = filename;}
//    else{document.getElementById("htmlViewer_Filename").value = "";}
//    if (verifyDocType!= null){document.getElementById("htmlViewer_VerifyDocType").value = verifyDocType;}
//    else{document.getElementById("htmlViewer_VerifyDocType").value = "";}
//    if (redirectPage!= null){document.getElementById("htmlViewer_RedirectPage").value = redirectPage;}
//    else{document.getElementById("htmlViewer_RedirectPage").value = "";}
//    if (repositoryPath!= null){document.getElementById("htmlViewer_RepositoryPath").value = repositoryPath;}
//    else{document.getElementById("htmlViewer_RepositoryPath").value = "";}
//    if (bdeFormat != null) { document.getElementById("htmlViewer_bdeformat").value = bdeFormat; }
//    else {document.getElementById("htmlViewer_bdeformat").value = "";}
//    document.getElementById("htmlViewer_BtnRedirect").click();
//}

function HtmlViewerCache(target, method) {
    var obj = new Object();
    obj.nodeTdc = "";
    obj.MenuOption = "";
    AjaxCachePageControl_load(target, method, obj, HtmlViewerLoadCallback);
}

function HtmlViewerLoadCallback(res) {
    if (res != null) {
        if (res.value.nodeTdc != "") {
            OpenFoldersViewer(res.value.nodeTdc, res.value.MenuOption);
        }
    }
}

function Positioning(nodeid) 
{
    var pos = document.getElementById(nodeid);
    if (pos!=null)
        pos.scrollIntoView(false);
}

function ExpandNode(nodeId) {
    if (nodeId != "") {
        var principalDiv = document.getElementById(nodeId);
        if (principalDiv != null) {
            if (principalDiv.hasChildNodes())
            // So, first we check if the object is not empty, if the object has child nodes
            {
                var children = principalDiv.childNodes;
                var i = 0;
                var stop = false;
                while ((i < children.length) && (!stop)) {
                    if (children[i].nodeName == "A") {
                        stop = true;
                        children[i].className = "isis-b";
                    };
                    i++;
                };
            };

            while (principalDiv.parentNode != null) 
            {
                principalDiv = principalDiv.parentNode;

                if ((principalDiv.nodeName == "DT")) {
                    //Toggle(imageFolder);
                    principalDiv.className = 'dop';
                };
                
                if ((principalDiv.nodeName == "DD")) {
                    //Toggle(imageFolder);
                    principalDiv.className = 'op';
                };
                
                if ((principalDiv.nodeName == "DL")) {
                    //Toggle(imageFolder);
                    principalDiv.className = 'op';
                };

                if (principalDiv.hasChildNodes())
                // So, first we check if the object is not empty, if the object has child nodes
                {
                    var children = principalDiv.childNodes;

                    var i = 0;

                    while ((i < children.length)) {
                        if (children[i].nodeName == "DD") {
                            children[i].className = "op";
                        };
                        i++;
                    };
                };
                for (i = 0; i < principalDiv.childNodes.length; i++) 
                {
                    if (principalDiv.childNodes[i].nodeName == "DT") 
                    {
                        principalDiv.childNodes[i].className = "dop";
                        break;
                    }
                }
            };
        }
    }
    setTimeout("Positioning('" + nodeId + "')", 200);
}

//Obtiene el link de acceso a documento, situandose en los comentarios.
function RedirectCommentsDocument(idd, version, verifyDocType) {
    var url = Wke.Presentation.WebControls.HtmlViewerControl.GetLinkCommentsDocument(idd, version, verifyDocType.toString());
    document.location.href = url.value;
}
/* EMG: 15/11/2007 FUNCIONALIDAD DOCUMENTOS */
/* MODIFICACIONES: 11/01/2008, 04/12/2007, 11/12/2007 */
if (document.implementation) {
	if (document.implementation.hasFeature('Events','2.0')) {
		var DOM2 = true;
	} else {
		var DOM1 = true;
		var elmObj = null;
	}
} else {
	if (document.getElementById) {
		var DOM1 = true;
		var elmObj = null;
	}
}


function Iniciar(menuId,tipo) {		
	if (!DOM1 && !DOM2) {return null;}
	var Menu = document.getElementById(menuId);
	var Submenues = Menu.getElementsByTagName(tipo);
	var SubmenuesLength = Submenues.length;
	var Menux;
	for (var i = 0; i < SubmenuesLength; i++) {
	if (	tipo =='dl'){
		Menux = Submenues[i];
	} else if (tipo =='ul'){
		Menux = Submenues[i].parentNode;
	} else if (tipo =='li'){
		Menux = Submenues[i];
	}
		while (Menux.nodeName=="#text"){
			Menux = Menux.nextSibling;
    		}
		if (DOM2) {
			if (	tipo =='dl'){
				Menux.firstChild.addEventListener('click', OpenDL, 0);	
			} else if (tipo =='ul'){
				Menux.addEventListener('click', OpenUL, 0);	
			} else if (tipo =='li'){
				Menux.addEventListener('click', OpenUL, 0);	
			}
		}
		if (DOM1) {
			if (	tipo =='dl'){
				Menux.firstChild['onclick']=new Function('OpenDL(this);');
			} else if (tipo =='ul'){
				Submenues[i].parentNode['onclick']=new Function('OpenUL(this);');
			} else if (tipo =='li'){
				if(Submenues[i].className != "ExISISc" && Submenues[i].className != "ExISISo" ){				
					Submenues[i]['onclick']=new Function('OpenUL(this);');
				}
			}
		}
	}
}
// EXPANDIR TODO ISIS
function ExISIS() {
	if (!DOM1 && !DOM2) {return null;}
	var Menu = document.getElementById('ISIS');
	var MenuEx = Menu.getElementsByTagName('li');
	var LinkEx = Menu.firstChild;
	while (LinkEx.nodeName=="#text"){
		LinkEx = LinkEx.nextSibling;
		}
    var estiloActual = LinkEx.className;
	var MenuExLength=MenuEx.length;
	for (var i = 0; i < MenuExLength; i++) {
		if (estiloActual == 'ExISISc') {
			if (	MenuEx[i].className =='cl'){
				MenuEx[i].className ='op'
				
			}
		} else if (estiloActual == 'ExISISo') {
			if (	MenuEx[i].className =='op'){
				MenuEx[i].className ='cl'
			}
		}
	}
	RecorreExISIS(estiloActual);
	LinkEx.className = (estiloActual=='ExISISc') ? 'ExISISo' : 'ExISISc';
}
function RecorreExISIS(estiloActual) {
	if (!DOM1 && !DOM2) {return null;}
	var Menu = document.getElementById('ISIS');
	var Submenues = Menu.getElementsByTagName('ul');
	var SubmenuesLength=Submenues.length;
	for (var i=0; i < Submenues.length; i++) {
		if (estiloActual == 'ExISISc') {
			Submenues[i].className  =  'op';
			Submenues[i].parentNode.className  =  'op';
		} 
		if (estiloActual == 'ExISISo') {
			Submenues[i].className  =  'cl';
			Submenues[i].parentNode.className  =  'icl';
		}
	}
}
function cComent(){ 
	var bComent = document.getElementById('dCm');
	var dTxT  = document.getElementById('dTxT');
  	var refTags = dTxT.getElementsByTagName('cite');
	var estiloActual = bComent.className;

	if (typeof refTags != "undefined") {
	    RecorreC(refTags, estiloActual )
	    
	}

	// Ahora tambien los div ccn con class son comentarios.
	var arrayDivs = dTxT.getElementsByTagName('div');
	RecorreC(arrayDivs, estiloActual);
	
	bComent.className = (estiloActual == 'dCmO') ? 'dCmC' : 'dCmO';
}

function RecorreC(refTags, refTagsActual) {
    if (refTagsActual == "dCmO") {
        var refTagsLength = refTags.length;
        for (var i = 0; i < refTagsLength; ++i) {
            if (Element_classList(refTags[i]).contains("ccn")) {
                Element_classList(refTags[i]).add("ccnOff");
                Element_classList(refTags[i]).remove("ccn");
            }
        }
    }
    if (refTagsActual == "dCmC") {
        var refTagsLength = refTags.length;
        for (var i = 0; i < refTagsLength; ++i) {
            if (Element_classList(refTags[i]).contains("ccnOff")) {
                Element_classList(refTags[i]).add("ccn");
                Element_classList(refTags[i]).remove("ccnOff");
            }
        }
    }
}

function SelectDL(E)
{
    var dt = document.getElementById(E).getElementsByTagName("DT")[0];
    if(dt.className == "dcl" || dt.className == "")
    {
        dt.className = "dop";
    }
    else if(dt.className == "dop")
    {
        dt.className = "dcl";
    }
    var dd = document.getElementById(E).getElementsByTagName("DD");
    for(var i = 0; i< dd.length; i++)
    {
        if(dd[i].parentNode.id == E)
        {
            if(dd[i].className == "cl" )
            {
                dd[i].className = "op";
                
            }
            else if(dd[i].className == "op"|| dd[i].className == "cPt")
            {
                dd[i].className = "cl";
            } 
        }
    }
    GotoAnchor(E);
}
function OpenDL(E) {
	var elmLI = (DOM1) ? E : E.currentTarget;
	
	if (DOM1) {
		  if (elmObj == null) elmObj = elmLI;
		  if (elmObj.parentNode == elmLI) return elmObj = elmLI;
	}
	if (DOM2) {
		if (elmLI.nodeName!='DT') {
			return null;
		}
	}
	var estiloActual = elmLI.nextSibling.className;
			if (elmLI.nextSibling.nodeName=='DD') {
				estiloActual = elmLI.nextSibling.className;
				if (estiloActual=='cl'){
					elmLI.className= elmLI.className.replace(/ dcl/, "");
					elmLI.className +=' dop';
				}
				else if (estiloActual=='op'){
					elmLI.className= elmLI.className.replace(/ dop/, "");
					elmLI.className +=' dcl';
				} else {
					elmLI.className +=' dcl';
				}
				
				elmLI.nextSibling.className = (estiloActual=='cl') ? 'op' : 'cl';
			} 
	if (DOM1) elmObj = elmLI;
	if (DOM2) E.stopPropagation();
}
function OpenUL(E) {
	var elmLI = (DOM1) ? E : E.currentTarget;
	if (DOM1) {
		  if (elmObj == null) elmObj = elmLI;
		  if (elmObj.parentNode.parentNode == elmLI) return elmObj = elmLI;
	}
	if (DOM2) {
		if (elmLI.nodeName!='LI') {
			return null;
		}
	}
	var estiloActual;
		for (var i=0; i < elmLI.childNodes.length; i++) {
			if (elmLI.childNodes[i].nodeName=='UL') {
				estiloActual = elmLI.childNodes[i].className;
				if (estiloActual=='cl'){
					elmLI.className= elmLI.className.replace(/ icl/, "");
					elmLI.className +=' iop';
				}
				else if (estiloActual=='op'){
					elmLI.className= elmLI.className.replace(/ iop/, "");
					elmLI.className +=' icl';
				} else {
					elmLI.className +=' icl';
				}
				elmLI.childNodes[i].className = (estiloActual=='cl') ? 'op' : 'cl';
			} 
		}
	if (DOM1) elmObj = elmLI;
	if (DOM2) E.stopPropagation();
}
// <a href="javascript:Ancla('LE0000048213_20060530.HTML#IDAPUP4I', 'TXT', this)">3.Ejecución del planeamiento:</a>
function Ancla(ancla, target)
{
	ancla = ancla.replace(/.*#/, "");
	location = "#"+ancla;
}
function salto_ancla(ancla, target)
{
    ancla = ancla.replace(/.*#/, "");
    location = "#"+ancla;
}
function DerogacionFutura(link,fecha,texto)
{
	if (fecha) {
	    var hoy = new Date();
	    var derogacion = new Date();   
	    derogacion.setMonth(fecha.substring(4, 6)-1);
	    derogacion.setYear(fecha.substring(0, 4));
	    derogacion.setDate(fecha.substring(6, 8));
	    if (derogacion.getTime() <= hoy.getTime()) {
			var md  ='<p class="derogacion">';
			    md +='<a href='+link+' >';
			    md +=texto;
			    md +='</a>';
			    md +='</p>';
			document.write(md);
		document.write(" <style type=\"text/css\"> ");
		document.write("#cVe li.d	 {color:#C00;}");
		document.write("#cVe li.derF 	 {color:#FFF;background-color:#C00;}");
		document.write("#cVe li.derF a {color:#FFF;font-weight:bold;}");
		document.write(" </style> ");
	    }
	} 
}
/* FUNCIONES DE FORMULARIOS */
// Open Nota Ayuda
function vNt(idNT){
//	var verNota    = document.getElementById(idNT);
//	var estadoNota	= verNota.className;
//	verNota.className = (estadoNota=='nCl') ? 'nOp' : 'nCl';
return; //con los nuevos tooltip es innecesaria
}
// Close Nota Ayuda
function cNt(id){
//	var capa    = document.getElementById(id).style;
//	capa.display  = 'block';
//	capa.display = 'none';
//	capa.visibility = 'hidden';
//	capa.display  = 'block';
	return; //con los nuevos tooltip es innecesaria
}

//Funcion para redirigirnos al documento vigente
function salto_a_vigente(version_vigente)
{
    var loc = String(document.location);
    var ancla = "";
    var res = loc.match(/(#\w+)$/, "");
    if (res)
    	ancla = res[1];
	document.location.replace(version_vigente + ancla);
}
/**/
function CagarBotonera(){}
function GenerarBotonera(){}
function corregirBugIE(){}
function abrir_ventana(urld) {
	var nPrcentScrW = 80;
	var nPrcentScrH = 70;
	var ancho = screen.width*nPrcentScrW/100;
	var alto = screen.height*nPrcentScrH/100;
	var posX = (screen.width-ancho)/2;
	var posY = (screen.height-alto)/2;
	var features = "width=" + ancho + ",height=" + alto + ",left=" + posX + ",top=" + posY + ",resizable=yes,status=yes,scrollbars=yes,titlebar=1,directories=1,location=yes,menubar=1,";
	window.open(urld,"",features);
}

function EditarFO(idd)
{
    var len;
    var posicion= idd.indexOf("_");
    if (posicion>=0)
    {
        // si tiene version
        len = posicion-4
    }
    else
    {
        // si no tiene version
        len = idd.length-4;
    }

    var iddAndVersion = idd.split("_");
    var formUrl = document.location.href;
	
	var ruta = idd.substr(len,1) + "/" + idd.substr(len+1,1) + "/" + idd.substr(len+2,1) + "/" + idd.substr(len+3,1) + "/" + idd + ".RTF";
    // Anadimos idd y version como parametro pq sino despues de editar no se puede imprimir ya que el pagecontrol de lector.aspx deja a vacio idd y version.
	//var urlpdf = "lector.aspx?http://rtfs.wke.es/" + ruta.toUpperCase() + "&idd=" + iddAndVersion[0] + "&version=" + iddAndVersion[1];
	var urlpdf = readerPage + "?" + rtfsRepository + "/" + ruta.toUpperCase() + "&idd=" + iddAndVersion[0] + "&version=" + iddAndVersion[1];
	
	//abrir_ventana_pdf(urlpdf); Lo comentamos para solucionaar el problema sobre el IE 6
    //var features="fullscreen=no,top=0,left=0"; Lo ponemos a pantalla completa pq en el IE6 se quedaba como descuadrado.
    var features="fullscreen=yes,top=0,left=0";
    if (!document.all)
    {
          //wcExport_convertFile();
		var hash = new Object();
		hash.extension = "doc";
		hash.documentPart = "text";
		hash.selectedText = "";
		//Esta variable la crea el DocumentControl cuando recupera tanto el titulo del documento 
		//como el que se debe mostrar en la exportacion e impresion de texto seleccionado
		hash.titleDocExportPrint = titleExportPrint;
		hash.idd = "";
		hash.version = "";   
		
		
		hash.checkedIsAllowed= checkedIsAllowed;
              
        target = "Wke.Presentation.WebControls.ExportControl";
        method = "ConvertFile";
        
        //AjaxControl_Default(target, method, hash, wcExport_redirection_callback);  
        var res=Wke.Presentation.WebControls.DocumentControl.ConvertFile(hash);  
                //Wke.Presentation.WebControls.DocumentControl.EncodeQLink  
        if (res.value!=null)
        {
            if (res.value.hasNotPermission != null)
		    {
		        alert(htmlNoPermissionsJavascript);
		    }
		    else
		    {
                swlogin=true;
                window.open('./ExportPage.aspx');
		    }
        }
        else
        {
            alert(wcExport_message_ExportError);
        }
            
    }
    else
    {
        window.open(urlpdf, "", features);
        document.location.href = formUrl;
	}
}
function openPdf(idd)
{
	var len = idd.length-4;
	var ruta = idd.substr(len,1) + "/" + idd.substr(len+1,1) + "/" + idd.substr(len+2,1) + "/" + idd.substr(len+3,1) + "/" + idd + ".pdf";
	var urlpdf = pdfsRepository + ruta.toLowerCase();
	abrir_ventana_pdf(urlpdf);
}
function abrir_ventana_pdf(urld) {
	var nPrcentScrW = 80;
	var nPrcentScrH = 70;
	var ancho = screen.width*nPrcentScrW/100;
	var alto = screen.height*nPrcentScrH/100;
	var posX = (screen.width-ancho)/2;
	var posY = (screen.height-alto)/2;
	var features = "width=" + ancho + ",height=" + alto + ",left=" + posX + ",top=" + posY + ",resizable=yes,status=no,scrollbars=no";
	window.open(urld,"",features);
}




function Al_Presionar_combo(e)
{
   var keycode;
	if (window.event)
	{
		keycode = window.event.keyCode;
	}
	else if (e)
	{
		keycode = e.which;
	}
	else
	{
		return true;
	}
    if (keycode == 13) {
        swlogin=false;
	    salto_art_combo();
	    if(document.all)
	        e.returnValue = false;
	    else
	    {
	    e.stopPropagation();
        e.preventDefault();
        }
	    return false;
    }    
}




function IsNumeric(sText)

{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (var i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
   }
   
   
   var msgnumber='';

function salto_art_combo()
{
	var ancla    = document.getElementById('tipo_busq_art');
	var tipoAncla = ancla[ancla.selectedIndex].value;
	var numero = document.getElementById('num_busq_art').value;
	var oldsubmit;
	if(numero == "") {
	    if (!document.all) {
            var form = document.forms[0];
            oldsubmit = form.onsubmit;
            form.onsubmit = function() { return false; };
            alert("Introduzca el n\u00famero de art\u00edculo o disposici\u00f3n");
            form.onsubmit = oldsubmit;
        }
        else
	       alert("Introduzca el n\u00famero de art\u00edculo o disposici\u00f3n");
	} 
	else if (IsNumeric(numero)==false){
        if(!document.all){
            var form  = document.forms[0];
            oldsubmit=form.onsubmit;
            form.onsubmit = function() { return false; };
            alert(msgnumber);
            form.onsubmit = oldsubmit;
        }
  	    else
            alert(msgnumber); 
    }
    else {
    numero = numero.replace(/[.,-]/, "");
    tipoAncla  += numero;
    location = "#"+tipoAncla;
    }
}

function Al_Presionar_caja(e)
{
    var keycode;
	if (window.event)
	{
		keycode = window.event.keyCode;
	}
	else if (e)
	{
		keycode = e.which;
	}
	else
	{
		return true;
	}
    if (keycode == 13) {
	    swlogin=false;
	    salto_art_caja();
	    if(document.all)
	        e.returnValue = false;
	    else
	    {
	    e.stopPropagation();
        e.preventDefault();
        return false;
	    }
	}     
}
//Función de búsqueda de un artículo determinado del documento
function salto_art_caja(ventana) {
    var numero = document.getElementById('num_busq_art').value;
    numero = numero.replace(/\./g, "");
    numero = numero.replace(/\*/g, "");
    numero = numero.replace(/ /g, ""); 
    
    goToFragmentDocumentAnchor("art_" + numero.toUpperCase());
}
function ImgOP(capaId,elemento){
	if (!DOM1 && !DOM2) {return null;}
	var capa = document.getElementById(capaId);
	var tipo = capa.getElementsByTagName(elemento);
	for (var i=0; i < tipo.length; i++) {
		if (elemento =='img'){
			nameImg = tipo[i].id;
			if(nameImg!=""){
			    vImg(nameImg);
		    }
		}
	}
}

//funcion javascript que nos muestra u oculta las imagenes del documento
function vImg(imgdoc)
{
    var len = imgdoc.length - 4;
    var ruta = pathImportantImages;
	ruta += imgdoc.substr(len,1) + "/" + imgdoc.substr(len+1,1) + "/" + imgdoc.substr(len+2,1) + "/" + imgdoc.substr(len+3,1) + "/" + imgdoc.toLowerCase(); ;
	var ImgDoc = ruta+".jpg";
	var ImgSrc;
		var estiloActual;
			if ( document.getElementById(imgdoc) ){ 
				ImgSrc = document.getElementById(imgdoc);
				ImgSrc.src = ImgDoc;
				estiloActual = ImgSrc.className;
				ImgSrc.className = (estiloActual=='op') ? 'cl' : 'op';	
			}}

function oImg(nameImg){
	var capa    = document.getElementById(nameImg);
	var estilo	= capa.className;
	capa.className = (estilo=='op') ? 'cl' : 'op';
}

function Control() {
    setTimeout('ControlAux()', 1);
    setOnKeyPress();
}

function ControlAux(){
	if (document.getElementById('ISIS') ){ 
		Iniciar('ISIS','li');
	}
	if (document.getElementById('voces') ){ 
		Iniciar('voces','li');
	}
	if (document.getElementById('sDt') ){ 
		Iniciar('sDt','li');
	}
	if (document.getElementById('dFiC') ){ 
		Iniciar('dFiC','dl');
    }
    if (document.getElementById('dSubv')) {
        Iniciar('dSubv', 'dl');
    }
	if (document.getElementById('dHPlus') ){ 
		Iniciar('dHPlus','dl');
	}
	if (document.getElementById('HisArt') ){ 
        Iniciar('HisArt','dl');
    }
		
	if (document.getElementById('tBody')) { 
		var tipoDoc = document.getElementById('tBody');
		if (tipoDoc.className == "BL")
		{
			ImgOP('tBody','img');
		} 
		if (tipoDoc.className == "NE")
		{
			ImgOP('tBody','img');
		}
		if (tipoDoc.className == "DT")
		{
			ImgOP('tBody','img');
		}
		if (tipoDoc.className == "FO")
		{
		    ImgOP('tBody','img');
			NotasAyudaFormularios('cCn','a');
        }
        if (tipoDoc.className == "PR") 
        {
            ImgOP('tBody', 'img');
        }
	}
	if (document.getElementById('fBody')) { 
		var tipoDoc = document.getElementById('fBody');
		if (tipoDoc.className == "BL")
		{
			ImgOP('fBody','img');
		} 
		if (tipoDoc.className == "NE")
		{
			ImgOP('fBody','img');
		}
		if (tipoDoc.className == "DT")
		{
			ImgOP('fBody','img');
		}
    }

    //Se habilita o deshabilita la barra de herramientas de los documentos de Atlas de Ciss.
    if (checkMatterForButtonBar == 'True')
    {
        if (document.getElementById('dHQLink'))
        {
            if (viewButtonBar == 'True') {
                document.getElementById('dHQLink').style.display = "block";
            }
            else
            {
                document.getElementById('dHQLink').style.display = "none";
            }
        }
    }
    
    //si es un documento por fragmentos tratamos el IVER
    if (typeof(documentLastFragmentCode)!='undefined' && documentLastFragmentCode != "") {
        ControlIver();
    }
}

///********Tratamiento de las capas de ayudas de los formularios ****/

// Función que prepara la capa del tooltip
function PrepareTooltip() {
    
    var h;
    h = document.createElement("span");
    h.id = "btc";
    h.setAttribute("id", "btc");
    h.style.position = "absolute";
    h.style.zIndex = 99999;
    document.getElementsByTagName("body")[0].appendChild(h);
}

//Funcion que inicializa las ayudas de los formularios
//capaid:capa de contenido ddonde se encuentran las ayudas, generalmente cCn
//elemento: tipos de elemnto a los que se le aplicaran las ayudas
function NotasAyudaFormularios(capaId,elemento){
    if (!DOM1 && !DOM2) {return null;}
	//Lo utilizamos para mostrar un texto cuando pasas el raton por encima de una imagen.
	var arr=document.getElementById(capaId).getElementsByTagName(elemento);

	//preparo el tooltip
	if (!document.getElementById || !document.getElementsByTagName) return;	
	PrepareTooltip();    
	var txt;
    var layer;
    var capa;
	for(var idarr=0;idarr<arr.length;idarr++){
	    if (arr[idarr].className =="nh"){
	        txt="";
	        layer=null;
	        capa="";
	        capa = arr[idarr].href.replace("javascript:vNt('","");
	        capa=capa.replace("')","");
            layer=document.getElementById(capa);
            if(layer.tagName=="CITE")
                txt=layer.innerHTML;//obtenemos el texto                    
            arr[idarr].id="hlp_" + capa;//le damos un id al anchor
            if (txt!="")
                CreateTooltip(arr[idarr],txt);
	    }
	}
}

//funcion para crear el tooltip
//el:elemnto al que se le agregara el tooltip
//txt:mensaje del tooltip
function CreateTooltip(el,txt){
    var tooltip,b,s,l;
    if(txt==null || txt.length==0) txt="link:";
    tooltip=CreateEl("span","helpFormtooltip");
    s=CreateEl("span","top");
    s.innerHTML=txt;
    tooltip.appendChild(s);
    b=CreateEl("b","bottom");
    tooltip.appendChild(b);
    setOpacity(tooltip);
    el.tooltip=tooltip;
    el.onmouseover=includeTooltip;
    el.onmouseout=removeTooltip;
    el.onmousemove=Locate;
}

//Funcion que muestra el tooltip
//e: evento
function includeTooltip(e){
    document.getElementById("btc").appendChild(this.tooltip);
    Locate(e);
}

//Funcion que oculta el tooltip
//e: evento
function removeTooltip(e){
    var d=document.getElementById("btc");
    if(d.childNodes.length>0) d.removeChild(d.firstChild);
}

//funcion para establecer la opcaidad de la burbuja
//el:elemento
function setOpacity(el){
    el.style.filter="alpha(opacity:95)";
    el.style.KHTMLOpacity="0.95";
    el.style.MozOpacity="0.95";
    el.style.opacity="0.95";
}

//funcion para crear elemntos html
//t:tipo de elemnto (span, div...)
//c:clase css a aplicarle al nuevo elemento
function CreateEl(t,c){
    var x=document.createElement(t);
    x.className=c;
    x.style.display="block";
    return(x);
}


//funcion para ubicar la capa de acuerdo al icono de ayuda
//e: evento
function Locate(e){
    var posx=0,posy=0;
    var layout;
    if(e==null) e=window.event;
    if(e.pageX || e.pageY){
        posx=e.pageX; 
        posy=e.pageY;
    }
    else if(e.clientX || e.clientY){
        if(document.documentElement.scrollTop){
            posx=e.clientX+document.documentElement.scrollLeft;
            posy=e.clientY+document.documentElement.scrollTop;
        }
        else{
            posx=e.clientX+document.body.scrollLeft;
            posy=e.clientY+document.body.scrollTop;
        }
    }
    //Compruebo contra el tamaño del documento para mostrarlo bien en los bordes
    posx=posx-20;
    posy=posy+10;
    layout="botton-right";
    
	if (posx>(f_clientWidth()+f_scrollLeft()-150)){
		posx=posx-120;
		layout="botton-left";
	}
	if ( posy>(f_clientHeight()+f_scrollTop()-50)) {
		posy=posy-120;
		if(layout=="botton-left")
		    layout="top-left";
		else
		    layout="top-right";
	} 
    
    var el=document.getElementById("btc");            
    el.style.top=(posy)+"px";
    el.style.left=(posx)+"px";
    if(el.childNodes.length>0){
        if (el.firstChild.childNodes.length>0){
            var childs=el.firstChild.childNodes;
            for (var i=0;i<childs.length;i++){
                if (childs[i].nodeName!="#text")
                    childs[i].className=layout;
            }
        }
    } 
}


/* Getting window size and scroll bars position in JavaScript/DHTML */
function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}
/*END Getting window size and scroll bars position in JavaScript/DHTML */

///********************Fin Ayudas formularios *****************/

// Ojo. Funcion tempooral pendiente de tarea TRA-93
function ClassDerFutura(fecha)
{
   if (fecha) {
     var hoy = new Date();
     var derogacion = new Date();   
     derogacion.setMonth(fecha.substring(4, 6)-1);
     derogacion.setYear(fecha.substring(0, 4));
     derogacion.setDate(fecha.substring(6, 8));
 
     if (derogacion.getTime() <= hoy.getTime()) {
        var contexto = document.getElementById('cCx')
        var estiloActual;
        for (var i=0; i < contexto.childNodes.length; i++) {
            if (contexto.childNodes[i].nodeName=='P') {
                estiloActual = contexto.childNodes[i].className;
                if (estiloActual=='lDF'){
                    contexto.className= contexto.className.replace(/lDF/, "lDR");
                }
                contexto.childNodes[i].className = (estiloActual=='cl') ? 'op' : 'cl';
            } 
        }
    }
  } 
}





//Formularios Francia

function EditarFrFo()
{


 var arr= document.getElementById('dTxT').getElementsByTagName('input');
 for (var i=0; i < arr.length; i++) 
 {
  if(arr[i].type=='checkbox' || arr[i].type=='radio')
  {
   if(!arr[i].checked)
   {
     //arr[i].parentNode.style.display='none';
     arr[i].parentNode.className=arr[i].parentNode.className+'hide';
     arr[i].removeAttribute("checked");
   }
   else
   {
     arr[i].setAttribute("checked","checked");
   }
  }
  
  if(arr[i].type=='text')
  {
   arr[i].setAttribute("value",arr[i].value);
  }
  
 }

var arr2= document.getElementById('dTxT').getElementsByTagName('select');
 for (var i=0; i < arr2.length; i++) 
 {
    for (var ii=0; ii<arr2[i].options.length; ii++) {
            if (ii == arr2[i].selectedIndex) {
                arr2[i].options[arr2[i].selectedIndex].setAttribute("selected","selected");
            }
            else
                arr2[i].options[ii].removeAttribute("selected");
        }
 }
 
}


function EditarFrFoReturn(){
    var arr= document.getElementById('dTxT').getElementsByTagName('input');
    for (var i=0; i < arr.length; i++){
        if(arr[i].type=='checkbox' || arr[i].type=='radio'){
            if(!arr[i].checked){
                arr[i].parentNode.className=arr[i].parentNode.className.replace('hide', '');
            }
        }
    }
}



// INICIO TRAIDO DESDE Docs.js DE PRODUCTO (por PRE-2251)

DOM = (document.getElementById) ? 1 : 0;
NS4 = (document.layers) ? 1 : 0;
IE = (document.all) ? 1 : 0;
IE4 = IE && !DOM;


var maxTableau = new Array();
var currentTableau = new Array();
var content = new Array();
var clonedDivs = new Object();

function add(divname) 
{

    if (currentTableau[divname] >= maxTableau[divname]) 
    {
        alert("le maximum est atteint  : " + maxTableau[divname]);
        return false;
    }

    currentTableau[divname]++;

    ExpressRegul = new RegExp("A1", "g");
    data = content[divname].replace(ExpressRegul, "A1_" + currentTableau[divname]);

    if (DOM) 
    {
        document.getElementById(divname + '_1').innerHTML = document.getElementById(divname + '_1').innerHTML + data;
    }
    else 
    {
        document.all[divname + '_' + 1].innerHTML = document.all[divname + '_' + 1].innerHTML + data;
    }

    //Marcar capa clonada:
    if (clonedDivs[divname] == null)
        clonedDivs[divname] = 1;
    else
        clonedDivs[divname]++;

    updateCreatedDivs(clonedDivs);

    return false;
}




function supp(divname) 
{
    if (currentTableau[divname] < 2) 
    {
        alert("le minimum est atteint");
        return false;
    }

    if (DOM) 
    {
        texte = document.getElementById(divname + '_' + 1).innerHTML;
    }
    else 
    {
        texte = document.all[divname + '_' + 1].innerHTML;
    }

    pos = texte.toUpperCase().lastIndexOf("<DIV");

    if (DOM) 
    {
        document.getElementById(divname + '_' + 1).innerHTML = texte.substring(0, pos);
    }
    else 
    {
        document.all[divname + '_' + 1].innerHTML = texte.substring(0, pos);
    }

    currentTableau[divname]--;

    //Marcar capa clonada:
    if (clonedDivs[divname] == null)
        clonedDivs[divname] = 0;
    else
        clonedDivs[divname]--;

    updateCreatedDivs(clonedDivs);

    return false;

}

function updateCreatedDivs(clones) 
{
    var info = "";

    for (var indice in clones) 
    {
        info += indice + "*" + clones[indice] + "|";
    }

    document.getElementById("createdDivs").value = info;
}

function setDefault(divname, max) 
{
    maxTableau[divname] = max;
    currentTableau[divname] = 1;

    //Crear el input hidden para llevar la cuenta de las capas dinámicas creadas
    createdDivs = document.createElement('input');
    createdDivs.setAttribute("type", "hidden");
    createdDivs.setAttribute("name", "createdDivs");
    createdDivs.setAttribute("id", "createdDivs");
    createdDivs.setAttribute("value", "");
    document.getElementById("tBody").appendChild(createdDivs);

    if (DOM) {
        content[divname] = document.getElementById(divname + '_' + 1).innerHTML;
    }
    else {
        content[divname] = document.all[divname + '_' + 1].innerHTML;
    }
}

// FIN TRAIDO DESDE Docs.js DE PRODUCTO (por PRE-2251)

// Funcion que inicializa los input de tipo text para que en el evento onKeyPress se ejecute la función
// resizeText que varia el size del input en funcion del texto que contiene
function setOnKeyPress() 
{
    // Inicializar inputs
    var inputs = document.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++) 
    {
        if ((inputs[i].type == "text") && (inputs[i].name.indexOf('I') == 0))
        {
            if (window.addEventListener) {
                inputs[i].addEventListener("keypress", resizeText, false);
            }
            else {
                inputs[i].attachEvent("onkeypress", resizeText, false);                
            }
        }
    }
}

// Funciona que comprueba el size del campo de texto y lo redimensiona si se escribe mas
// Funciona que comprueba el size del campo de texto y lo redimensiona si se escribe mas
function resizeText(e) {
    if (e.srcElement) {
        var tamanio = parseInt(e.srcElement.value.length) + parseInt(Math.round(e.srcElement.value.length / 10));
        if (tamanio < 47) {
            tamanio = 47;
        }
        e.srcElement.className = "";
        e.srcElement.size = tamanio;
    }
    else {
        var tamanio = parseInt(e.target.value.length) + parseInt(Math.round(e.target.value.length / 10));
        if (tamanio < 47) {
            tamanio = 47;
        }
        e.target.className = "";
        e.target.size = tamanio;
    }
    return true;
}
/* EMG: 29/02/2008 FUNCIONALIDAD TDC CODIGOS */
/* */


if (document.implementation) {
	if (document.implementation.hasFeature('Events','2.0')) {
		var DOM2 = true;
	} else {
		var DOM1 = true;
		var elmObj = null;
	}
} else {
	if (document.getElementById) {
		var DOM1 = true;
		var elmObj = null;
	}
}
/* */
function IniciarCodigo(menuId,tipo) {		
	if (!DOM1 && !DOM2) {return null;}
	var Menu = document.getElementById(menuId);
	var Submenues = Menu.getElementsByTagName(tipo);
	var Submenueslength=Submenues.length;
	for (var i = 0; i < Submenueslength; i++) {
	if (	tipo =='dl'){
		Menux = Submenues[i];
	} else if (tipo =='ul'){
		Menux = Submenues[i].parentNode;
	} else if (tipo =='li'){
		Menux = Submenues[i];
	}
		while (Menux.nodeName=="#text"){
			Menux = Menux.nextSibling;
    		}
		if (DOM2) {
			if (	tipo =='dl'){
				if (	Menux.firstChild.nodeName=="#text"){
				    ReestructNodes(Menux.firstChild.nextSibling);
				} else {
				    ReestructNodes(Menux.firstChild);
				} 		
			} else if (tipo =='ul'){
				Menux.addEventListener('click', OpenUL, 0);	
			} else if (tipo =='li'){
				Menux.addEventListener('click', OpenUL, 0);	
			}
		}
		if (DOM1) {
			if (	tipo =='dl'){
			    //Menux.firstChild['onclick'] = new Function('OpDLc(this);');
			    ReestructNodes(Menux.firstChild);
			} else if (tipo =='ul'){
				Submenues[i].parentNode['onclick']=new Function('OpenUL(this);');
			} else if (tipo =='li'){
				if(Submenues[i].className != "ExISISc" && Submenues[i].className != "ExISISo" ){				
					Submenues[i]['onclick']=new Function('OpenUL(this);');
				}
			}
		}
	}
}
function OpDLc(E) {
	var elmDT = (DOM1) ? E : E.currentTarget;
	if (DOM1) {
		  if (elmObj == null) elmObj = elmDT;
		  if (elmObj.parentNode == elmDT) return elmObj = elmDT;
		  if (window.event.srcElement.nodeName != 'DT') {
		      return null;
		  }
	}
	if (DOM2) {
	    if (elmDT.nodeName != 'DT') {
	        return null;
	    }
	    else {
	        if (E.target.nodeName != 'DT') {
	            return null;
	        }
	    }
	}
	var estiloActual = elmDT.className;
		elmDT.className = (estiloActual=='dcl') ? 'dop' : 'dcl';
    if(elmDT.nextSibling!=null){
	    while (elmDT.nextSibling!=null && elmDT.nextSibling.nodeName=="#text"){
			elmDT= elmDT.nextSibling;
    	}
    }
    var ajaxload = false;
    var auxiliary = elmDT.nextSibling;
    if (auxiliary!=null && auxiliary.id != '') {
        var i = 0;
        for (i; i < auxiliary.childNodes.length; i++) {
            if (auxiliary.childNodes[i].nodeName == "DFN") {
                ajaxload = true;
                LoadingViewer(auxiliary.id,"");
                ControlTDC();
                auxiliary.className = "op";
                break;
            }
        }
    }
    if (!ajaxload) {
        while (elmDT = elmDT.nextSibling) {
            estiloActual = elmDT.className;
            if (elmDT.nodeName == 'DD') {
                elmDT.className = (estiloActual == 'cl') ? 'op' : 'cl';
                //tratamos el hijo si es un dl
                var hijos=elmDT.childNodes.length;
                for (var i=0; i<hijos; i++){
                    var child=elmDT.childNodes[i];
                    if (child.nodeName=='DL' && child.className==''){
                        for (var k=0;k<child.childNodes.length;k++){
                            if (child.childNodes[k].nodeName!='#text'){
                                child.childNodes[k].className= (estiloActual == 'cl') ? 'op' : 'cl';
                            }
                        }
                    }
                }
            }
        }
    }
	if (DOM1) elmObj = elmDT;
	if (DOM2) E.stopPropagation();
}

function ControlTDC(){
	if (document.getElementById('tdcBody') ){ 
		IniciarCodigo('tdcBody','dl');
	}
}
function LoadingViewer(tdc, ide) {
    if (ide == "") {
        var hash = new Object();
        hash.Idd = tdc;
        hash.Vigente = "";
        hash.RepositoryPath = 'tdc';
        hash.LanguageDependence = new Boolean(false);
        var res = Wke.Presentation.WebControls.HtmlViewerControl.LoadInnerHtml(hash);
        document.getElementById(tdc).innerHTML = res.value;
        document.getElementById(tdc).className = "op";
    }
    else{
        var node = document.getElementById(ide);
        if (node.nodeName == "DFN") {
            var obj = new Object();
            var tdcsecondnode = node.parentNode;
            var tdcsecondid = tdcsecondnode.id;
            obj.Idd = tdcsecondid;
            obj.Vigente = "";
            obj.RepositoryPath = 'tdc';
            obj.LanguageDependence = new Boolean(false);
            var secondary = Wke.Presentation.WebControls.HtmlViewerControl.LoadInnerHtml(obj);
            tdcsecondnode.innerHTML = secondary.value;
            ControlTDC();
            if (document.all)
                tdcsecondnode.previousSibling.className = "dop";
            else
                tdcsecondnode.previousSibling.previousSibling.className = "dop";
            var contlinknode = document.getElementById(ide);
            var episodenode = contlinknode.parentNode.parentNode;
            if (document.all)
                episodenode.previousSibling.className = "dop";
            else
                episodenode.previousSibling.previousSibling.className = "dop";
            for (var i = 0; i < contlinknode.childNodes.length; i++) {
                if (contlinknode.childNodes[i].nodeName == "A")
                    contlinknode.childNodes[i].className = "selected-item";
            }
            OpenTdcNodeViewer(node.id);
        }
    }
}
function OpenTdcNodeViewer(nodeId) {
    if (nodeId != "") {
        var principalDiv = document.getElementById(nodeId);
        if (principalDiv != null) {
            if (principalDiv.hasChildNodes())
            // So, first we check if the object is not empty, if the object has child nodes
            {
                var children = principalDiv.childNodes;
                var i = 0;
                var stop = false;
                while ((i < children.length) && (!stop)) {
                    if (children[i].nodeName == "A") {
                        stop = true;
                        //children[i].className = "isis-b";
                        //principalDiv.style.display = 'block';
                        principalDiv.className = "op";
                    };
                    i++;
                };
            };

            while (principalDiv.parentNode != null) {
                principalDiv = principalDiv.parentNode;
                //principalDiv.textContent=principalDiv.innerHTML;
                //imageFolder = principalDiv.firstChild;
                //
                if ((principalDiv.nodeName == "DT")) {
                    //Toggle(imageFolder);
                    principalDiv.className = 'dop';
                };
                if ((principalDiv.nodeName == "DD")) {
                    //Toggle(imageFolder);
                    principalDiv.className = 'op';
                };
                if ((principalDiv.nodeName == "DL")) {
                    //Toggle(imageFolder);
                    principalDiv.className = 'op';
                };

            };
        }
    }
}
function ReestructNodes(node) {
    var res;
    if (DOM1) {
        res = node.childNodes[0];
    }
    else {
        res = node.childNodes[1];
    }
    var child=node.firstChild;
    if (child.nodeName=="#text")
        child=child.nextSibling;
    if (!child || child.className!="ex"){
        if (res) {
            if (res.nodeName == "A") {
                var literal = res.nextSibling.nodeValue;
                var ref = res.href;
                var pos = ref.indexOf("Cn");
                if (pos != -1) {
                    res.innerHTML = literal;
                    res.textContent = literal;
                    res.nextSibling.nodeValue = "";
                }
                if (DOM2) {
                    node.addEventListener('click', OpDLc, 0);
                }
                else {
                    node['onclick'] = new Function('OpDLc(this);');
                }
            }
            else {
                //node.addEventListener('click', OpDLc, 0);
                if (DOM2) {
                    node.addEventListener('click', OpDLc, 0);
                }
                else {
                    node['onclick'] = new Function('OpDLc(this);');
                }
            }
        }
        else {
            //node.addEventListener('click', OpDLc, 0);
            if (DOM2) {
                node.addEventListener('click', OpDLc, 0);
            }
            else {
                node['onclick'] = new Function('OpDLc(this);');
            }
        }
    }
    else{
        if (res) {
            if (res.nodeName == "A") {
                var literal = res.nextSibling.nodeValue;
                var ref = res.href;
                var pos = ref.indexOf("Cn");
                if (pos != -1) {
                    res.innerHTML = literal;
                    res.textContent = literal;
                    res.nextSibling.nodeValue = "";
                }
                if (DOM2) {
                    node.addEventListener('click', OpDLc, 0);
                }
                else {
                    node['onclick'] = new Function('OpDLcEX(this);');
                }
            }
            else {
                if (DOM2) {
                    node.addEventListener('click', OpDLcEX, 0);
                }
                else {
                    node['onclick'] = new Function('OpDLcEX(this);');
                }
            }
        }
        else {
            if (DOM2) {
                node.addEventListener('click', OpDLcEX, 0);
            }
            else {
                node['onclick'] = new Function('OpDLcEX(this);');
            }
        }
    }
}

/*Funcion para tratar como indice sistematico las tdc */
function OpDLcEX(E) {
	var elmDT = (DOM1) ? E : E.currentTarget;
	if (DOM1) {
		  if (elmObj == null) elmObj = elmDT;
		  if (elmObj.parentNode == elmDT) return elmObj = elmDT;
		  if (window.event.srcElement.nodeName == 'A') {
		      return null;
		  }
	}
	if (DOM2) {
	    if (elmDT.nodeName != 'DT')
	        return null;
	    else
	        if (E.target.nodeName == 'A' || E.currentTarget.nodeName != 'DT') return null;
	}
	var estiloActual = elmDT.className;
	elmDT.className = (estiloActual=='cTl') ? 'oTl' : 'cTl';
    if(elmDT.nextSibling!=null){
	    while (elmDT.nextSibling!=null && elmDT.nextSibling.nodeName=="#text"){
			elmDT= elmDT.nextSibling;
    	}
    }
    while (elmDT = elmDT.nextSibling) {
        var hijos = elmDT.childNodes.length;
        for (var i = 0; i < hijos; i++) {
            var child = elmDT.childNodes[i];
            OpDLcEXRecursive(child,estiloActual);
        }
    }
	if (DOM1) elmObj = elmDT;
	if (DOM2) E.stopPropagation();
}

function OpDLcEXRecursive(elmDT,estiloActual)
{
    while (elmDT = elmDT.nextSibling) {
        if (elmDT.nodeName == 'DD') elmDT.className = (estiloActual == 'cTl') ? 'cl' : 'op';
        if (elmDT.nodeName == 'DT') elmDT.className = (estiloActual == 'cTl') ? 'dcl' : 'dop' ;
        var hijos = elmDT.childNodes.length;  
        for (var i = 0; i < hijos; i++) {
            var child = elmDT.childNodes[i];
            OpDLcEXRecursive(child,estiloActual);
        }
    }
}
//Funcion que se ejecuta nada mas terminar de cargar el documento
function FinishLoading() {
    var obj = document.getElementById("loadDiv");
    if (obj) {
        obj.style.display = "none";
    }
}

function RedirectionTDC(node, filename, verifyDocType, redirectPage, repositoryPath, bdeFormat)
{
    if (document.getElementById("ebook_BtnRedirect")!=null)
    {
        RedirectionEBOOK(node, filename, verifyDocType, redirectPage, repositoryPath, bdeFormat);
    }
    else
    {
        if (document.getElementById("htmlViewer_BtnRedirect")!=null)
        {
            RedirectionViewer(node, filename, verifyDocType, redirectPage, repositoryPath, bdeFormat);
        }
        else {
            Redirection(filename, repositoryPath, bdeFormat,redirectPage);
        }
    }
}
function RedirectionEBOOK(node, filename, verifyDocType, redirectPage, repositoryPath, bdeFormat)
{
    document.getElementById("ebook_Node").value = node != null ? node : "";
    document.getElementById("ebook_Filename").value = filename != null ? filename : "";
    document.getElementById("ebook_VerifyDocType").value = verifyDocType != null ? verifyDocType : "";
    document.getElementById("ebook_RedirectPage").value = redirectPage != null ? redirectPage : "";
    document.getElementById("ebook_RepositoryPath").value = repositoryPath != null ? repositoryPath : "";
    document.getElementById("ebook_bdeformat").value = bdeFormat != null ? bdeFormat : "";
   
    document.getElementById("ebook_BtnRedirect").click();
}
function RedirectionViewer(node, filename, verifyDocType, redirectPage, repositoryPath, bdeFormat)
{
    if (filename!= null){
        var pos=filename.indexOf('.');
        if (pos==-1)
        {
            document.getElementById("htmlViewer_Filename").value = filename;
            document.getElementById("htmlViewer_Ebook").value = filename;
        }
        else
        {
            document.getElementById("htmlViewer_Filename").value = filename;
            document.getElementById("htmlViewer_Ebook").value = filename.substring(0,pos);
        }
    }
    else{
        document.getElementById("htmlViewer_Filename").value = "";
    }
    
    document.getElementById("htmlViewer_Node").value = node != null ? node : "";
    document.getElementById("htmlViewer_VerifyDocType").value = verifyDocType != null ? verifyDocType : "";
    document.getElementById("htmlViewer_RedirectPage").value = redirectPage != null ? redirectPage : "";
    document.getElementById("htmlViewer_RepositoryPath").value = repositoryPath != null ? repositoryPath : "";
    document.getElementById("htmlViewer_bdeformat").value = bdeFormat != null ? bdeFormat : "";
   
    document.getElementById("htmlViewer_BtnRedirect").click();
}
function OpenFolders(nodeId) {
    var selected;
    if (nodeId != "")
    {
        var principalDiv = document.getElementById(nodeId);
        if (principalDiv != null)
        {
            if (principalDiv.hasChildNodes())
            // So, first we check if the object is not empty, if the object has child nodes
            {
                var children = principalDiv.childNodes;
                var i = 0;
                var stop = false;
                while ((i < children.length) && (!stop))
                {
                    if (children[i].nodeName == "A")
                    {
                        stop = true;
                        children[i].className = "selected-index";
                        selected = children[i];
                    };
                    i++;
                };
            };
            
            while (principalDiv.parentNode != null)
            {
                principalDiv = principalDiv.parentNode;
                //principalDiv.textContent=principalDiv.innerHTML;
                //imageFolder = principalDiv.firstChild;
                //
                if ((principalDiv.nodeName == "DT"))
                {
                    //Toggle(imageFolder);
                    principalDiv.className='dop';
                };     
                if ((principalDiv.nodeName == "DD"))
                {
                    //Toggle(imageFolder);
                    principalDiv.className='op';
                };    
                if ((principalDiv.nodeName == "DL"))
                {
                    //Toggle(imageFolder);
                    principalDiv.className='op';
                };    
                
                if (principalDiv.hasChildNodes())
            // So, first we check if the object is not empty, if the object has child nodes
            {
                var children = principalDiv.childNodes;
                
                var i = 0;
               
                while ((i < children.length) )
                {
                    if (children[i].nodeName == "DD")
                    {
                       
                        children[i].className = "op";
                        //principalDiv.style.display = 'block';
                    };
                    i++;
                };
            };
            for (i = 0; i < principalDiv.childNodes.length; i++) {
                if (principalDiv.childNodes[i].nodeName == "DT") {
                    principalDiv.childNodes[i].className = "dop";
                    //                            principalDiv.childNodes[i].click();
                    break;
                }
            }  
            };
        }
    }
    if (selected != null) 
    {
        setTimeout("positioningScroll('" + selected.parentNode.id + "')", 300);
    }
    
}
function positioningScroll(id) {
    var node = document.getElementById(id);
    var nodeParent = node.parentNode;
    nodeParent.scrollIntoView();
}
if(typeof Wke == "undefined") Wke={};
if(typeof Wke.Presentation == "undefined") Wke.Presentation={};
if(typeof Wke.Presentation.WebControls == "undefined") Wke.Presentation.WebControls={};
Wke.Presentation.WebControls.AjaxCachePageControl_class = function() {};
Object.extend(Wke.Presentation.WebControls.AjaxCachePageControl_class.prototype, Object.extend(new AjaxPro.AjaxClass(), {
	AjaxCahePageControl_OnLoad: function(target, method, jobject) {
		return this.invoke("AjaxCahePageControl_OnLoad", {"target":target, "method":method, "jobject":jobject}, this.AjaxCahePageControl_OnLoad.getArguments().slice(3));
	},
	url: '/ajaxpro/Wke.Presentation.WebControls.AjaxCachePageControl,Wke.Presentation.ashx'
}));
Wke.Presentation.WebControls.AjaxCachePageControl = new Wke.Presentation.WebControls.AjaxCachePageControl_class();


if(typeof Wke == "undefined") Wke={};
if(typeof Wke.Presentation == "undefined") Wke.Presentation={};
if(typeof Wke.Presentation.WebControls == "undefined") Wke.Presentation.WebControls={};
Wke.Presentation.WebControls.AjaxControl_class = function() {};
Object.extend(Wke.Presentation.WebControls.AjaxControl_class.prototype, Object.extend(new AjaxPro.AjaxClass(), {
	AjaxControl_Click: function(target, method, jobject) {
		return this.invoke("AjaxControl_Click", {"target":target, "method":method, "jobject":jobject}, this.AjaxControl_Click.getArguments().slice(3));
	},
	url: '/ajaxpro/Wke.Presentation.WebControls.AjaxControl,Wke.Presentation.ashx'
}));
Wke.Presentation.WebControls.AjaxControl = new Wke.Presentation.WebControls.AjaxControl_class();


function AjaxControl_Default(target, method, obj, callback)
{
    //ejemplo de objeto 
    /*
    obj=new Object();
    obj.name='paco';
    obj.number=7;
    */
    var res=Wke.Presentation.WebControls.PageControl.VerifySession(document.location.href);
    if (res.value=="true")
    {
        if(callback==null)
        {
             var res= Wke.Presentation.WebControls.AjaxControl.AjaxControl_Click(target, method, obj);
            return res;
        }
        else
        {
            Wke.Presentation.WebControls.AjaxControl.AjaxControl_Click(target, method, obj, callback);
         }
    }
    else
    {
        window.location.href=res.value;
    }
    
}

function AjaxControl_Callback(response)
{
    if(response.value == null)
    {
        alert('Error in AjaxControl_Callback, see the log file.');
    }
    else
    {
        alert('AjaxControl_Callback por defecto');
    }
}

/************ FUNCIONES PROPIAS DEL AJAX TEXT CONTROL ************/
/*  Las propiedades que recibe en el JavaScriptObject son:
    txtvalue (valor de la caja de texto)
    txtid (id de la caja de texto)
    divid (id de la capa donde se insertara el innerhtml y que mostraremos)
    Debe devolver:
    innerHTML con el html que queramos mostrar en la capa
    
    Como se use depende de cada uno, la forma logica es como esta el ejemplo
    poniendo el valor pulsado y ocultando la capa
    luego los valores que vayan dentro que cada uno lo busque o haga lo que quiera</example>
*/
function AjaxTextControl_KeyPress(target,method,obj,callback)
{
    if(obj.txtvalue.length>0)
    {
        Wke.Presentation.WebControls.AjaxTextControl.AjaxTextControl_KeyPress(target,method,obj,callback);
    }
    else
    {
        if (document.getElementById(obj.divid) != null)
        {
            document.getElementById(obj.divid).style.display='none';
        }
    }
}

function AjaxTextControl_Callback(res)
{
    if(res.value==null)
    {
        alert('Error in AjaxTextControl_Callback, see the log file.');
    }
    else
    {
        //ejemplo de recoger los valores
        document.getElementById(res.value.divid).innerHTML=res.value.innerHTML;
        document.getElementById(res.value.divid).style.display='block';
    }
}

var menuControl = null;
var menuItems = new Array();
function aniadirEventos(nodeArg) // tienen que llegar nodos ul
{
    try{
    var nodes=nodeArg.getElementsByTagName("li"); 
     
    for (var i=0;i<nodes.length; i++) // Me recorro todos los hijos del nodo
    {
        var node=nodes[i];
        if (node.nodeName=="LI")  // si son li le anadimos los eventos
	    {
	        node.onmouseover=function() 
	        {
		        this.className+=" over";
	        }
	        node.onmouseout=function() 
	        {
		        this.className=this.className.replace(" over", "");
	        }
	        
	        var nodes2=node.getElementsByTagName("ul"); 
	        for (var j=0;j<nodes2.length;j++) // nos recorremos todos los hijos del li
		    {
				var node2 = nodes[j];
				if (node2.nodeName=="UL") // Si encuentra un submenu a sus hijos li habra que ponerle las funciones
				{
				    aniadirEventos(node2);
				}
	        }
        }       
    }  
    }
    catch(e){ 
 		//alert('error in menu'); 
 	} 
}

function InitializeMenu(id) 
{
    if (document.all&&document.getElementById) 
    {
		navRoot = document.getElementById(id);
		aniadirEventos(navRoot)
    }
}

function expandSubmenu(idUl)
{
    var ul = document.getElementById("ul" + idUl);
    var brother = ul.previousSibling;
  if (ul.style.display == 'block' || ul.style.display == '')
  {
      ul.style.display = 'none';
      while (brother.previousSibling != null) {
          brother = brother.previousSibling;
          if (brother.className != '')
              brother.className = 'SubmenuCollapsed';
      }      
  }
  else
  {
      ul.style.display = 'block';
      while (brother.previousSibling != null) {
          brother = brother.previousSibling;
          if (brother.className != '')
              brother.className = 'SubmenuExpanded';
      }
  }
}
function CreateMenuItem(index, itemText, itemLink) {
    var item = new Ext.menu.Item({
        text: itemText,
        href: itemLink
    });
    menuItems[index] = item;
}
function CreateSumenuItems(index, itemText, listItems) {
    var subMenuItems= new Array();
    for (var i=0;i<listItems.length;i++){
        var menuItem=new Ext.menu.Item({
                        text: listItems[i].Text,
                        href: listItems[i].Href
                        });
        subMenuItems[i]=menuItem;
    }
    var submenu= new Ext.menu.Menu({
                    text: itemText,
                    items: subMenuItems
                });
    var item = new Ext.menu.Item({
        text: itemText,
        menu: submenu
    });
    menuItems[index] = item;
}
function CreateMenu(activeIndex) {
    menuControl = new Ext.Toolbar({
                    layout: 'menu',
                    items: menuitems
                    });
}
if(typeof Wke == "undefined") Wke={};
if(typeof Wke.Presentation == "undefined") Wke.Presentation={};
if(typeof Wke.Presentation.WebControls == "undefined") Wke.Presentation.WebControls={};
Wke.Presentation.WebControls.AuthenticationControl_class = function() {};
Object.extend(Wke.Presentation.WebControls.AuthenticationControl_class.prototype, Object.extend(new AjaxPro.AjaxClass(), {
	ForzeSession: function(authusername, authpassword, arguments) {
		return this.invoke("ForzeSession", {"authusername":authusername, "authpassword":authpassword, "arguments":arguments}, this.ForzeSession.getArguments().slice(3));
	},
	ValidateSessionLogout: function() {
		return this.invoke("ValidateSessionLogout", {}, this.ValidateSessionLogout.getArguments().slice(0));
	},
	url: '/ajaxpro/Wke.Presentation.WebControls.AuthenticationControl,Wke.Presentation.ashx'
}));
Wke.Presentation.WebControls.AuthenticationControl = new Wke.Presentation.WebControls.AuthenticationControl_class();


var swlogin=false;

function validate_swlogin()
{
   if(swlogin)
    {
        swlogin=false;
        return true;
    }
    else
    {
        return false;
    }
}

function ChangePermissions(div,divlogin) {
    if (typeof defaultUser != "undefined") {
        if (defaultUser) {
            //document.getElementById(div).innerHTML = document.getElementById(divlogin).innerHTML;
            //document.getElementById(divlogin).className='kaka';
            document.getElementById(div).appendChild(document.getElementById(divlogin));
        }
    }
}

function ValidateuserBack(target,method)
{
    var obj=new Object();  
    obj.Target = target;
    obj.Method = method;
    AjaxCachePageControl_load(target, method,obj,ValidateuserBackCallback); 
}

function ValidateuserBackCallback(res)
{
    if (res != null &&
        res.value != null &&
        res.value.logado == 'false' && 
        document.getElementById('username') == null) {
        document.location.href = res.value.page;
    }
}

function logout()
{
    var resuse=Wke.Presentation.WebControls.AuthenticationControl.ValidateSessionLogout();
    if(resuse.value!=''){
        var aux='document.location.href=';
        aux=aux+'\"'+resuse.value+'\"';
         var form  = document.forms[0];
        form.onsubmit = function(){return false;};
        setTimeout(aux,500);
        return false;}
    else{  swlogin=true;return true;}
}

function enable_logout() {
    disabled_first_child_inputs('logindiv', false);

    var form = GetFormularioPrincipal();
    if (form != null)
    {
        form.onsubmit = function() { return true; };
    }

    disabled_button('buttonLogout', false);
}

function disable_logout()
{
    disabled_first_child_inputs('logindiv', true);
    disabled_button('buttonLogout', true);
}

function disabled_first_child_inputs(idElement, estado) {
    var divLogin = document.getElementById(idElement);
    if (divLogin != null) {
        var arr = divLogin.getElementsByTagName('input');
        if (arr.length > 0) {
            arr[0].disabled = estado;
        }
    }
}

function disabled_button(idbutton, estado) {
    var buttonLogout = document.getElementById(idbutton);
    if (buttonLogout != null) {
        buttonLogout.disabled = estado;
    }
}

function GetFormularioPrincipal() {
    if (document != null &&
        document.forms != null &&
        document.forms.length > 0) {
        return document.forms[0];
    }

    return null;
}

function PathLoad(target, method, idHdHistoricalPath, idDivPath)
{    
    var obj=new Object();
    obj.IdHdHistoricalPath = idHdHistoricalPath;
    obj.IdDivPath = idDivPath;
    if (document.getElementById(idHdHistoricalPath) != null) {
        if (document.getElementById(idHdHistoricalPath).value + '' != '') {
            obj.Method = 'Synchronize';
            obj.HistoricalId = document.getElementById(idHdHistoricalPath).value;
        }
        else {
            obj.Method = 'UpdateHistoricalId';
            obj.HistoricalId = '';
        }
    }
    else {
        obj.Method = '';
        obj.HistoricalId = '';
    }
    AjaxControl_Default(target, method,obj,PathLoadCallback);
}

function PathLoadCallback(res)
{   
    if(res != null)  
    {
        if(res.value!=null)
        {
        if(res.value.Method=='Synchronize')
        {
            if(res.value.SynchronizeCallback[0] == '')
		    {		        
			    document.getElementById(res.value.IdDivPath).value = res.value.SynchronizeCallback[1];
		    }
		    else
		    {		   
			    window.location = res.value.SynchronizeCallback[0];
		    }
        }
        else
        {        
            document.getElementById(res.value.IdHdHistoricalPath).value = res.value.RecoverHistoricalIdCallback;
        }   
        
        }
     }
}



if(typeof Wke == "undefined") Wke={};
if(typeof Wke.Presentation == "undefined") Wke.Presentation={};
if(typeof Wke.Presentation.WebControls == "undefined") Wke.Presentation.WebControls={};
Wke.Presentation.WebControls.SearchPublicationControl_class = function() {};
Object.extend(Wke.Presentation.WebControls.SearchPublicationControl_class.prototype, Object.extend(new AjaxPro.AjaxClass(), {
	GetYearList: function(typeDoc) {
		return this.invoke("GetYearList", {"typeDoc":typeDoc}, this.GetYearList.getArguments().slice(1));
	},
	GetMonthList: function(typeDoc, rangeyear) {
		return this.invoke("GetMonthList", {"typeDoc":typeDoc, "rangeyear":rangeyear}, this.GetMonthList.getArguments().slice(2));
	},
	GetNumberList: function(typeDoc, rangedate) {
		return this.invoke("GetNumberList", {"typeDoc":typeDoc, "rangedate":rangedate}, this.GetNumberList.getArguments().slice(2));
	},
	GetNumberResultList: function(range, number, typeDoc) {
		return this.invoke("GetNumberResultList", {"range":range, "number":number, "typeDoc":typeDoc}, this.GetNumberResultList.getArguments().slice(3));
	},
	GetNumberOpen: function(range, number, typeDoc) {
		return this.invoke("GetNumberOpen", {"range":range, "number":number, "typeDoc":typeDoc}, this.GetNumberOpen.getArguments().slice(3));
	},
	GetLastPublication: function(typeDoc) {
		return this.invoke("GetLastPublication", {"typeDoc":typeDoc}, this.GetLastPublication.getArguments().slice(1));
	},
	url: '/ajaxpro/Wke.Presentation.WebControls.SearchPublicationControl,Wke.Presentation.ashx'
}));
Wke.Presentation.WebControls.SearchPublicationControl = new Wke.Presentation.WebControls.SearchPublicationControl_class();


//*******     CARGANDO                    *********************//
var loadingcombo = false;
//
function loadcomboyearssearchpub(loadingtext) {
    if (!loadingcombo) {
        document.getElementById('anoselectcombo').style.display = 'block';
        document.getElementById('anoselectcombo').innerHTML = loadingtext;
        loadingcombo = true;
        Wke.Presentation.WebControls.SearchPublicationControl.GetYearList(document.getElementById('codtypedoc').value, loadcomboyearssearchpub_callback);
        document.getElementById('anoselectcombo').innerHTML = "";
        loadingcombo = false;
    }
}

function loadcomboyearssearchpub_callback(res) {
    GetYearListcallback(res);
}

function loadcombomonthssearchpub(loadingtext) {
    if (!loadingcombo) {
        //document.getElementById('messelectcombo').style.display = 'block';
        //document.getElementById('messelectcombo').innerHTML = loadingtext;
        //loadingcombo = true;
        if (document.getElementById('messelectcombo') != null) {
            document.getElementById('messelectcombo').length = 0;
            var date = compruebadatepdf();
            Wke.Presentation.WebControls.SearchPublicationControl.GetMonthList(document.getElementById('codtypedoc').value, date, loadcombomonthssearchpub_callback);

        }
        if (document.getElementById('numberselectcombo') != null) {
            document.getElementById('numberselectcombo').length = 0;
            //monto los numeros
            var date = compruebadatepdf();
            Wke.Presentation.WebControls.SearchPublicationControl.GetNumberList(document.getElementById('codtypedoc').value, date, GetNumberListcallback);
        }
        //loadingcombo = false;
    }
}

function loadcombomonthssearchpub_callback(res) {
    document.getElementById('anoselectcombo').innerHTML = "";
    GetMonthListcallback(res);
    //loadingcombo = false;
}

//*******        FIN CARGANDO            *********************//

function loadyearspdf() 
{
    if (document.getElementById('anoselectcombo').length == 0) {
        document.getElementById('chargeanoselectcombo').style.display = 'block';
        Wke.Presentation.WebControls.SearchPublicationControl.GetYearList(document.getElementById('codtypedoc').value, GetYearListcallback);        
    }
}

function GetYearListcallback(res)
{
    var arr=res.value;
    document.getElementById('anoselectcombo').options[0]=new Option('','');
        for(i=0;i<arr.length;i++)
        {
            document.getElementById('anoselectcombo').options[i+1]=new Option(arr[i],arr[i]);
        }
        document.getElementById('chargeanoselectcombo').style.display = 'none';
}

function loadmonthandnumberspdf()
{
    if(document.getElementById('messelectcombo')!=null) {
        document.getElementById('messelectcombo').length=0;

        var date=compruebadatepdf();
        Wke.Presentation.WebControls.SearchPublicationControl.GetMonthList(document.getElementById('codtypedoc').value,date,GetMonthListcallback);
    }    
    if(document.getElementById('numberselectcombo')!=null)
    {
        document.getElementById('numberselectcombo').length=0;
        //monto los numeros
        var date=compruebadatepdf();
        Wke.Presentation.WebControls.SearchPublicationControl.GetNumberList(document.getElementById('codtypedoc').value,date,GetNumberListcallback);
    }
}


function GetMonthListcallback(res)
{
    var arr=res.value;
    document.getElementById('messelectcombo').options[0]=new Option('','');
        for(i=0;i<arr.length;i++)
        {
            document.getElementById('messelectcombo').options[i+1]=new Option(arr[i].split('|')[0],arr[i].split('|')[1]);
        }
}

function GetNumberListcallback(res)
{
    var arr=res.value;
    document.getElementById('numberselectcombo').options[0]=new Option('','');
        for(i=0;i<arr.length;i++)
        {
            document.getElementById('numberselectcombo').options[i+1]=new Option(arr[i].split('|')[0],arr[i].split('|')[1]);
        }
}

function loadmonthpdf()
{
    if(document.getElementById('messelectcombo').length==0)
    {
        var date=compruebadatepdf();
        Wke.Presentation.WebControls.SearchPublicationControl.GetMonthList(document.getElementById('codtypedoc').value,date,GetMonthListcallback);
    }
}

function loadnumberpdf()
{
    if(document.getElementById('numberselectcombo')!=null)
    {
    document.getElementById('numberselectcombo').length=0;
    var date=compruebadatepdf();
    Wke.Presentation.WebControls.SearchPublicationControl.GetNumberList(document.getElementById('codtypedoc').value,date,GetNumberListcallback);
    }
}

function loadnumberclickpdf()
{
    if(document.getElementById('numberselectcombo').length==0)
    {
        var date=compruebadatepdf();
        Wke.Presentation.WebControls.SearchPublicationControl.GetNumberList(document.getElementById('codtypedoc').value,date,GetNumberListcallback);
    }
}

function loadnumberchangepdf()
{
    if(document.getElementById('numberselectcombo').selectedIndex>0)
    {
        openorredirect(document.getElementById('numberselectcombo').options[document.getElementById('numberselectcombo').selectedIndex].value);
    }
}

function openorredirect(idd)
{
    if(document.getElementById('codopen').value=='true')
        window.open(document.getElementById('codurl').value+idd+'.'+document.getElementById('codext').value);
    else
        document.location.redirect=document.getElementById('codurl').value+idd+'.'+document.getElementById('codext').value;
}


function loadultimopdf()
{
      Wke.Presentation.WebControls.SearchPublicationControl.GetLastPublication(document.getElementById('codtypedoc').value,loadultimopdfcallback);
}

function loadultimopdfcallback(res)
{
    document.getElementById('resverultpdf').innerHTML=res.value;
}


function loadresultpdf()
{
    try
    {
    var date=compruebadatepdf();
    //lanzamos los resultados con
    var numero = '';
    if(document.getElementById('numberselectcombo')!=null)
    {
        if(document.getElementById('numberselectcombo').selectedIndex>0)
            numero=document.getElementById('numberselectcombo').options[document.getElementById('numberselectcombo').selectedIndex].text;
    }
    var res=Wke.Presentation.WebControls.SearchPublicationControl.GetNumberOpen(date,numero,document.getElementById('codtypedoc').value);
    eval(res.value);
    }
    catch(e)
    {
        alert('error in loadresultpdf: ' +e.message);
    }
}


function loaddivresultpdf()
{
    try
    {
    var date=compruebadatepdf();
    //lanzamos los resultados con
    var numero = '';
    if(document.getElementById('numberselectcombo')!=null)
    {
        if(document.getElementById('numberselectcombo').selectedIndex>0)
            numero=document.getElementById('numberselectcombo').options[document.getElementById('numberselectcombo').selectedIndex].text;
    }
    Wke.Presentation.WebControls.SearchPublicationControl.GetNumberResultList(date,numero,document.getElementById('codtypedoc').value,loaddivresultpdfcallback);
    }
    catch(e)
    {
        alert('error in loaddivresult: ' +e.message);
    }
}

function loaddivresultpdfcallback(res)
{
    document.getElementById('resverpdf').innerHTML=res.value;
}

function compruebadatepdf()
{
//comprobamos fecha
     var date='';
     
     if(document.getElementById('messelectcombo')!=null)
     {
        if(document.getElementById('messelectcombo').selectedIndex>0)
        {
            if(document.getElementById('anoselectcombo').selectedIndex>0)
                date= document.getElementById('messelectcombo').options[document.getElementById('messelectcombo').selectedIndex].value+'/'+document.getElementById('anoselectcombo').options[document.getElementById('anoselectcombo').selectedIndex].value;
        }
        else
        {
            if(document.getElementById('anoselectcombo').selectedIndex>0)
                date=document.getElementById('anoselectcombo').options[document.getElementById('anoselectcombo').selectedIndex].value;
        }
     }
     else
     {
        if(document.getElementById('anoselectcombo').selectedIndex>0)
            date=document.getElementById('anoselectcombo').options[document.getElementById('anoselectcombo').selectedIndex].value;
     }
     if(date=='')
     {
        //comprobamos si existe la caja de texto
        if(document.getElementById('txtsearchpub')!=null)
            date=document.getElementById('txtsearchpub').value;
     }
    if(date!='')
    {    
    var fecha = new Fecha(date);
        GetFmtLimites(fecha);
        //Comprobamos que las fechas estan dentro de rangos permitidos
        if (!ValidateDates(fecha))
        {
            alert(msgerrorpub);
            return "";
        }
        if (fecha.tipo == "de hasta" && fecha.ini && fecha.fin) 
        {
           date=fecha.ini+'~'+fecha.fin;
        } 
        else if (fecha.tipo == "desde" && fecha.ini) 
        {
            date=fecha.ini+'~null';
        } 
        else if (fecha.tipo == "hasta" && fecha.fin) 
        {
            date='null~'+fecha.fin;
        } 
        else if (fecha.tipo == "en" && fecha.ini) 
        {
            date=fecha.ini+'~'+fecha.ini;
        } 
        else 
        {
            alert(msgerrorpub);
            return "";
        } 
        return date;    
     }    
    //fin comprobacion
}


function checkEnterSub(e){ 
    var keycode;
	if (window.event)
	{
		keycode = window.event.keyCode;
	}
	else if (e)
	{
		keycode = e.which;
	}
	else
	{
		return true;
	}
	if (keycode == 13)
	{
	     document.forms[0].onsubmit = function(){return false;};
	     setTimeout("document.forms[0].onsubmit = function(){return true;};",100);  
	     return false;
	}
	else
	{
		return true;
	}

}

// Esta funcion es llamada en el CreateChildControls del GenericAssistanControl
function load_init_generic(idcontrol, idSearchButtonControl)
{
    // Guardamos los id´s de los assistentes genericos en el hidden AssistantGenericBox, separados por |
    if(document.getElementById('AssistantGenericBox')==null)
	{
		var h=document.createElement('input');
		h.type='hidden';
		h.id='AssistantGenericBox';
		//document.getElementById(idcontrol+'div').appendChild(h);
		document.forms[0].appendChild(h);
		document.getElementById('AssistantGenericBox').value=idcontrol;
	}
	else
	{
		document.getElementById('AssistantGenericBox').value=document.getElementById('AssistantGenericBox').value + '|' + idcontrol;
	}
	// En el input(hidden) EquivalenceAssitantGenericAndSearchButtonControl almacenaremos a que SearchButtonControl hace referencia el GenericAssistant.
	// si vale para todos lo dejaremos a vacio "".
     if(document.getElementById('EquivalenceAssitantGenericAndSearchButtonControl') == null)
     {
         if (document.getElementById(idcontrol + 'div') != null) {
             var inputHidden = document.createElement('input');
             inputHidden.type = 'hidden';
             inputHidden.id = 'EquivalenceAssitantGenericAndSearchButtonControl';
             document.getElementById(idcontrol + 'div').appendChild(inputHidden);
        
	        if (idSearchButtonControl!=undefined)
	        {
	          document.getElementById('EquivalenceAssitantGenericAndSearchButtonControl').value=idSearchButtonControl;
	        }
	        else
	        {
	          document.getElementById('EquivalenceAssitantGenericAndSearchButtonControl').value="";
	        }
	    }
     }
     else
     {
        // si el control ya existe
        if (idSearchButtonControl!=undefined)
	    {
	        document.getElementById('EquivalenceAssitantGenericAndSearchButtonControl').value=document.getElementById('EquivalenceAssitantGenericAndSearchButtonControl').value + '#' + idSearchButtonControl;
	    }
	    else
	    {
	        document.getElementById('EquivalenceAssitantGenericAndSearchButtonControl').value=document.getElementById('EquivalenceAssitantGenericAndSearchButtonControl').value + '#' + "";
	    }
	    
     }
	
}

//Funcion para que al pulsar el Enter nos realice la búsqueda.
function GenericSubmitEnter(e, obj, idControlStatistic) {



	var keycode;
	if (window.event)
	{
		keycode = window.event.keyCode;
	}
	else if (e)
	{
		keycode = e.which;
	}
	else
	{
		return true;
	}
	if (keycode == 13)
	{
	     var res=Wke.Presentation.WebControls.PageControl.VerifySession(document.location.href);
        if (res.value!="true")
        {
            window.location.href=res.value;
            return false;
        }
	    var form  = document.forms[0];
	    form.onsubmit = function(){return false;};
	    if(typeof(disable_logout)=='function')
	        disable_logout();
	    if(typeof(SearchAjaxBtnSearch_OnClick)=='function')
	    {
	        SearchAjaxBtnSearch_OnClick('Wke.Presentation.WebControls.SearchControl', 'AjaxBtnSearch_OnClick', null, null, idControlStatistic);		
		}
		else
		{
		    if(typeof(SearchAjaxButtonSearch_OnClick)=='function')	    
		    {
		        SearchAjaxButtonSearch_OnClick('Wke.Presentation.WebControls.SearchButtonControl', 'AjaxBtnSearch_OnClick', null, null, idControlStatistic);		
		    }
		    else
		    {
		        alert('ERROR:no hay control de busqueda');
		    }
		}
	}
	else
	{
		return true;
	}
}                           


// Funcion que manda a servidor el valor de los asistentes. Devuelve true o false.
// idControlButton -> identificador del searchButtonControl que ha ejecutado el click.
function load_generic_values(idControlButton)
{  
    //antes de llamar limpiamos, para que no se queden cosas
    clean_generic_values(false);
    var resu=true;
    
    // AssistantGenericBox almacenas los id´s de los asistentes genericos.
    // EquivalenceAssitantGenericAndSearchButtonControl almacenas a que searchButtonControl pertence un asistente.
    if(document.getElementById('AssistantGenericBox')!=null)
    {
        var arr=document.getElementById('AssistantGenericBox').value.split('|');
        var arrayEquivalencias;
        if (document.getElementById('EquivalenceAssitantGenericAndSearchButtonControl') != null)
            arrayEquivalencias = document.getElementById('EquivalenceAssitantGenericAndSearchButtonControl').value.split('#');
        else
            arrayEquivalencias = new Array();
        // ejemplo: arr[0]= idAsistente1 -> el id de uno de los asistentes es idAsistente1
        // arrayEquivalencias[0]= btnSearch1 -> el asistente cuyo id es idAsistente1 solo afecta al searchButtonControl btnSearch1
        
        for(i=0;i<arr.length;i++)
        {
            if(resu)
            {
                
                // solo anadiremos el asistente si idControlButton es undefined ( compatibilidad hacia atras)
                // o cuando el asistente no tenga ninguna referecia a un searchButtonControl (arrayEquivalencias[i]="")
                // o cuando el asistente que estamos tratantado tenga asociado el searchButtonControl que hemos pulsado(esto lo marca el array de equivalencias.).
                // (como un asistente puede tener varios ids de searchButtonControl asociados basta con que el indexOf nos devuelva una pos mas de 0.)
               //if (idControlButton==undefined || arrayEquivalencias[i]=="" ||(idControlButton==arrayEquivalencias[i]))
                if (idControlButton==undefined || arrayEquivalencias[i]=="" ||(arrayEquivalencias[i].indexOf(idControlButton)>-1))
                { 
                    var res='';
                    
                    // si no es de tipo fecha.
                    if(document.getElementById(arr[i]+'hiddate')==null) {
                        if (document.getElementById(arr[i] + 'hid') != null) {
                            // primer parametro es el nombre del meta, el segundo el valor
                            var resajax = Wke.Presentation.WebControls.GenericAssistantControl.LoadGenericValues(document.getElementById(arr[i] + 'hid').value, document.getElementById(arr[i]).value, arr[i], document.getElementById(arr[i] + 'hiddenUseSearchWildcard').value);
                            res = resajax.value;
                        }
                    }
                    else {
                        if (document.getElementById(arr[i] + 'hid') != null) {
                            resu = GetParamConsultaFechaAsis(document.getElementById(arr[i]).value, document.getElementById(arr[i] + 'hid').value, arr[i]);
                            if (!resu) {
                                document.getElementById(arr[i]).focus();
                                document.getElementById(arr[i]).select();
                            }
                        }
                    }
                    if(res!='')
                    {
                        eval(res);
                        document.getElementById(arr[i]).focus();
                        document.getElementById(arr[i]).select();
                    }
                }
            
            } // fin del if resu
        }
    }
    return resu;
}

function clean_generic_values(cleanall)
{
    if(document.getElementById('AssistantGenericBox')!=null)
    {
    var arr=document.getElementById('AssistantGenericBox').value.split('|');
    for(i=0;i<arr.length;i++) {
        if (document.getElementById(arr[i] + 'hid') != null) {
            var res = Wke.Presentation.WebControls.GenericAssistantControl.CleanGenericValues(document.getElementById(arr[i] + 'hid').value, arr[i]);
            eval(res.value);
            if (cleanall)
                document.getElementById(arr[i]).value = '';
        }
    }
    }
}


function GenericLoad(target, method, id, tipo, useSearchWildcard)
{
    var obj=new Object();  
    obj.Target = target;
    obj.Method = method;
    obj.Id = id;
    obj.tipo = tipo;
    obj.useSearchWildcard = useSearchWildcard;
    AjaxCachePageControl_load(target, method,obj,GenericLoadCallback); 
}


function GenericLoadCallback(res)
{
    if(res!=null)
    {
        eval(res.value.result);
    }
}


//funciones para la fecha
var separator = "/";

//var meses = new Array();
//meses[0] = Searchfmtmes1; //new String(";enero;ene;I;");
//meses[1] = Searchfmtmes2; //new String(";febrero;feb;II;");
//meses[2] = Searchfmtmes3; //new String(";marzo;mar;III;");
//meses[3] = Searchfmtmes4; //new String(";abril;abr;IV;");
//meses[4] = Searchfmtmes5; //new String(";mayo;may;V;mai");
//meses[5] = Searchfmtmes6; //new String(";junio;jun;VI;");
//meses[6] = Searchfmtmes7; //new String(";julio;jul;VII;");
//meses[7] = Searchfmtmes8; //new String(";agosto;ago;VIII;");
//meses[8] = Searchfmtmes9; //new String(";septiembre;sep;IX;");
//meses[9] = Searchfmtmes10; //new String(";octubre;oct;X;");
//meses[10] = Searchfmtmes11; //new String(";noviembre;nov;XI;");
//meses[11] = Searchfmtmes12; //new String(";diciembre;dic;XII;");



//Comprueba si el texto de busqueda por fecha es correcto en cuyo caso devuelve true
function GetParamConsultaFechaAsis(val_param,tipo,idcontrol)
{
    var correctDate = true;
    //var val_param = document.getElementById("txtDate").value;

    //para el multiidioma cambiamos el valparam

    var val_param_aux = val_param;
    var s = val_param;

    var rExps = [/[\xC0-\xC2]/g, /[\xE0-\xE2]/g,
/[\xC8-\xCA]/g, /[\xE8-\xEB]/g,
/[\xCC-\xCE]/g, /[\xEC-\xEE]/g,
/[\xD2-\xD4]/g, /[\xF2-\xF4]/g,
/[\xD9-\xDB]/g, /[\xF9-\xFB]/g];

    var repChar = ['A', 'a', 'E', 'e', 'I', 'i', 'O', 'o', 'U', 'u'];

    for (var i = 0; i < rExps.length; i++)
        s = s.replace(rExps[i], repChar[i]);


    //para que acepte el separadar de puntos
    s = s.replace(/\u002E/g, '-');
    s = s.replace(/:/g, '-');
    s = s.replace('1er', '1');


    val_param = s;
 
    
    if (val_param != "")
    { 
        var fecha = new Fecha(val_param);
        GetFmtLimites(fecha);
        //Comprobamos que las fechas estan dentro de rangos permitidos
        if (!ValidateDates(fecha))
        {
            //alert(wcDate_message_ErrorDate);
            //alert(wcDate_message_ErrorDate);
            eval(popup.OpenGenericPopup('GenericPopup.aspx?labelCodeText=IncorrectFormatDate&idType=23','no',300,200,'px','yes','','','', 23));
            return false;
        }
        val_param = val_param_aux;
        if (fecha.tipo == "de hasta" && fecha.ini && fecha.fin) 
        {
            //InsertDateIntoSession(fecha.ini, fecha.fin, val_param);
            res = Wke.Presentation.WebControls.GenericAssistantControl.LoadGenericValues(tipo, fecha.ini + '~' + fecha.fin + '~' + val_param, idcontrol, document.getElementById(idcontrol + 'hiddenUseSearchWildcard').value);
        } 
        else if (fecha.tipo == "desde" && fecha.ini) 
        {
            //InsertDateIntoSession(fecha.ini, "", val_param);
            res = Wke.Presentation.WebControls.GenericAssistantControl.LoadGenericValues(tipo, fecha.ini + '~ ' + '~' + val_param, idcontrol, document.getElementById(idcontrol + 'hiddenUseSearchWildcard').value);
        } 
        else if (fecha.tipo == "hasta" && fecha.fin) 
        {
            //InsertDateIntoSession("", fecha.fin, val_param);
            res = Wke.Presentation.WebControls.GenericAssistantControl.LoadGenericValues(tipo, ' ~' + fecha.fin + '~' + val_param, idcontrol, document.getElementById(idcontrol + 'hiddenUseSearchWildcard').value);
        } 
        else if (fecha.tipo == "en" && fecha.ini) 
        {
            //InsertDateIntoSession(fecha.ini, fecha.ini, val_param);
            res = Wke.Presentation.WebControls.GenericAssistantControl.LoadGenericValues(tipo, fecha.ini + '~' + fecha.ini + '~' + val_param, idcontrol, document.getElementById(idcontrol + 'hiddenUseSearchWildcard').value);
        } 
        else 
        {
            //alert(wcDate_message_ErrorDate);
            alert(wcDate_message_ErrorDate);
            correctDate = false;
        }         
     }
     else
     {
        //InsertDateIntoSession("", "", "");
     }
     return correctDate;
}



function GetAnnoCompleto(str_anno)
{
	if (str_anno.length == 2) {
		var date = new Date();
		var annomax = (date.getFullYear())%100;
		if (str_anno <= annomax) {
			return "20" + str_anno;
		} else {
			return "19" + str_anno;
		}
	}
	if (str_anno.length == 4) {
		return str_anno;
	}
	return "";
}

function GetNumeroMes(str_mes)
{
	var fmt = /^[^\d]+/; // si no es digito hay que convertir a un número
	var res = str_mes.match(fmt);
	if (res) {
		reg_exp = new RegExp(";" + str_mes + ";","i")
		var val_mes = ""
		for (num_mes=0; num_mes<meses.length; num_mes++) {
			if (meses[num_mes].match(reg_exp)) {
				val_mes = num_mes+1;
				break;
			}
		}
		if (val_mes) {
			return val_mes;
		} else {
			return "";
		}
	}
	fmt = /^(1?[012]|[1-9])/; // si es un número entre 1 - 12
	res = str_mes.match(fmt);
	if (res) {
		return str_mes;
	}
	return "";
}

//Parsea los dias y los meses para que los menores de 10 tengan el 0 delante (ej: 01)
function ParsingNumber(number)
{
    var num = number + "";
    if (num.length<2)
    {
        num = "0" + num;
    }
    return num;
}

//Obtiene la fecha de inicio y la fecha de fin de la busqueda
function GetFmtLimites(fecha) {
    //var fmt = /^(del?|desde|>)\s+(.+)(al?|hasta|<)\s+(.+)/i;
    var fmt = fmtall;
    var res = fecha.str.match(fmt);
   if (res) {
       fecha.tipo = "de hasta"
       fecha.ini = GetFmtFecha("ini",res[2]);
       fecha.fin = GetFmtFecha("fin",res[4]);
       return;
   }
   //fmt = /^(desde|del?|>)\s+(.+)/i;
   fmt = fmtsince;
   res = fecha.str.match(fmt);
   if (res) {
       fecha.tipo = "desde"
       fecha.ini = GetFmtFecha("ini", res[2]);
       return;
   }
   //fmt = /^(al?|hasta|<)\s+(.+)/i;
   fmt = fmtto;
   res = fecha.str.match(fmt);
   if (res) {
       fecha.tipo = "hasta"
       fecha.fin = GetFmtFecha("fin", res[2]);
       return;
   }
   fecha.ini = GetFmtFecha("ini",fecha.str);
   fecha.fin = GetFmtFecha("fin",fecha.str);
   if (fecha.ini && fecha.fin) {
       if (fecha.ini == fecha.fin) {
           fecha.tipo = "en";
           return;
       } else {
           fecha.tipo = "de hasta";
           return;
       }
   }
   return;
}

function GetFmtFecha(tipo,str) {
     //var fmt = /^(\d+)\s*(del?)?[\/\-\s]\s*(\w+)\s*(del?)?[\/\-\s]\s*(\d+)\s*/;
    var fmt = fmtfrom;
          
           var res = str.match(fmt);
           if (res) {
                       var dia = res[1];
                       var mes = GetNumeroMes(res[3]);
                       var anno = GetAnnoCompleto(res[5]);
                       return GetFecha(dia,mes,anno);
                   }
                   //fmt = /^(\w+)\s*(del?)?[\/\-\s]\s*(\d+)\s*/;
                   fmt = fmtfrom2;
           res = str.match(fmt);
           if (res) {
                       var mes = GetNumeroMes(res[1]);
                       var anno = GetAnnoCompleto(res[3]);
                       if (tipo == "ini") {
                                  return GetFecha(1,mes,anno);
                       }
                       if (tipo == "fin") {
                                   var fecha_ini_mes_sig = new Date(anno,mes,1)
                                  var val_fecha = fecha_ini_mes_sig.valueOf();
                                  val_fecha -= 86400000 // Le resto los milisegungos de un día
                                  var fecha_fin_mes = new Date(val_fecha);
                                  return GetFecha(fecha_fin_mes.getDate(),mes,anno);
                       }
           }
           fmt = /^(\d+)\s*/;
           res = str.match(fmt);
           if (res) {
                       var anno = GetAnnoCompleto(res[1]);
                       if (tipo == "ini") {
                                  return GetFecha(1,1,anno);
                       }
                       if (tipo == "fin") {
                                  return GetFecha(31,12,anno);
                       }
           }
           return "";
}

/* Obtiene una fecha estandar para poder hacer la consulta */
function GetFecha(str_dia, str_mes, str_anno)
{
           if (str_dia && str_mes && str_anno) {
                      return str_anno + separator + ParsingNumber(str_mes) + separator + ParsingNumber(str_dia);
           } else {
                      return "";
           }
} 

function Fecha(str_fecha) {
	this.str = str_fecha;
	this.ini = "";
	this.fin = "";
	this.tipo = "";
}

// Ano minimo y ano maximo
var minYear=1000;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

//se comprueba el numero de dias que tiene febrero, dependiendo de si es bisiesto o no
function daysInFebruary (year){
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31;
		if (i==4 || i==6 || i==9 || i==11) 
		{
		    this[i] = 30;
		}
		if (i==2) 
		{
		    this[i] = 29;
		}
   } 
   return this;
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12);
	
	
	var strYear=dtStr.substring(0,4);
	var strMonth=dtStr.substring(5,7);
	var strDay=dtStr.substring(8,dtStr.length);
	//alert(strDay+'--'+strMonth+'--'+strYear);
	strYr=strYear;
	if (strDay.charAt(0)=="0" && strDay.length>1) 
	    strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) 
	    strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1);
	}
	month=parseInt(strMonth);
	day=parseInt(strDay);
	year=parseInt(strYr);
	//alert(day+'--'+month+'--'+year);
	//if(isNaN(day) || isNaN(month) || isNaN(year))
	//    return false;
	if (strMonth.length<1 || strMonth.length>2 || month<1 || month>12){
		return false;
	}
	if (strDay.length<1 || strDay.length>2 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month] || day =='Nan' ){
		return false;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		return false;
	}
	
    return true;
}

//Valida la fecha de inicio y la fecha de fin
function ValidateDates(fecha)
{
    if (fecha.ini != "")
    {
        if (!isDate(fecha.ini))
            return false;
    }
    if (fecha.fin != "")
    {
        if (!isDate(fecha.fin))
            return false;
    }
    return true;
}
function AjaxCachePageControl_load(target,method,obj,callback)
{
    Wke.Presentation.WebControls.AjaxCachePageControl.AjaxCahePageControl_OnLoad(target,method,obj,callback);
}

function AjaxCachePageControl_Callback(res)
{
//    if(res.value==null)
//        //alert('Error in AjaxCachePageControl_Callback, see the log file.');
//    else
//    {
        //alert('AjaxCachePageControl_Callback por defecto,implementar por cada control si propio callback si fuera necesario, aunque sea uno vacio');
        //ejemplo de recoger los valores
        //alert(response.value.name+'--'+response.value.number);
//    }
}

var redirectControl = null;

function CreateRedirect(htmlout, height, width, Region) {
    redirectControl = new Ext.Panel({
        html: htmlout,
        margins: '0 0 5 0',
        region: Region
    });
    if (returnAllResultsItemControl == null)
    if (height != 0) {
        redirectControl.setHeight(height);
        redirectControl.autoHeight = false;
    }
    if (width != 0) {
        redirectControl.setWidth(width);
        redirectControl.autoWidth = false;
    }
}

