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 = [];
		for(var i=0; i<this.arguments.length; 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 aquí de forma temporal
function SaltoExt(url)
{
 window.open(url);
} 



//var xmlHttp = createXmlHttpRequestObject();

//function createXmlHttpRequestObject()
//{
// 
//  var xmlHttp;
// 
//  try
//  {
//   
//    xmlHttp = new XMLHttpRequest();
//  }
//  catch(e)
//  {
//    //  IE6 
//    var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
//                                    "MSXML2.XMLHTTP.5.0",
//                                    "MSXML2.XMLHTTP.4.0",
//                                    "MSXML2.XMLHTTP.3.0",
//                                    "MSXML2.XMLHTTP",
//                                    "Microsoft.XMLHTTP");
//   
//    for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++)
//    {
//      try
//      {
//        
//        xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
//      }
//      catch (e) {}
//    }
//  }
// 
//  if (!xmlHttp)
//    alert("Error creating the XMLHttpRequest object.");
//  else
//    return xmlHttp;
//}

//function process(pageprocess)
//{

//  if (xmlHttp)
//  {
//   
//    try
//    {
//     
//      xmlHttp.open("GET",pageprocess, true);
//      xmlHttp.onreadystatechange = handleRequestStateChange;
//      xmlHttp.send(null);
//    }

//    catch (e)
//    {
//      alert("Can't connect to server:\n" + e.toString());
//    }
//  }
//}


//function handleRequestStateChange()
//{
//  
//  if (xmlHttp.readyState == 4)
//  {
//    
//    if (xmlHttp.status == 200)
//    {
//      try
//      {
//        
//        //esto funciona
//      }
//      catch(e)
//      {
//        // display error message
//        alert("Error reading the response: " + e.toString());
//      }
//    }
//    else

//    {
//      // display status message
//      alert("There was a problem retrieving the data:\n" +
//            xmlHttp.statusText);
//    }
//  }
//}



/**************************************************************************/
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();
	    }        
	};

    OnLoadCache();
    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 extraño 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;
       
    /* CRC (16/04/2008)
       MODIFICACION PARA EVITAR POSICIONAMIENTO DE LA CAPA DE CONTENIDO 
       POR JAVASCRIPT CUANDO SE ESTE CARGANDO UN DOCUMENTO */
    var setBodyHeight= true;
    //if (document.getElementById("cDocument") != null){
    //    setBodyHeight= false;
    //}
    
    if(setBodyHeight) {
        if (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;
                }
                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 (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");
var PutItCenter="";

/**
 * Clase que encapsula un contenedor de la pagina web.
 */
function CPopup(nombre)
{
    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 = "";
}


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.
    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();
        }
        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.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();
};

//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;    
    
    this.closeButton.onclick = function() {popup.ClosePopup();}
};

