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

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

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

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

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

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

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


