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

if(typeof Wke == "undefined") Wke={};
if(typeof Wke.Presentation == "undefined") Wke.Presentation={};
if(typeof Wke.Presentation.WebControls == "undefined") Wke.Presentation.WebControls={};
Wke.Presentation.WebControls.HtmlViewerControl_class = function() {};
Object.extend(Wke.Presentation.WebControls.HtmlViewerControl_class.prototype, Object.extend(new AjaxPro.AjaxClass(), {
	LoadInnerHtml: function(hash) {
		return this.invoke("LoadInnerHtml", {"hash":hash}, this.LoadInnerHtml.getArguments().slice(1));
	},
	Redirect: function(hash) {
		return this.invoke("Redirect", {"hash":hash}, this.Redirect.getArguments().slice(1));
	},
	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,redirectPage);
        }
    }
}
function RedirectionEBOOK(node, filename, verifyDocType, redirectPage, repositoryPath, bdeFormat)
{
    document.getElementById("ebook_Node").value = node != null ? node : "";
    document.getElementById("ebook_Filename").value = filename != null ? filename : "";
    document.getElementById("ebook_VerifyDocType").value = verifyDocType != null ? verifyDocType : "";
    document.getElementById("ebook_RedirectPage").value = redirectPage != null ? redirectPage : "";
    document.getElementById("ebook_RepositoryPath").value = repositoryPath != null ? repositoryPath : "";
    document.getElementById("ebook_bdeformat").value = bdeFormat != null ? bdeFormat : "";
   
    document.getElementById("ebook_BtnRedirect").click();
}
function RedirectionViewer(node, filename, verifyDocType, redirectPage, repositoryPath, bdeFormat)
{
    if (filename!= null){
        var pos=filename.indexOf('.');
        if (pos==-1)
        {
            document.getElementById("htmlViewer_Filename").value = filename;
            document.getElementById("htmlViewer_Ebook").value = filename;
        }
        else
        {
            document.getElementById("htmlViewer_Filename").value = filename.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();
}
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;
}
var menuControl = null;
var menuItems = new Array();
function aniadirEventos(nodeArg) // tienen que llegar nodos ul
{
    try{
    var nodes=nodeArg.getElementsByTagName("li"); 
     
    for (var i=0;i<nodes.length; i++) // Me recorro todos los hijos del nodo
    {
        var node=nodes[i];
        if (node.nodeName=="LI")  // si son li le 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';
      }
  }
}
function CreateMenuItem(index, itemText, itemLink) {
    var item = new Ext.menu.Item({
        text: itemText,
        href: itemLink
    });
    menuItems[index] = item;
}
function CreateSumenuItems(index, itemText, listItems) {
    var subMenuItems= new Array();
    for (i=0;i<listItems.length;i++){
        var menuItem=new Ext.menu.Item({
                        text: listItems[i].Text,
                        href: listItems[i].Href
                        });
        subMenuItems[i]=menuItem;
    }
    var submenu= new Ext.menu.Menu({
                    text: itemText,
                    items: subMenuItems
                });
    var item = new Ext.menu.Item({
        text: itemText,
        menu: submenu
    });
    menuItems[index] = item;
}
function CreateMenu(activeIndex) {
    menuControl = new Ext.Toolbar({
                    layout: 'menu',
                    items: menuitems
                    });
}
function ItemMouseOver(e) {
    var node;
    if (document.all)
        node = window.event.srcElement;
    else
        node = e.target;
    node.className += " over";
}
function ItemMouseOut(e) {
    var node;
    if (document.all)
        node = window.event.srcElement;
    else
        node = e.target;
    //node.className += " over";
    node.className = node.className.replace(" over", "");
}
if(typeof Wke == "undefined") Wke={};
if(typeof Wke.Presentation == "undefined") Wke.Presentation={};
if(typeof Wke.Presentation.WebControls == "undefined") Wke.Presentation.WebControls={};
Wke.Presentation.WebControls.AjaxControl_class = function() {};
Object.extend(Wke.Presentation.WebControls.AjaxControl_class.prototype, Object.extend(new AjaxPro.AjaxClass(), {
	AjaxControl_Click: function(target, method, jobject) {
		return this.invoke("AjaxControl_Click", {"target":target, "method":method, "jobject":jobject}, this.AjaxControl_Click.getArguments().slice(3));
	},
	url: '/ajaxpro/Wke.Presentation.WebControls.AjaxControl,Wke.Presentation.ashx'
}));
Wke.Presentation.WebControls.AjaxControl = new Wke.Presentation.WebControls.AjaxControl_class();


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

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