//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)
    {
        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);    
    }
    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(url) 
{
    if (!this.request)
    {
        alert("ERROR AL INICIALIZAR!");
    }
    else
    {
        if ((url.toLowerCase( ).indexOf(".gif") != -1) || (url.toLowerCase( ).indexOf(".jpg") != -1) || (url.toLowerCase( ).indexOf(".png") != -1))
        {
            this.contentDiv.innerHTML = '<img src="' + url + '" />';
        }
        else
        {
            this.contentDiv.innerHTML = '<p style="margin-top: 200px;text-align:center;"><img src="../Img/popup_load.gif" /></p>';
            this.request.open("GET", url);
            //this.request.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" );
            var popup = this;
            this.request.onreadystatechange = function() 
            {
                if (popup.request.readyState == 4) 
                {
                    popup.contentDiv.innerHTML = popup.request.responseText;
                    popup.enterFunction = RecoverEnterFunction(popup.request.responseText);
                    if (popup.onLoadFunction != "")
                    {
                        eval(popup.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;
}
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();


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);
//    }
}

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();


//window.onclick = function(){
//    var idSession = window.idSessionUser != null ? window.idSessionUser : window.opener.idSessionUser;
//    Wke.Presentation.WebControls.AuthenticationControl.VerifyIdSession(idSession, WhatToDoCallback);
//}

//function WhatToDoCallback(result)
//{
//    if (result.value != null)
//    {
//        if (result.value.urlError != null)
//        {
//            //Hay un popup abierto
//            if (window.opener != null)
//            {
//                window.opener.ExecuteClosePopup();
//                window.opener.location.href = result.value.urlError;
//            }
//            //Estamos en la pagina principal
//            else
//            {
//                window.location.href = result.value.urlError;
//            }            
//        }
//    }
//}


var swlogin=false;




function validate_swlogin()
{
   if(swlogin)
    {
        swlogin=false;
        return true;
    }
    else
    {
        return false;
    }
}

function ChangePermissions(div,divlogin)
{
    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.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()
{
    var arr=document.getElementById('logindiv').getElementsByTagName('input');
            if(arr.length>0)
                arr[0].disabled=false;
    var form  = document.forms[0];
	    form.onsubmit = function(){return true;};
}

function disable_logout()
{
    var arr=document.getElementById('logindiv').getElementsByTagName('input');
            if(arr.length>0)
                arr[0].disabled=true;
}
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 añadimos 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';
      }
  }
}

if(typeof Wke == "undefined") Wke={};
if(typeof Wke.Presentation == "undefined") Wke.Presentation={};
if(typeof Wke.Presentation.WebControls == "undefined") Wke.Presentation.WebControls={};
Wke.Presentation.WebControls.DocumentaryTypeControl_class = function() {};
Object.extend(Wke.Presentation.WebControls.DocumentaryTypeControl_class.prototype, Object.extend(new AjaxPro.AjaxClass(), {
	url: '/ajaxpro/Wke.Presentation.WebControls.DocumentaryTypeControl,Wke.Presentation.ashx'
}));
Wke.Presentation.WebControls.DocumentaryTypeControl = new Wke.Presentation.WebControls.DocumentaryTypeControl_class();


function DocumentaryTypeLoad(target, method, idFile)
{    
    var obj=new Object();
    obj.FileId = idFile;
    AjaxCachePageControl_load(target, method,obj,DocumentaryTypeLoadCallback);      
}

function DocumentaryTypeLoadCallback(res)
{
}

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();


if(typeof Wke == "undefined") Wke={};
if(typeof Wke.Presentation == "undefined") Wke.Presentation={};
if(typeof Wke.Presentation.WebControls == "undefined") Wke.Presentation.WebControls={};
Wke.Presentation.WebControls.SearchControl_class = function() {};
Object.extend(Wke.Presentation.WebControls.SearchControl_class.prototype, Object.extend(new AjaxPro.AjaxClass(), {
	AjaxChkSearch_OnClickDirecto: function(hash) {
		return this.invoke("AjaxChkSearch_OnClickDirecto", {"hash":hash}, this.AjaxChkSearch_OnClickDirecto.getArguments().slice(1));
	},
	url: '/ajaxpro/Wke.Presentation.WebControls.SearchControl,Wke.Presentation.ashx'
}));
Wke.Presentation.WebControls.SearchControl = new Wke.Presentation.WebControls.SearchControl_class();


function SearchLoad(target, method,id,tipo,visible,chekado, methodCallback)
{   
    var obj=new Object();  
    obj.TargetCallback = target;
    obj.MethodCallback = methodCallback;
    obj.id=id;
    obj.tipo = tipo;
    obj.visible = visible;
    obj.chekado = chekado;
    AjaxCachePageControl_load(target, method,obj,SearchLoadCallback);                                                                  
}    


function initSearchControl(idcontrol,path,assistant,activetab)
{
    if(document.getElementById('SearchControlBox')==null)
	{

		var h=document.createElement('input');
		h.type='hidden';
		h.id='SearchControlBox';
		document.getElementById(idcontrol+'DivTxtSearch').appendChild(h);
		document.getElementById('SearchControlBox').value=idcontrol;
		
		var hh=document.createElement('input');
		hh.type='hidden';
		hh.id='searchPageResultList';
		document.getElementById(idcontrol+'DivTxtSearch').appendChild(hh);
		document.getElementById('searchPageResultList').value=path;
		
		var hhh=document.createElement('input');
		hhh.type='hidden';
		hhh.id='WithAssistants';
		document.getElementById(idcontrol+'DivTxtSearch').appendChild(hhh);
		document.getElementById('WithAssistants').value=assistant;

		var InputActiveTab=document.createElement('input');
		InputActiveTab.type='hidden';
		InputActiveTab.id='ActiveTab';
		document.getElementById(idcontrol+'DivTxtSearch').appendChild(InputActiveTab);
		document.getElementById('ActiveTab').value=activetab;
		//aunque haya varios en asistentes solo habra uno, por lo que el primero definira los asistentes

	}
	else
	{
		document.getElementById('SearchControlBox').value=document.getElementById('SearchControlBox').value + '|' + idcontrol;
	}
}   

function SearchLoadCallback(res)
{
    if(res != null)  
    {       
        document.getElementById(res.value.id+'TxtSearch').value = res.value.LastTextSearch;
        if (document.getElementById(res.value.id + 'ChkSynonym') != null) {
            document.getElementById(res.value.id + 'ChkSynonym').checked = res.value.LastSynonymSearch;
        }
        if (res.value.LastTextSearch + '' != '') {
            SearchAjaxChkSearch_OnClick(res.value.TargetCallback, res.value.MethodCallback, res.value.id);
        } 
    }        
} 

// idControl-> identificador del SearhButtonControl. Esto solo viajará en el caso de que en el SearchButtonControl se haya puesto el parametro
// pathResultList.
function SearchAjaxBtnSearch_OnClick(target, method, idControl, pageNoData, idControlStatistic)
{       
    //abujalance, comprobamos si existen asistentes genericos
    if(typeof load_generic_values == 'function') 
    {
        // Mandamos a servidor el valor de los asistentes genericos.
        if(!load_generic_values(idControl))
            return ""; //quito la ejecucion
    }

    //abujalance, comprobamos los asistentes de seleccion
    if(typeof loadSelectionAssistantValues=='function')
    {
        loadSelectionAssistantValues();       
    }
    
     var obj = new Object();
    
     //abujalance
    //obj.QueryText = document.getElementById(searchIdTxtSearch).value;
    var arr=document.getElementById('SearchControlBox').value.split('|');
    obj.QueryText='';
    var sinonym=false;
    
    for(i=0;i<arr.length;i++)
    {
        //el tipohiddenpasara a ser el tipo de cada caja, que pondremos por configuracion
        if(document.getElementById(arr[i]+'TxtSearch').value!='')
        {
            if(obj.QueryText!='')
                obj.QueryText = obj.QueryText + '~' + document.getElementById(arr[i]+'TxtSearch').value + '@' +  document.getElementById(arr[i]+'hidtype').value + '@' + arr[i];
            else
            {
                obj.QueryText = document.getElementById(arr[i]+'TxtSearch').value + '@' + document.getElementById(arr[i]+'hidtype').value + '@' + arr[i];
            }
        }
        if(document.getElementById(arr[i]+'ChkSynonym')!=null)
        {
            if (document.getElementById(arr[i] + 'ChkSynonym').checked) {
                sinonym = true;
            }
        }
    }
    obj.Synonym=sinonym;
    obj.WithAssistants = document.getElementById('WithAssistants').value; 
    obj.ResultListPage = document.getElementById('searchPageResultList').value;
    //fin abujalance

    // sebas: Necesitamos para estdisticas que siempre se envia el idcontrol, para no rehacer el resto del
    // codigo pasamos otro parametro con dicho identificador a la espera de poder rehacer el control una vez
    // tengamos tiempo de desarrollo disponible.
    if (idControlStatistic != null)
    {
        // Si estamos en un SearchControl pueden venir mas de un identificador de control
        // que será la lista de SearchButtonControl a los que se puede redirigir
        // Buscamos el primero que exista, asignamos valores y salimos.
        var arrSCB = idControlStatistic.split('|');
        for (i = 0; i < arrSCB.length; i++) 
        {
            try {
                var cpi = "cpi_" + arrSCB[i];
                var cpd = "cpd_" + arrSCB[i];
                var cmi = "cmi_" + arrSCB[i];
                var ubs = "ubs_" + arrSCB[i];
                obj.idControlStatistic = arrSCB[i];
                obj.cpi = eval(cpi);
                obj.cpd = eval(cpd);
                obj.cmi = eval(cmi);
                obj.ubs = eval(ubs);
                break;
            }
            catch (err)
            { }
        }
    }// sebas
   
    // jc: Si el SearchButtonControl pasa idControl, la pagina  a la que redirecciona el control debe ser la que
    // establece el SearchButtonControl y no la de SearchControl.
    if (idControl != undefined) 
    {
        var paginaSaltoSearchButton = "searchbtnPageResultList_" + idControl;
        obj.ResultListPage = eval(paginaSaltoSearchButton);
        obj.idControl = idControl;
        obj.idSearchButtonControl = idControl;
        obj.ActiveTab = eval("activeTab_" + idControl); // Marcamos como active tab el del searchButtonControl no el del SearchControl
        obj.IdDocumentaryType = eval("idDocumentaryType_" + idControl); // Marcamos como documentayType el del searchButtonControl no el del control web documentaryTypeControl
    }
    else
    {
       obj.idSearchButtonControl =""
       obj.ActiveTab = document.getElementById("ActiveTab").value; // Marcamos como active tab el del SearchControl no el de SearchButtonControl
    }
    obj.pageNoData=pageNoData;
    
    
    //fin abujalance
    var res=Wke.Presentation.WebControls.AjaxControl.AjaxControl_Click(target, method, obj);
    SearchAjaxBtnSearch_Callback(res,pageNoData);       
}

function SearchAjaxBtnSearch_Callback(res,pageNoData)
{   
    if(res != null)  
    {           
        if(res.value.ResultListFullPath=='')
        {
            
            //en caso de que no tenga valores, pondremos el foco en la primera caja
            var idtxt=document.getElementById('SearchControlBox').value.split('|')[0]+'TxtSearch';
            //alert(searchMessageEmpty);
            eval(searchMessageEmpty);
            document.getElementById(idtxt).select();
            document.getElementById(idtxt).focus();
        }
        else
        {       
            window.location.href = res.value.ResultListFullPath;              
        }
    }        
}


function ClearAllSearch()
{
     var arr=document.getElementById('SearchControlBox').value.split('|');
    for(i=0;i<arr.length;i++)
    {
    document.getElementById(arr[i]+'TxtSearch').value = '';   
    document.getElementById(arr[i]+'DivSynonymTitle').innerHTML = '';
    document.getElementById(arr[i]+'DivSynonymText').innerHTML = '';
    document.getElementById(arr[i]+'DivSynonym').style.display ='none';
    }
}

//function SearchAjaxTxtSearch_OnClick(target,method,id)
//{      
//        //sin intervalo
//       //SearchAjaxChkSearch_OnClick(target,method,id);
//      
//        if(eval('intervaltime'+id+'>0'))
//        {
//        //formula vieja
////            //con intervalo
////            if(eval('interval'+id+'!=null'))
////            {
////                clearTimeout(eval('interval'+id));
////                eval('interval'+id+'=null;');
////            }
////            eval('interval'+id+'=setTimeout("SearchAjaxChkSearch_OnClick(\''+target+'\',\''+method+'\',\''+id+'\')",intervaltime'+id+')');

//        //formula nueva
//        if(eval('interval'+id+'==null'))
//        {
//            eval('interval'+id+'=setTimeout("SearchAjaxChkSearch_OnClick(\''+target+'\',\''+method+'\',\''+id+'\')",intervaltime'+id+')');
//         }
//      }
//      else
//      {
//        SearchAjaxChkSearch_OnClick(target,method,id);
//      }
//      
//}


function LaunchSinonimTime(target,method,id,time)
{
    eval('interval'+id+'=""');
    setInterval("SearchAjaxChkSearch_OnClick('"+target+"','"+method+"','"+id+"');",time);
}

var oneEnter=false;

function SearchSubmitEnter(myfield,e, target, method, idControl, idControlStatistic)
{
	var keycode;
	if (window.event)
	{
		keycode = window.event.keyCode;
	}
	else if (e)
	{
		keycode = e.which;
	}
	else
	{
		return true;
	}
	if (keycode == 13)
	{
	    if(!oneEnter)
	    {
	    oneEnter=true;
	    setTimeout("oneEnter=false;",1000);
	     var res=Wke.Presentation.WebControls.PageControl.VerifySession(document.location.href);
        if (res.value!="true")
        {
            //alert(res.value);
            window.location.href=res.value;
            return false;
        }
   
	    var form  = document.forms[0];
	    form.onsubmit = function(){return false;};
	    if(typeof(disable_logout)=='function')
	        disable_logout();
	    SearchAjaxBtnSearch_OnClick(target, method, idControl, null, idControlStatistic);		
		return false;
		
		}
	}
	else
	{
	    if (keycode == 64)
	    {
	        return false;
	    }
	     if (keycode == 35)
	    {
	        return false;
	    }
	    else
	    {
	        return true;
	    }
		
	}
}

function SearchAjaxTxtSearch_Callback(res)
{
}

function SearchAjaxChkSearch_OnClick(target,method,id) {
    try {
        if (document.getElementById(id + 'ChkSynonym') != null) {
            if (document.getElementById(id + 'ChkSynonym').checked) {
                if (eval('interval' + id + '!=document.getElementById(\'' + id + 'TxtSearch\').value')) {
                    eval('interval' + id + '=document.getElementById(\'' + id + 'TxtSearch\').value;')
                    var obj = new Object();
                    obj.QueryText = document.getElementById(id + 'TxtSearch').value;
                    obj.id = id;
                    //AjaxControl_Default(target, method, obj, SearchAjaxChkSearch_Callback);
                    Wke.Presentation.WebControls.SearchControl.AjaxChkSearch_OnClickDirecto(obj, SearchAjaxChkSearch_Callback);
                }
            }
            else {
                eval('interval' + id + '=\'\';');
                document.getElementById(id + 'DivSynonymTitle').innerHTML = '';
                document.getElementById(id + 'DivSynonymText').innerHTML = '';
                document.getElementById(id + 'DivSynonym').style.display = 'none';
            }
        }
    } catch (e) { }  	
}

function SearchAjaxChkSearch_Callback(res)
{   
    document.getElementById(res.value.id+'DivSynonym').style.display ='block';
	document.getElementById(res.value.id+'DivSynonymText').innerHTML = res.value.SynonymousText;
	document.getElementById(res.value.id+'DivSynonymTitle').innerHTML = res.value.SynonymTitle;	 
	//Se añade la siguiente línea para que al aparecer el scroll en la búsqueda no cambie de posición la página
	document.getElementById(res.value.id+'DivSynonymText').style.position='relative';
	setTimeout("document.getElementById('"+res.value.id+"DivSynonymText').style.position='static'",100);
	//eval('interval'+res.value.id+'=null;')
}

function SearchClean(target,method,id)
{
    document.getElementById(id+'TxtSearch').value = '';
    document.getElementById(id+'DivSynonymText').innerHTML = '';
    SearchAjaxBtnSearch_OnClick(target,method, null, null, id);
}
	

if(typeof Wke == "undefined") Wke={};
if(typeof Wke.Presentation == "undefined") Wke.Presentation={};
if(typeof Wke.Presentation.WebControls == "undefined") Wke.Presentation.WebControls={};
Wke.Presentation.WebControls.SelectionAssistantControl_class = function() {};
Object.extend(Wke.Presentation.WebControls.SelectionAssistantControl_class.prototype, Object.extend(new AjaxPro.AjaxClass(), {
	CleanSelectionValues: function(uniqueId, id, boolinvisible) {
		return this.invoke("CleanSelectionValues", {"uniqueId":uniqueId, "id":id, "boolinvisible":boolinvisible}, this.CleanSelectionValues.getArguments().slice(3));
	},
	LoadValues: function(tipo, valor, idcontrol) {
		return this.invoke("LoadValues", {"tipo":tipo, "valor":valor, "idcontrol":idcontrol}, this.LoadValues.getArguments().slice(3));
	},
	url: '/ajaxpro/Wke.Presentation.WebControls.SelectionAssistantControl,Wke.Presentation.ashx'
}));
Wke.Presentation.WebControls.SelectionAssistantControl = new Wke.Presentation.WebControls.SelectionAssistantControl_class();


function loadSelection(idcontrol)
{
    if(document.getElementById('SelectionAssistantBox')==null)
	{
		var h=document.createElement('input');
		h.type='hidden';
		h.id='SelectionAssistantBox';
		document.getElementById(idcontrol+'divselection').appendChild(h);
		document.getElementById('SelectionAssistantBox').value=idcontrol;
	}
	else
	{
		document.getElementById('SelectionAssistantBox').value=document.getElementById('SelectionAssistantBox').value + '|' + idcontrol;
	}
}



function clean_selection_values(all)
{
   if (document.getElementById('SelectionAssistantBox')!=null)
   {
        var arr=document.getElementById('SelectionAssistantBox').value.split('|');
        try
        {
            for(i=0;i<arr.length;i++)
            {
                var res=Wke.Presentation.WebControls.SelectionAssistantControl.CleanSelectionValues(document.getElementById(arr[i]+'hiddenUniqueId').value,arr[i],document.getElementById(arr[i]+'hiddenInvisibleId').value);
                if(all)
                    eval(res.value);
            }
        }catch (e)
            {
                for(i=0;i<arr.length;i++)
                {
                    var res=Wke.Presentation.WebControls.AssistantMatterControl.CleanSelectionValues(document.getElementById(arr[i]+'hiddenUniqueId').value,arr[i],document.getElementById(arr[i]+'hiddenInvisibleId').value);
                    if(all)
                        eval(res.value);
                }
            }
          
       }
}

function loadSelectionAssistantValues()
{
    clean_selection_values(false);
    var arr=document.getElementById('SelectionAssistantBox').value.split('|');
    try{
        for(iii=0;iii<arr.length;iii++)
        {
            var valor=getSelectionValue(arr[iii]);
            if(valor!='')
            {
                var res=Wke.Presentation.WebControls.SelectionAssistantControl.LoadValues(document.getElementById(arr[iii]+'hiddenMeta').value,valor,arr[iii]);
                eval(res.value);
             }
        }
     }catch(e)
        {
            for(iii=0;iii<arr.length;iii++)
            {
                var valor=getSelectionValue(arr[iii]);
                if(valor!='')
                {
                    var res=Wke.Presentation.WebControls.AssistantMatterControl.LoadValues(document.getElementById(arr[iii]+'hiddenMeta').value,valor,arr[iii]);
                    eval(res.value);
                 }
            }
        }
}

function getSelectionValue(id)
{  
    var valor='';
    //select
    if(document.getElementById(id+'select')!=null)
    {
       valor= document.getElementById(id+'select').options[document.getElementById(id+'select').selectedIndex].value;
    }
    else //radio
    {
        var arr=document.getElementById(id+'divselection').getElementsByTagName('input');
        for (i=0;i<arr.length;i++)
       {
            if(arr[i].type=='radio')
            {
                if (arr[i].checked)
                {
                    valor=arr[i].value;
                    break;
                }
            }
            if(arr[i].type=='checkbox')
            {
                if (arr[i].checked)
                {
                    valor+=arr[i].value+'|';
                
                }
            }
//            if (arr[i].type=='hidden' && arr[i].id=='SelectedOption')
//            {
//                valor=document.getElementById('SelectedOption').value;
//                break;
//            }
       }
    }
    return valor;
}


function SelectionAssistantCache(target,method,uniqueid,id)
{
    var obj=new Object();
    obj.id=id;
    obj.uniqueid=uniqueid;
    AjaxCachePageControl_load(target, method,obj,SelectionLoadCallback);
}

function SelectionLoadCallback(res)
{
    if(res!=null)
    {
        eval(res.value.result);
    }
}


// Funcion que se ejecuta cuando se hace onClick sobre un SearchButtonControl. El idControl solo viajara en el caso de que en en 
// searchButtonControl se haya puesto el parametro PathResultList.
function SearchAjaxButtonSearch_OnClick(target,method,idControl,pageNoData, idControlStatistic)
{ 
    if(typeof(SearchAjaxBtnSearch_OnClick)=="function")
        {
            var res=Wke.Presentation.WebControls.PageControl.VerifySession(document.location.href);
            if (res.value=="true")
            {
                   SearchAjaxBtnSearch_OnClick('Wke.Presentation.WebControls.SearchControl', 'AjaxBtnSearch_OnClick', idControl, pageNoData, idControlStatistic);  
            }
            else
            {
                window.location.href=res.value;
            }
            
        }
    else
    {
    //abujalance, comprobamos si existen asistentes genericos
    if(typeof load_generic_values == 'function') {
        if(!load_generic_values())
            return ""; //quito la ejecucion
    }
    
     //abujalance, comprobamos los asistentes de seleccion
    if(typeof loadSelectionAssistantValues=='function')
    {
        loadSelectionAssistantValues();
    }
    
    var obj = new Object();
   
    obj.ResultListPage = searchbtnPageResultList;  
    obj.ActiveTab = activeTab;  
    obj.pageNoData=pageNoData;    
    var res=Wke.Presentation.WebControls.AjaxControl.AjaxControl_Click(target, method, obj);
    SearchAjaxButtonSearch_Callback(res);  
    }
}

function SearchAjaxButtonSearch_Callback(res)
{   
    if(res != null)  
    {           
        if(res.value.ResultListFullPath=='')
        {
                alert(searchbtnMessageEmpty);            
        }
        else
        {       
            window.location.href = res.value.ResultListFullPath;              
        }
    }        
}

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';
    }
}

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';
        }
    }   
    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.EditionsCalendarControl_class = function() {};
Object.extend(Wke.Presentation.WebControls.EditionsCalendarControl_class.prototype, Object.extend(new AjaxPro.AjaxClass(), {
	LoadNumberComboSearch: function(codrev, ano, id) {
		return this.invoke("LoadNumberComboSearch", {"codrev":codrev, "ano":ano, "id":id}, this.LoadNumberComboSearch.getArguments().slice(3));
	},
	LoadNumberSearch: function(div, numero, codrev, id) {
		return this.invoke("LoadNumberSearch", {"div":div, "numero":numero, "codrev":codrev, "id":id}, this.LoadNumberSearch.getArguments().slice(4));
	},
	LoadDateSearch: function(div, fecha, codrev, id) {
		return this.invoke("LoadDateSearch", {"div":div, "fecha":fecha, "codrev":codrev, "id":id}, this.LoadDateSearch.getArguments().slice(4));
	},
	LoadCalendar: function(div, year, month, codrev, minyea) {
		return this.invoke("LoadCalendar", {"div":div, "year":year, "month":month, "codrev":codrev, "minyea":minyea}, this.LoadCalendar.getArguments().slice(5));
	},
	ComposeUrlParams: function(doc, altpage, datenew, datedoc, year, month, idcontrol) {
		return this.invoke("ComposeUrlParams", {"doc":doc, "altpage":altpage, "datenew":datenew, "datedoc":datedoc, "year":year, "month":month, "idcontrol":idcontrol}, this.ComposeUrlParams.getArguments().slice(7));
	},
	url: '/ajaxpro/Wke.Presentation.WebControls.EditionsCalendarControl,Wke.Presentation.ashx'
}));
Wke.Presentation.WebControls.EditionsCalendarControl = new Wke.Presentation.WebControls.EditionsCalendarControl_class();


function loadcalendar(year,month,idcontrol)
{
    
    try
    {
        Wke.Presentation.WebControls.EditionsCalendarControl.LoadCalendar(idcontrol+'calcont',year,month,document.getElementById('cod'+idcontrol).value,document.getElementById('year'+idcontrol).value,loadcalendarCallback);
    }
    catch(e)
    {
       // alert('error in LoadCalendar: ' +e.message);
        Wke.Presentation.WebControls.EstandarCalendarControl.LoadCalendar(idcontrol+'calcont',year,month, document.getElementById('year'+idcontrol).value,loadcalendarCallback);
    }
}

function loadnumbersearch(number,idcontrol)
{
    try
    {
    document.getElementById('resnumber').innerHTML='Loading ...';
    Wke.Presentation.WebControls.EditionsCalendarControl.LoadNumberSearch('resnumber',number,document.getElementById('cod'+idcontrol).value,idcontrol,loadnumbersearchCallback);
    }
    catch(e)
    {
        alert('error in loadnumbersearch: ' +e.message);
    }
}

function loaddatesearch(date,idcontrol,msgerror)
{
    try
    {
    //comprobamos fecha
    var fecha = new Fecha(date);
        GetFmtLimites(fecha);
        //Comprobamos que las fechas están dentro de rangos permitidos
        if (!ValidateDates(fecha))
        {
            alert(msgerror);
            document.getElementById('datesearchtext').focus();
            return false;
        }
        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(msgerror);
            document.getElementById('datesearchtext').focus();
            return false;
        }         
    //fin comprobacion
    document.getElementById('resdate').innerHTML='Loading ...';
    Wke.Presentation.WebControls.EditionsCalendarControl.LoadDateSearch('resdate',date,document.getElementById('cod'+idcontrol).value,idcontrol,loadnumbersearchCallback);
    }
    catch(e)
    {
        alert('error in loaddatesearch: ' +e.message);
    }
}


function loadcombosearch(idcontrol)
{
   try
{
    var date=document.getElementById('yearsearchselect').options[document.getElementById('yearsearchselect').selectedIndex].value+'/'+document.getElementById('monthsearchselect').options[document.getElementById('monthsearchselect').selectedIndex].value + '/01';
    document.getElementById('rescombodate').innerHTML='Loading ...';
    Wke.Presentation.WebControls.EditionsCalendarControl.LoadDateSearch('rescombodate',date,document.getElementById('cod'+idcontrol).value,idcontrol,loadnumbersearchCallback);
    }
    catch(e)
    {
        alert('error in loadcombosearch: ' +e.message);
    }
}

function loadnumbersearchCallback(res)
{
    try
{
    document.getElementById(res.value[0]).innerHTML=res.value[1];
    }
    catch(e)
    {
        alert('error in loadnumbersearchCallback: ' +e.message);
    }
}

function loadcalendarCallback(res)
{
try
{
    document.getElementById(res.value[0]).innerHTML=res.value[1];
    }
    catch(e)
    {
        alert('error in LoadCalendarCallback: ' +e.message);
    }
}

function clickday(doc,altpage,datenew,datedoc,year,month,idcontrol)
{
    //alert(day+'/'+month+'/'+year);
    //alert(doc);
    Wke.Presentation.WebControls.EditionsCalendarControl.ComposeUrlParams(doc,altpage,datenew,datedoc,year,month,idcontrol,loadparams_callback);
}

function clicknumber(number,doc,altpage,datenew,datedoc,year,month,idcontrol)
{
    //alert(number+'---'+doc);
    Wke.Presentation.WebControls.EditionsCalendarControl.ComposeUrlParams(doc,altpage,datenew,datedoc,year,month,idcontrol,loadparams_callback);
}

function loadparams_callback(res)
{
try
{
    eval(res.value);
    }
    catch(e)
    {
        alert('error in loadparams_callback: ' +e.message);
    }
}


function loadnumbercombo(codrevista,id)
{
    var sel =document.getElementById('numbercombosearchselect');
    while(sel.length>0)
    {
        sel.remove(0);
    }
    sel.options[0]=new Option('--','');
    if(document.getElementById('yearnumbersearchselect').options[document.getElementById('yearnumbersearchselect').selectedIndex].value!='')
    {
    var arr=Wke.Presentation.WebControls.EditionsCalendarControl.LoadNumberComboSearch(codrevista,document.getElementById('yearnumbersearchselect').options[document.getElementById('yearnumbersearchselect').selectedIndex].value,id).value;
    if(arr[0]=='error')
    {
        alert('internal error, try again');
        return "";
    }
    
    for(i=0;i<arr.length;i++)
    {
        var arr2=arr[i].split('~');
        sel.options[i+1]=new Option(arr2[0],arr2[1]);
    }
    }
}

function loadnumbercombodoc()
{
    if(document.getElementById('numbercombosearchselect').options[document.getElementById('numbercombosearchselect').selectedIndex].value!='')
    {
        var arr=document.getElementById('numbercombosearchselect').options[document.getElementById('numbercombosearchselect').selectedIndex].value.split('|');
        var idcontrol=arr[4];
        var doc=arr[0];
        var altpage=document.getElementById('altpage'+idcontrol).value;
        var datenew=document.getElementById('newdate'+idcontrol).value;
        var datedoc=arr[1];
        var year=arr[2];
        var month=arr[3];
        var idcontrol=arr[4];
        Wke.Presentation.WebControls.EditionsCalendarControl.ComposeUrlParams(doc,altpage,datenew,datedoc,year,month,idcontrol,loadparams_callback);
    }
}

// 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.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)
     {
	    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)
{
	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');		
		}
		else
		{
		    if(typeof(SearchAjaxButtonSearch_OnClick)=='function')	    
		    {
		        SearchAjaxButtonSearch_OnClick('Wke.Presentation.WebControls.SearchButtonControl', 'AjaxBtnSearch_OnClick');		
		    }
		    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=document.getElementById('EquivalenceAssitantGenericAndSearchButtonControl').value.split('#');
        // 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 añadiremos 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)
                    {              
                        // 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]);
                        res=resajax.value;
                    }
                    else
                    {
                           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++)
    {
        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)
{
    var obj=new Object();  
    obj.Target = target;
    obj.Method = method;
    obj.Id = id;
    obj.tipo=tipo;
    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] = new String(";enero;ene;I;");
meses[ 1] = new String(";febrero;feb;II;");
meses[ 2] = new String(";marzo;mar;III;");
meses[ 3] = new String(";abril;abr;IV;");
meses[ 4] = new String(";mayo;may;V;");
meses[ 5] = new String(";junio;jun;VI;");
meses[ 6] = new String(";julio;jul;VII;");
meses[ 7] = new String(";agosto;ago;VIII;");
meses[ 8] = new String(";septiembre;sep;IX;");
meses[ 9] = new String(";octubre;oct;X;");
meses[10] = new String(";noviembre;nov;XI;");
meses[11] = 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;
    if (val_param != "")
    { 
        var fecha = new Fecha(val_param);
        GetFmtLimites(fecha);
        //Comprobamos que las fechas están 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;
        }
        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);
        } 
        else if (fecha.tipo == "desde" && fecha.ini) 
        {
            //InsertDateIntoSession(fecha.ini, "", val_param);            
            res=Wke.Presentation.WebControls.GenericAssistantControl.LoadGenericValues(tipo,fecha.ini+'~ '+'~'+val_param,idcontrol);
        } 
        else if (fecha.tipo == "hasta" && fecha.fin) 
        {
            //InsertDateIntoSession("", fecha.fin, val_param);            
            res=Wke.Presentation.WebControls.GenericAssistantControl.LoadGenericValues(tipo,' ~'+fecha.fin+'~'+val_param,idcontrol);
        } 
        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);
        } 
        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 = "";
}

// Año minimo y año 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;
}
if(typeof Wke == "undefined") Wke={};
if(typeof Wke.Presentation == "undefined") Wke.Presentation={};
if(typeof Wke.Presentation.WebControls == "undefined") Wke.Presentation.WebControls={};
Wke.Presentation.WebControls.FormControl_class = function() {};
Object.extend(Wke.Presentation.WebControls.FormControl_class.prototype, Object.extend(new AjaxPro.AjaxClass(), {
	LoadValuesForProvence: function(selectid) {
		return this.invoke("LoadValuesForProvence", {"selectid":selectid}, this.LoadValuesForProvence.getArguments().slice(1));
	},
	url: '/ajaxpro/Wke.Presentation.WebControls.FormControl,Wke.Presentation.ashx'
}));
Wke.Presentation.WebControls.FormControl = new Wke.Presentation.WebControls.FormControl_class();


//js de formularios
function loadformsprovence(ind)
{
    try
    {
    var clientid='sprovence';
    document.getElementById('scityhiden').value='';
    document.getElementById('sprovencehiden').value='';
    document.getElementById('scityhiden').value=document.getElementById('scity').options[document.getElementById('scity').selectedIndex].value;
    var res=Wke.Presentation.WebControls.FormControl.LoadValuesForProvence(ind);
    document.getElementById(clientid).options.length=0;
    for(ires=0;ires<res.value.length;ires++)
    {
        document.getElementById(clientid).options[ires]=new Option(res.value[ires],res.value[ires]);
    }
    }
    catch(e)
    {
    alert('error in loadformsprovence');
    }
}

function loadformsmatter(ind) {
    try {
        //var clientid = 'smatter';
        document.getElementById('smatterhiden').value = '';
        //document.getElementById('sprovencehiden').value = '';
        document.getElementById('smatterhiden').value = document.getElementById('smatter').options[document.getElementById('smatter').selectedIndex].value;
//        var res = Wke.Presentation.WebControls.FormControl.LoadValuesForProvence(ind);
//        document.getElementById(clientid).options.length = 0;
//        for (ires = 0; ires < res.value.length; ires++) {
//            document.getElementById(clientid).options[ires] = new Option(res.value[ires], res.value[ires]);
//        }
    }
    catch (e) {
        alert('error in loadformsmatter');
    }
}

function loadformscheckmatter(id) {
    try {
        document.getElementById('scheckmatterhiden').value = '';
        //hiddenmatter.value = '';
        //document.getElementById('sprovencehiden').value = '';
        var checks = document.getElementById(id).getElementsByTagName('INPUT');
        for (i = 0; i < checks.length; i++) {
            if (checks[i].checked) {
                if (document.getElementById('scheckmatterhiden').value != '') {
                    document.getElementById('scheckmatterhiden').value += '|' + checks[i].name;
                }
                else {
                    document.getElementById('scheckmatterhiden').value = checks[i].name;
                }
            }
        }
    }
    catch (e) {
        alert('error in loadformsmatter');
    }
}

function loadformscheckmatterWS(id) {
    try {
        document.getElementById('scheckmatterhiden').value='';
        //hiddenmatter.value = '';
        //document.getElementById('sprovencehiden').value = '';
        var checks = document.getElementById(id).getElementsByTagName('INPUT');
        for (i = 0; i < checks.length; i++) {
            if (checks[i].checked) {
                if (document.getElementById('scheckmatterhiden').value != '') {
                    document.getElementById('scheckmatterhiden').value += '|' + checks[i].name + '-' + checks[i].value;
                }
                else {
                    document.getElementById('scheckmatterhiden').value = checks[i].name + '-' + checks[i].value;
                }
            }
        }
    }
    catch (e) {
        alert('error in loadformsmatter');
    }
}

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));
	},
	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);
}
/* 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);
	
	for (var i=0; i < Submenues.length; 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;
	for (var i=0; i < MenuEx.length; 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');
	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(){ 
// function Toggle_Comentarios(node, imagen){
	var bComent = document.getElementById('dCm');
	var dTxT  = document.getElementById('dTxT');
  	var refTags = dTxT.getElementsByTagName('cite');
	var estiloActual = bComent.className;
	
	if (typeof refTags != "undefined" ) {
		for (var i=0; i < refTags.length; i++) {
			RecorreC(refTags, estiloActual )
		}
	bComent.className = (estiloActual=='dCmO') ? 'dCmC' : 'dCmO';
	}
}
function RecorreC( refTags, refTagsActual ) {
			if (refTagsActual=="dCmO") {
				for (var i = 0; i < refTags.length; ++i) {
					if (	refTags[i].className=='ccn'){
						refTags[i].className="ccnOff";
					}
				}
			} 
			if (refTagsActual=="dCmC") {
				for (var i = 0; i < refTags.length; ++i) {
					if (	refTags[i].className=='ccnOff'){
						refTags[i].className="ccn";
					}
				}
			}
}
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';
}
// Close Nota Ayuda
function cNt(id){
	var capa    = document.getElementById(id).style;
	capa.display  = 'block';
	capa.display = 'none';
	capa.visibility = 'hidden';
	capa.display  = 'block';
}

//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";
    // Añadimos 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 = "lector.aspx?" + 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 (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;
	    }
	}     
}
function salto_art_caja(ventana) {
    var ancla = document.getElementById('tipo_busq_art');
    var tipoAncla = "art";
    var numero = document.getElementById('num_busq_art').value;
    var articleType = numero.substring(0, 1).toUpperCase();

    if (articleType == 'A' || articleType == 'D' || articleType == 'L' || 
        articleType == 'LO' || articleType=='R') {
        goToFragmentDocumentAnchor("art_" + numero.toUpperCase());
    }
    else {
        numero = numero.replace(/[.,-]/, "");
        ancla = tipoAncla + numero;
        location = "#" + ancla;
    }
}
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 = "http://imgs.wke.es/";
	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 Retirar(capaId)
{
	var capa = document.getElementById(capaId);
	var cssA = capa.className;
	capa.className = (cssA=='nCl') ? 'nOp' : 'nCl';

}

function Posicionar(capaId)
{
	var capa = document.getElementById(capaId);
	var cssA = capa.className;
	capa.className = (cssA=='nCl') ? 'nOp' : 'nCl';


}

function Control()
{
    setTimeout('ControlAux();',1);
}


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('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";
            }
        }
    }
}

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);
	
	for(idarr=0;idarr<arr.length;idarr++)
	{
	    if (arr[idarr].className =="nh")
	    {
	        var capa = arr[idarr].href.replace("javascript:vNt('","");
	        capa=capa.replace("')","");

            if(DOM1)
              {
              	arr[idarr]['onmouseover']=new Function("Posicionar('"+capa+"');");
              	arr[idarr]['onmouseout']=new Function("Retirar('"+capa+"');");

              }
              else if(DOM2)
              {
                  arr[idarr].setAttribute("onmouseover","Posicionar('"+capa+"');");
                  arr[idarr].setAttribute("onmouseout","Retirar('"+capa+"');");
              }
	    }
	}
}

// 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';
            } 
        }
    }
  } 
}






/* 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);
	for (var i=0; i < Submenues.length; 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"){
					Menux.firstChild.nextSibling.addEventListener('click', OpDLc, 0);
				} else {
					Menux.firstChild.addEventListener('click', OpDLc, 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('OpDLc(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);');
				}
			}
		}
	}
}
function OpDLc(E) {
	var elmDT = (DOM1) ? E : E.currentTarget;
	if (DOM1) {
		  if (elmObj == null) elmObj = elmDT;
		  if (elmObj.parentNode == elmDT) return elmObj = elmDT;
	}
	if (DOM2) {
		if (elmDT.nodeName!='DT') {
			return null;
		}
	}
	var estiloActual = elmDT.className;
		elmDT.className = (estiloActual=='dcl') ? 'dop' : 'dcl';
    if(elmDT.nextSibling!=null)
    {
	while (elmDT.nextSibling.nodeName=="#text")
		{
			elmDT= elmDT.nextSibling;
    		}
    }
    var ajaxload = false;
    var auxiliary = elmDT.nextSibling;
    if (auxiliary.id != '') {
        var i = 0;
        for (i; i < auxiliary.childNodes.length; i++) {
            if (auxiliary.childNodes[i].nodeName == "DFN") {
                //Cargar por ajax la tdc
//                var hash = new Object();
//                hash.Idd = auxiliary.id;
//                hash.Vigente = "";
//                hash.RepositoryPath = 'tdc';
//                hash.LanguageDependence = new Boolean(false);
//                var result = Wke.Presentation.WebControls.HtmlViewerControl.LoadInnerHtml(hash);
                //                auxiliary.innerHTML = result.value;
                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';
            }
        }
    }
	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);
        }
    }
//    else {
//        ControlTDC();
//        //node.txtContent=node.innerHTML;
//        //node.firstChild.nextSibling.className = "indice-seleccionado";
//        for (var i = 0; i < node.childNodes.length; i++) {
//            if (node.childNodes[i].nodeName == "A")
//                node.childNodes[i].className = "selected-item";
//        }
//    }
//    OpenTdcNodeViewer(node.id);
//    //Positioning(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';
                };

            };
        }
    }
}

//Funcion que se ejecuta nada mas terminar de cargar el documento
function FinishLoading()
{
    document.getElementById("loadDiv").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);
        }
    }
}
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.substring(0,pos);
            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();
}
