if (typeof MVD === 'undefined') {
	var MVD = {};
}

MVD.extend = function (base, ext) {
	for (var i in ext) if (ext.hasOwnProperty(i)) {
		// if (!base[i]) {
			base[i] = ext[i];
		// }
	}
};

MVD.nullFunc = function() { return this; };

/* Objeto con la funcionalidad a aplicar a cada element (DOM) */
MVD.elemExtension = {
	show: function() { this.style.display = ((this.nodeName == 'SPAN') || (this.nodeName == 'A') ) ? 'inline' : 'block'; return this; },
	hide: function() { this.style.display = 'none'; return this; },
	setHTML : function(txt) { this.innerHTML = txt; return this; },
	getWidth : function() {
		if(this.style.pixelWidth) {
			return this.style.pixelWidth;
		} else {
			return parseInt(this.style.width, 10);
		}
	},
	getHeight : function() {
		if(this.style.pixelHeight) {
			return this.style.pixelHeight;
		} else {
			return parseInt(this.style.height, 10);
		}
	},

	setTop : function(c) {
		if(this.style.pixelTop) {
			this.style.pixelTop = c;
		} else {
			this.style.top = c + 'px';
		}
		return this;
	},
	setLeft : function(c) {
		if(this.style.pixelLeft) {
			this.style.pixelLeft = c;
		} else {
			this.style.left = c + 'px';
		}
		return this;
	},
	setHeight : function(c) {
		if(this.style.pixelHeight) {
			this.style.pixelHeight = c;
		} else {
			this.style.height = c + 'px';
		}
		return this;
	},

	setWidth : function(c) {
		if(this.style.pixelWidth) {
			this.style.pixelWidth = c;
		} else {
			this.style.width = c + 'px';
		}
		return this;
	},
	/*
	e.getTop = function() {
		if(this.style.pixelTop) return this.style.pixelTop;
		else return parseInt(this.style.top, 10);
	}

	} */
	setOpacity : function(opacity) {
		opacity = (opacity >= 100) ? 99.99999 :opacity;
		this.style.filter = "alpha(opacity:"+opacity+")"; // IE/Win
		this.style.KHTMLOpacity = opacity/100; 	// Safari<1.2, Konqueror
		this.style.MozOpacity = opacity/100;  // Older Mozilla and Firefox
		this.style.opacity = opacity/100; // Safari 1.2, newer Firefox and Mozilla, CSS3
		return this;
	},

	fadeOut : function() {
		return this.hide();
	},

	// Muestra el elemento por time milisegundos y luego lo oculta.
	showAndHide : function(time) {
		if (!time) {
			time = 2000;
		}
		var that = this.show();
		var timer = setTimeout(function() { that.fadeOut(); }, time);
		return this;
	}
};

MVD.extend(MVD, {

	elemNull : { show : MVD.nullFunc, setHTML : MVD.nullFunc, hide: MVD.nullFunc },

	extendElement : function(el) {
		if(el) {
			MVD.extend(el, MVD.elemExtension);
		}
		return el;
	},

	get : function(id) {
		return MVD.extendElement(document.getElementById(id));
	},

	createElem : function (tagName) {
		return MVD.extendElement(document.createElement(tagName));
	},

	getSafe : function(id) {
		return MVD.get(id) || MVD.elemNull;
	},

	delCookie : function (name) {
	  var d = new Date();
	  d.setTime(d.getTime() - 1);
	  document.cookie=name + "=;expires=" + d.toGMTString();
	}

});

MVD.Form = function (id) {
	this.id = id;
	this.form = null;
	this.errors = [];
	this.errElem = null;
	return this;
};

MVD.extend(MVD.Form.prototype,
	{
		emailExp : /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/,

		init: function() {
			if(!this.form) {
				this.form = document[this.id];
			}
		},

		submit : function () {
			this.form.submit();
		},

		get : function(id) {
			return this.form[id].value;
		},

		getInput : function(id) {
			return this.form[id];
		},

		getFormElements: function() {
			var e = this.form.elements, f = {};
			for(var i=0;i<e.length;i++) {
				f[e[i].name] = e[i].value;
			}
			return f;
		},

		enable: function(val) {
			var e = this.form.elements;
			for(var i=0;i<e.length;i++) {
				if ((e[i].type === 'text') || (e[i].type === 'textarea')) {
					e[i].readOnly = !val;
				} else if (e[i].type === 'submit') {
					e[i].disabled = !val;
				}
			}
		},

		clear: function() {
			var e = this.form.elements;
			for(var i=0;i<e.length;i++) {
				e[i].value = '';
			}
		},

		checkNotEmpty : function(input, msg) {
			if(this.form[input].value.length === 0) {
				this.errors.push(msg);
				return false;
			}
			return true;
		},

		checkMail : function(input, name) {
			if(!this.form[input].value.match(this.emailExp)){
				var msg = 'La direcci&oacute;n de e-mail ' + (name ? name + ' ' : '') + 'no es v&aacute;lida';
				this.errors.push(msg);
				return false;
			}
			return true;
		},

		setErrorElem : function(id) {
			this.errElem = MVD.get(id);
		},

		showErrors : function(texto) {
			var el = this.errElem;
			if (el) {
				if (texto || this.errors.length > 0) {
					el.setHTML('<ul><li>' + (texto ? texto : this.errors.join('</li><li>')) + '</li></ul>').show();
					// Demorar 5 segundos por cada error
					el.showAndHide(this.errors.length * 5000);
				} else {
					el.hide();
				}
			}
		},

		valid : function() {
			return (this.errors.length === 0);
		},

		clearErrors: function() {
			this.errors = [];
		}

	});

/*	Crear un menu desplegable. Base es el elemento de la página desde donde se va a colgar el menú.

	La función crea un "contenedor" del menu, en un nodo hermano del base, y dentro un div, con clase "menuCom", con el menú.
	Devuelve el contenedor.
	El base generalmente es un a, con una imagen adentro que debe tener definidos los atributos width y height.
*/
MVD.MenuDespl = function (base, className) {

	this.base = MVD.extendElement(base);

	// Crear contenedor del menú, en nodo hermano al base.
	this.menuCont = document.createElement('span');
	this.menuCont.style.position = 'absolute';
	base.parentNode.insertBefore(this.menuCont, base.nextSibling);

	// Crear nodo del menu
	var menuDiv = MVD.createElem('div');
	menuDiv.className = className;
	menuDiv.style.position = 'absolute';
	this.menuCont.appendChild(menuDiv);
	menuDiv.setLeft(-base.firstChild.width).setTop(base.firstChild.height);

	var that = this;

	menuDiv.onmouseout = function (ev) {
		if (!ev) {
			ev = event;
		}
		var rel;
		if (ev.relatedTarget) {
			rel = ev.relatedTarget;
		} else if (ev.toElement) {
			rel = ev.toElement;
		}
		if (rel != menuDiv && rel.parentNode != menuDiv) {
			that.close();
		}
	};

	// Si no entra al menu en 3 segundos, cerrarlo.
	var timeout = setTimeout(function() { that.close(); }, 3000);

	// Si entra el menú, desactivar cerramiento automático.
	menuDiv.onmouseover = function () {
		if (timeout) {
			clearTimeout(timeout);
		}
		timeout = null;
	};
};

MVD.extend(MVD.MenuDespl.prototype, {
	close : function () {
		this.base.menu = null;
		this.base.parentNode.removeChild(this.menuCont);

	},

	appendOption : function (texto, callback) {
		// Se espera que se aplique un display:block a estos <a> dentro del menu.
		var opc = document.createElement('a');
		opc.href = '#';
		opc.innerHTML = texto;
		opc.style.display = 'block';
		var menu = this;
		opc.onclick = function () {
			menu.close();
			callback();
			return false;
		};
		this.menuCont.firstChild.appendChild(opc);
	}
});

MVD.Tween = function (init) {

	MVD.extend(this, {
		/* public */
		from: 0,
		to: 1,
		time: 500,
		onFinish: null,
		update: function () { },
		onStart: null,
		mode: 0, // 0=normal, 1=pingpong

		/* private */
		steps: 1,
		step: 0,
		timer: null,
		isActive: function() {
			return (this.timer !== null);
		},
		fps: 30,
		stepFunction : null,
		transition: function(x) { return 1 - Math.cos(Math.PI*x/2); }
		// transition: function(x) { return x; },
		// transition: function(x) { return (Math.pow((2*x-1),3)+1)/2; },
	});

	MVD.extend(this, init);
	return this;
};

MVD.extend(MVD.Tween.prototype, {

		stepForward: function() {
			with(this) {
				if (step > (steps - 1)) {
					update(to);
					clearInterval(timer);
					timer = null;
					if(onFinish) onFinish();
				} else {
					step ++;
					update(from + (to - from)*transition(step/steps));
				}
			}
		},

		stepBackward: function() {
			with(this) {
				if (step <= 0) {
					update(from);
					clearInterval(timer);
					timer = null;
					if(onFinish) onFinish();
				} else {
					step --;
					update(from + (to - from)*transition(step/steps));
				}
			}
		},

		programTimer: function() {
			var ref = this;
			this.timer = setInterval(function () { ref.stepFunction(); } , this.time/this.steps);
		},


		/* Public */
		start: function() {
			if (this.timer === null) {
				with(this) {
					stepFunction = stepForward;
					if(onStart) onStart();
					steps = Math.round((fps*time) / 1000);
					step = 0;
					update(from);
					programTimer();
				}
			} else {
				this.stepFunction = this.stepForward;
			}
		},

		rewind: function() {
			if (this.timer==null) {
				with(this) {
					this.stepFunction = this.stepBackward;
					if(onStart) onStart();
					steps = Math.round((fps*time) / 1000);
					step = steps;
					update(to);
					programTimer();
				}
			} else {
				this.stepFunction = this.stepBackward;
			}
		},

		stop: function() {
			if (this.timer) {
				clearInterval(this.timer);
				this.timer = null;
			}
		}

	});

if (MVD.elemExtension) {
	MVD.elemExtension.fadeOut = function(time) {
		var that = this;
		if (!time) {
			time = 500;
		}
		var t = new MVD.Tween({	from: 100, to: 0,
							time: time,
							update: function(x) {
								that.setOpacity(x);
							},
							onFinish: function() {
								that.hide();
								that.setOpacity(100);
							}
						});
		t.start();
	};
}
MVD.Window = function () {
    var vw, vh, sx, sy;
    
    function isNumber(n) {
        return (typeof(n) === 'number');
    }
    
    if (isNumber(window.innerHeight)) {
        vw = function () { return document.body.clientWidth; };
        vh = function () { return window.innerHeight; };
    } else if( document.documentElement && (document.documentElement.clientWidth > 0) ) {
        vw = function () { return document.documentElement.clientWidth; };
        vh = function () { return document.documentElement.clientHeight; };
    } else if (document.body && isNumber(document.body.clientWidth)) {
        vw = function () { return document.body.clientWidth; };
        vh = function () { return document.body.clientHeight; };
    } else {
        vw = function () { return 0; };
        vh = vw;
    }
    
    if (isNumber(window.pageYOffset)) {
        sy = function () { return window.pageYOffset; };
        sx = function () { return window.pageXOffset; };
    } else if( document.body && isNumber(document.body.scrollLeft) && document.documentElement && isNumber(document.documentElement.scrollLeft)) {
        sy = function () { return document.body.scrollTop || document.documentElement.scrollTop; };
        sx = function () { return document.body.scrollLeft || document.documentElement.scrollLeft; };
    } else if( document.body && isNumber(document.body.scrollLeft)) {
        sy = function () { return document.body.scrollTop; };
        sx = function () { return document.body.scrollLeft; };
    } else if( document.documentElement && isNumber(document.documentElement.scrollLeft)) {
        sy = function () { return document.documentElement.scrollTop; };
        sx = function () { return document.documentElement.scrollLeft; };
    } else {
        sy = function () { return 0; };
        sx = sy;
    }
    
    return {
        getViewHeight: vh,
        getViewWidth: vw,
        getScrollX : sx,
        getScrollY : sy
    };
} ();

MVD.getComputedStyle = function (el, name, nameCC) {
		var val;
		if (!nameCC) {
			nameCC = name;
		}
		if (el.currentStyle) {
			val = el.currentStyle[nameCC];
			if ( !/^\d+(px)?$/i.test(val) && /^\d/.test(val) ) {
				var style = el.style.left;
				var runtimeStyle = el.runtimeStyle.left;
				el.runtimeStyle.left = el.currentStyle.left;
				el.style.left = val || 0;
				val = el.style.pixelLeft + "px";
				el.style.left = style;
				el.runtimeStyle.left = runtimeStyle;
			}

		} else if (document.defaultView && document.defaultView.getComputedStyle) {
			val = document.defaultView.getComputedStyle(el, null).getPropertyValue(name);
		}
		return val;
};


MVD.Dialog = function (className) {
	this.title = null;
	this.el = null;
	this.content = null;
	this.className = className;
	this.blocker = null;
	this.buttons = null;
	return this;
};

MVD.extend(MVD.Dialog.prototype, {

	block : function () {
		var div = MVD.createElem('div');
		div.style.position = 'absolute';
		div.style.background = 'black';
		// div.hide();
		div.setOpacity(0);
		this.blocker = div;
		document.body.appendChild(div);
	},

	setTitle : function (title) {
		if (!this.title) {
			this.title = MVD.createElem('div');
			this.title.className = 'DialogTitle';
			this.el.insertBefore(this.title, this.content);
		}
		this.title.setHTML(title);
		this.reposition();
	},

	open : function () {
		this.block();

		// Crear dialogo
		var dialog = MVD.createElem('div');
		dialog.className = this.className;
		dialog.hide();
		dialog.style.position = 'absolute';
		document.body.appendChild(dialog);

		// Crear contenido
		var content = MVD.createElem('div');
		content.className = 'DialogContent';
		dialog.appendChild(content);

		this.el = dialog;
		this.content = content;
	},

	close : function () {
		var that = this;
		this.tween.onFinish = function () {
			document.body.removeChild(that.blocker);
			that.blocker = null;
		};
		this.tween.rewind();

		document.body.removeChild(this.el);
		this.content = null;
		this.el = null;
		this.buttons = null;
		window.onresize = null;
		window.onscroll = null;
	},

	setContent : function (cont) {
		this.content.setHTML(cont);
		this.reposition();
	},

	setSize : function (width, height) {
		this.el.setWidth(width).setHeight(height);
	},

	getWidth : function () {
		var v = this.el.getWidth();
		if(!v) {
			v = parseInt(MVD.getComputedStyle(this.el, 'width'), 10);
			if(!v) {
				v = this.el.offsetWidth;
			}
		}
		return v;
	},

	getHeight : function () {
		var v = this.el.getHeight();
		if (!v) {
			v = parseInt(MVD.getComputedStyle(this.el, 'height'), 10);
			if(!v) {
				v = this.el.offsetHeight;
			}
		}
		return v;
	},

	/* Reposiciona el dialogo y el bloqueo de pantalla */
	reposition : function () {
        var sy = MVD.Window.getScrollY(), vh = MVD.Window.getViewHeight();
        var sx = MVD.Window.getScrollX(), vw = MVD.Window.getViewWidth();
        
		var y = sy + ((vh - this.getHeight())/2);
		var x = sx + ((vw - this.getWidth())/2);
		this.el.setTop(y).setLeft(x);

		this.blocker.setWidth(vw).setHeight(vh);
		this.blocker.setTop(sy).setLeft(sx);
	},

	show : function (cont) {
		var blocker = this.blocker;

		this.tween = new MVD.Tween({
			to: 30,
			time: 100,
			update : function(x) { blocker.setOpacity(x); }
		});
		this.tween.start();
		// this.blocker.show();
		this.el.show();
		/*
		var w = parseInt(MVD.getComputedStyle(this.el, 'width'), 10);
		var h = parseInt(MVD.getComputedStyle(this.el, 'height'), 10);
		console.log(w, h);
		console.log(this.el);
		if (h < 100) {
			this.el.setHeight(100);
		}
		if (w < 60) {
			this.el.setWidth(60);
		}
		*/
		this.reposition();

		var that = this;
		var reposition = function() {
			that.reposition();
		};
		window.onresize = reposition;
		window.onscroll = reposition;
	},


	appendButton : function(text) {
		if (!this.buttons) {
			this.buttons = MVD.createElem('div');
			this.buttons.className = 'DialogButtons';
			this.el.appendChild(this.buttons);
		}

		var btn = MVD.createElem('a');
		btn.className = 'btn';
		btn.setHTML(text);

		this.buttons.appendChild(btn);
		this.reposition();
		return btn;
	},

	appendClickButton : function(text, action) {
		var btn = this.appendButton(text);

		btn.href = '#';
		btn.onclick = function() {
			action();
			return false;
		};


	},

	appendLinkButton : function(text, link, target) {
		var btn = this.appendButton(text);
		btn.href = link;
		// btn.target = target;

		var that = this;
		btn.onclick = function() {
			that.close();
			return true;
		};
	},

	appendCloseButton : function () {
		var that = this;
		this.appendClickButton("Cerrar", function () { that.close(); });
	},

	appendAcceptButton : function () {
		var that = this;
		this.appendClickButton("Aceptar", function () {
			if (that.onAccept) {
				that.onAccept();
			}
			that.close();
		});
	}

});

MVD.DialogMsg = function (msg, className) {
	this.el = null;
	this.content = null;
	this.className = className;
	this.blocker = null;
	this.buttons = null;
	this.open();
	this.setContent(msg);
	this.appendCloseButton();
	this.show();
	
	return this;
};
MVD.DialogMsg.prototype = MVD.Dialog.prototype;

if (typeof MVD.CMS === 'undefined') {
	MVD.CMS = {};
}

MVD.CMS.HelpDialog = function () {
	var url;
	var dialog = new MVD.Dialog("MyDialog");

	return {
		show : function () {
			if (url) {
				dialog.open();
				dialog.setContent('Cargando');
				dialog.appendCloseButton();
				dialog.show();
				MVD.Ajax.get(
					url,
					function(html) { dialog.setContent(html); },
					function() { dialog.setContent('Lamentablemente la ayuda no est&aacute; disponible.'); }
				);
			}
		},
		setUrl : function(u) {
			url = u;
		}
	};
} ();


// Muestra un Dialogo que indica al usuario que debe loguearse
MVD.CMS.LoginDialog = function() {

	var link;
	var dialog = new MVD.Dialog("MyDialog");

	return {
		show : function (text) {
			texto = text;
			dialog.open();
			dialog.setContent(text);
			if (link) {
				dialog.appendLinkButton('Iniciar', link, '_blank');
			}
			dialog.appendCloseButton();
			dialog.show();
		},
		setLink : function (l) {
			link = l;
		}
	};
} ();


MVD.CMS.MyConfigDialog = function (desbloquearCallBack) {
	this.el = null;
	this.content = null;
	this.className = "MyDialog";

	var that = this;

	// Funcion llamada cuando el usuario pulsa sobre "Aceptar" en el dialogo
	var desbloquear = function () {
		var l = this.content.getElementsByTagName("input");
		var inp;
		for (var i=0;i<l.length;i++) {
			inp = l[i];
			if (!inp.checked) {
				MVD.Ajax.postGX('ancomocultausrreg', { UsrRegId : inp.value, Action: 'D' }, desbloquearCallBack);
			}
		}
	};

	// Crea el contenido de "Mi configuracion"
	var miConfigCont = function (txt) {
		var s;
		var data;
		eval('data = ' + txt);

		var cant = 0;

		if (data) {
			var res = data[0];
			if (res == -1) {
				that.close();
				MVD.CMS.LoginDialog.show('Debe iniciar la sesi&oacute;n para editar su configuraci&oacute;n.');
			} else {
				var usr = data[1];
				cant = usr.length;
				
				if (cant > 0) {
					s = '<div style="margin: 4px; width: 140px;' + (cant > 10 ? "height: 190px; overflow: auto;" : "") + '">';
					s += '<ul>';
					for(var i=0;i<cant;i++) {
						s += '<li><input value="' + usr[i].id + '" type="checkbox" checked>' + usr[i].nick + '</li>';
					}
					s += '</ul>';
					that.appendAcceptButton();
					that.onAccept = desbloquear;
					that.setTitle('Usuarios ocultos:');
					s += '</div>';
				} else {
					s = 'No hay usuarios ocultos.';
				}
				that.appendCloseButton();
				that.setContent(s);
			}
		}

	};

	var miConfigError = function () {
		that.setContent('Se produjo un error, vuelva a intentarlo m&aacute;s tarde.<br>Gracias.');
		that.appendCloseButton();
	};

	this.load = function () {
		this.open();
		this.setContent('Cargando...');
		// this.setSize(400,200);
		this.show();
		MVD.Ajax.getGX('ancomgetusrregocultos','', miConfigCont, miConfigError);
	};

	return this;
};

MVD.CMS.MyConfigDialog.prototype = MVD.Dialog.prototype;




MVD.CMS.ComPag = function () {
	var NNotId;
	var elem_lista;
	var elem_paginado1, elem_paginado2;
	var elem_nuevos;
	var elem_com;

	// html con "Plantilla" para un comentario (Visible u Oculto).
	var strComVisible, strComOculto;
	// html con separador entre comentarios.
	var strSep = '';

	// Atributos del objeto "comentario" y el correspondiente tag para ser reemplazado en strCom.
	var reTags = { nick:/%%NNotComUsrRegNick%%/g, date:/%%NNotComFechaHora%%/g, txt:/%%NNotComTexto%%/g, id:/%%NNotComId%%/g, usr:/%%NNotComUsrRegId%%/g };
	var elemsPag = { NNotCantCom: 'cantComs', com_nro_pag1: 'nroPag', com_nro_pag2: 'nroPag', com_cant_pag1:'cantPag', com_cant_pag2:'cantPag' };
	var enabled;
	var cantComs, pagAct, cantPag;
	var comsActuales;

	var timer = 0;
	var timProg = 0;
	var imgProgreso = new Image();
	var currPageClass = '';
	var primPag = true;
	var bot;
	var menuDiv;
	var menuTxt = { hide:'Ocultar comentarios de este usuario', conf:'Mi configuraci&oacute;n', show:'Mostrar comentarios de este usuario', showThis: 'Mostrar este comentario', help: 'Ayuda' };
	var dialogTxt = { errSesionHide: 'Debe iniciar la sesi&oacute;n para ocultar o mostrar usuarios.' };

	var genHTMLComentarios; // función, definida + adelante;
	var getPagina;
	var getPrimeraPagina;
	var getUsersHidden;
	var programarMenus;


	var getStrCom = function() {
		var strCom = elem_lista.innerHTML;
		elem_lista.innerHTML = '';
		var reVisible = /%%ComentarioVisible_INI%%([\s\S]*)%%ComentarioVisible_FIN%%/g;

		var match = reVisible.exec(strCom);
		if (match) {
			strComVisible = match[1];
		} else {
			strComVisible = strCom;
			strComOculto = strCom;
			return;
		}

		var reOculto = /%%ComentarioOculto_INI%%([\s\S]*)%%ComentarioOculto_FIN%%/g;
		match = reOculto.exec(strCom);
		if (match) {
			strComOculto = match[1];
		} else {
			strComOculto = strComVisible;
		}
	};

	// Función que se ejecuta al responder el ajax que desoculta un usuario, invocado dentro del menu de configuración.
	var cambioBloqueadoCallBack = function (txt) {
		var data;
		eval('data = ' + txt);
		var res = parseInt(data[0], 10);
		if (res == -1) {
			MVD.CMS.LoginDialog.show(dialogTxt.errSesionHide);
		} else {
			var usrH = getUsersHidden(data[1]);
			genHTMLComentarios(comsActuales, usrH);
	 		programarMenus(comsActuales, usrH);
		}
	};

	var crearMenuComOculto = function (base, id, usr) {
		var menu = new MVD.MenuDespl(base, "menuCom");
		var opc;

		var comocu = MVD.get('comhidden' + id );
		if (comocu && comocu.style.display === 'none') {
			opc = menu.appendOption(menuTxt.showThis, function () {
				comocu.show();
			});
		}
		menu.appendOption(menuTxt.show, function () {
			MVD.Ajax.postGX('ancomocultausrreg', { UsrRegId : usr, Action: 'D' }, cambioBloqueadoCallBack);
		});

		menu.appendOption(menuTxt.conf, function () {
			var dial = new MVD.CMS.MyConfigDialog(cambioBloqueadoCallBack);
			dial.load();
		});

		menu.appendOption(menuTxt.help, MVD.CMS.HelpDialog.show);

		return menu;
	};

	var crearMenuComVisible = function (base, id, usr) {
		var menu = new MVD.MenuDespl(base, "menuCom");
		var opc;

		menu.appendOption(menuTxt.hide, function () {
			MVD.Ajax.postGX('ancomocultausrreg', { UsrRegId : usr, Action: 'B' }, cambioBloqueadoCallBack);
		});

		menu.appendOption(menuTxt.conf, function () {
			var dial = new MVD.CMS.MyConfigDialog(cambioBloqueadoCallBack);
			dial.load();
		});

		menu.appendOption(menuTxt.help, MVD.CMS.HelpDialog.show);

		return menu;
	};

	/* Prepara la página para los comentarios paginados.
			Obtiene la "plantilla" de comentarios.
			Obtiene los botones de navegación y los programa.
	*/
	var setup = function() {
		elem_lista = MVD.get('lista_comentarios');
		getStrCom();

		var sep = MVD.get('com_separador');
		if (sep) {
			strSep = sep.innerHTML;
			sep.innerHTML = '';
		}
		bot = { };
		var bn = ['pri1', 'pri2', 'ant1', 'ant2', 'sig1', 'sig2', 'ult1', 'ult2'];
		for (var i=0;i<bn.length;i++) {
			bot[bn[i]] = MVD.getSafe('com_pag_' + bn[i]);
		}

		bot.pri2.onclick = bot.pri1.onclick = function () {
			if (enabled && pagAct > 1) {
				getPagina(1);
			}
			return false;
		};

		bot.ant2.onclick = bot.ant1.onclick = function () {
			if (enabled && pagAct > 1) {
				getPagina(pagAct - 1);
			}
			return false;
		};
		bot.sig2.onclick = bot.sig1.onclick = function () {
			if (enabled && pagAct < cantPag) {
				getPagina(pagAct + 1);
			}
			return false;
		};
		bot.ult2.onclick = bot.ult1.onclick = function () {
			if (enabled && pagAct < cantPag) {
				getPagina(99999);
			}
			return false;
		};

		elem_paginado1 = MVD.getSafe('com_pag_pgs1');
		elem_paginado2 = MVD.getSafe('com_pag_pgs2');
		elem_com = MVD.get('com_noticia');
		// elem_nuevos = MVD.get('com_nuevos')
		getPrimeraPagina();
	};


	var armarPaginado = function () {

		/* Devuelve el html a incluir para un número de página.
			nro = número de página.
			ad = postfijo a agregar al número (ej. '...')
		*/
		var txt = function(nro, ad) {
			return '<a href="#" onclick="return MVD.CMS.ComPag.pag(' + nro + ')">' + nro + ad + '</a> ';
		};
		var tp = '';
		var decActual = Math.floor(pagAct/10) * 10;
		var i = decActual - 10;
		while((i >= (decActual - 50)) && (i >= 0)) {
			if (i === 0) {
				i = 1;
			}
			tp = txt(i, '..') + tp;
			i -= 10;
		}
		i = decActual;
		if (i === 0) {
			i = 1;
		}
		while ((i <= decActual + 9) && (i <= cantPag)) {
			if (i === pagAct) {
				if (currPageClass) {
					tp += '<span class="' + currPageClass + '">' + i + '</span> ';
				} else {
					tp += '[' + i + '] ';
				}
			} else {
				tp += txt(i, '');
			}
			i ++;
		}
		while ((i <= (decActual + 50)) && (i <= cantPag)) {
			tp += txt(i, '..');
			i += 10;
		}
		elem_paginado1.innerHTML = tp;
		elem_paginado2.innerHTML = tp;
	};


	var com2text = function(com, visible) {
		var txt = visible ? strComVisible : strComOculto;
		for(var i in reTags) if (reTags.hasOwnProperty(i)) {
			txt = txt.replace(reTags[i], com[i]);
		}
		return txt;
	};

	/* Dado un array a, devuelve un objeto h, donde h[a[i]] = true para todo i. */

	getUsersHidden = function (usersList) {
		var h = {};
		if (usersList) {
			for (var i=0;i<usersList.length;i++) {
				h[usersList[i]] = true;
			}
		}
		return h;
	};

	/**
	 * Genera el HTML con los comentarios.
	 * coms : lista de comentarios
	 * usrH : diccionario con usuarios ocultos. si usrH[usrId] = true entonces el usuario está oculto.
	 */
	genHTMLComentarios = function (coms, usrH) {
		// Generar el código html con los comentarios
		var comtxt = '';
		var visible;
		for(var i=0; i<coms.length; i++) {
			visible = !(usrH[coms[i].usr]);
			comtxt += ((i>0) ? strSep : '') + com2text(coms[i], visible);
		}
		elem_lista.innerHTML = comtxt; // mostrarlo
	};

	programarMenus = function (coms, usrH) {
		var visible, el;
		var id;

		var programarMenu = function (el, id, usr, visible) {
			el.onclick = function () {
				if (!this.menu) {
					this.menu = visible ? crearMenuComVisible(this, id, usr) : crearMenuComOculto(this, id, usr);
				}
				return false;
			};
		};

		for(var i=0; i<coms.length; i++) {
			visible = !(usrH[coms[i].usr]);
			el = MVD.get('menucom' + coms[i].id);
			if (el) {
				programarMenu(el, coms[i].id, coms[i].usr, visible);
			}
		}

	};

	var mostrarPaginado = function () {
		// Mostrar u ocultar botones según la cantidad de páginas y la página actual.
		if (cantPag > 1) {
			armarPaginado();
			if (pagAct <= 1) {
				bot.ant2.hide();
				bot.ant1.hide();
			} else {
				bot.ant2.show();
				bot.ant1.show();
			}
			if (pagAct == cantPag) {
				bot.sig2.hide();
				bot.sig1.hide();
			} else {
				bot.sig2.show();
				bot.sig1.show();
			}
			MVD.getSafe('com_pag2').show();
			MVD.getSafe('com_pag1').show();
		} else {
			MVD.getSafe('com_pag2').hide();
			MVD.getSafe('com_pag1').hide();
		}
	};

	/* Arma el contenido de la página actual apartir del texto con el objeto JSON.
	   El objeto tiene las siguientes propiedades:
		cantComs : Cantidad de comentarios
		nroPag : número de página actual
		cantPag : cantidad de páginas
		hidden : lista de ids de usuarios que se encuentran ocultos para el usuario actual.
		coms: Lista de comentarios (cada uno es un objeto)
	 */
	var setPagina = function(text) {

		// Desprogramar la visualización de la imagen de progreso
		if(timProg) {
			clearTimeout(timProg);
			timProg = 0;
		}
		var texta = text;
		text = text.replace(/\r/g, ' ');
		text = text.replace(/\n/g, ' ');
		
		var data, i;
		eval("data = " + text);

		if (data !== null) {
			// Obtener usuarios ocultos
			var usrH = getUsersHidden(data.hidden);

			// generar HTML com Comentarios
			genHTMLComentarios(data.coms, usrH);
			comsActuales = data.coms;

			programarMenus(data.coms, usrH);

			// Reemplazar las propiedades generales (cantComs, nroPag, etc) en el html de la página
			var el;
			for(i in elemsPag) if (elemsPag.hasOwnProperty(i)) {
				MVD.getSafe(i).innerHTML = data[elemsPag[i]];
			}

			pagAct = data.nroPag;
			cantPag = data.cantPag;
			cantComs = data.cantComs;

			mostrarPaginado();

			enabled = true;
			// Mostrar todo el bloque de comentarios.
			elem_com.show();
			// Si no es la primera página que se carga (la que se carga por defecto)
			// Mover la página hacia el comienzo del paginado.
			if (primPag) {
				primPag = false;
			} else {
				window.location.hash = 'com';
			}
		} else {
			// No hay comentarios? Ocultar todo el bloque.
			elem_com.hide();
		}
	};

	var showCenter = function(what) {
		var tmp = '<br><br><br><br><br>';
		tmp += tmp;
		elem_lista.innerHTML = tmp + '<center>' + what + '</center>' + tmp;
	};

	var showError = function() {
		if(timProg) {
			clearTimeout(timProg);
			timProg = 0;
		}
		showCenter('Ocurri&oacute; un error en el servidor, int&eacute;ntelo m&aacute;s tarde. Gracias.');
		enabled = true;
	};
	var showProgress = function() {
		showCenter('<img src="' + imgProgreso.src + '">');
		if(timProg) {
			clearTimeout(timProg);
			timProg = 0;
		}
	};

	getPagina = function(nro) {
		enabled = false;
		timProg = setTimeout(showProgress, 1000);
		MVD.Ajax.postGX('ancomgetpag', { uc: NNotId, pag: nro } , setPagina, showError);
	};

	getPrimeraPagina = function() {
		MVD.Ajax.postGX('ancomgetpag', { uc: NNotId, pag: 1 } ,
					   function(txt) {
							setPagina(txt);
							try {
								MVD.CMS.ComSend.autoForm();
							} catch(e) { }
					   });
	};

	/*
	var mostrarNuevos = function (newCant) {
		if (newCant > cantComs) {
			elem_nuevos.innerHTML = 'Hay comentarios nuevos. <a href="#" onclick="return MVD.CMS.Comentarios.pag(1)">Ver...</a>'
		} else {
			setTimerCheckNuevos();
		}
	}

	var checkNuevos = function() {
		MVD.Ajax.postGX('anget1notcantcoms', { uc: NNotId }, mostrarNuevos);
	}

	var setTimerCheckNuevos = function () {
		if (timer) {
			clearTimeout(timer);
			timer = null;
		}
		timer = setTimeout(checkNuevos, 30000);
	}*/

	return {
		init : function(notid) {
			NNotId = notid;
			setup();
            return this;
		},
		pag : function(nro) {
			if(enabled) {
				getPagina(nro);
			}
			return false;
		},
		setImgProgress: function(imgname) {
			imgProgreso.src = imgname;
            return this;
		},
		setCurrentPageClass: function(className) {
			currPageClass = className;
            return this;
		},
		getCantComs : function() {
			return cantComs;
		}

	};
}();

if (typeof MVD.CMS === 'undefined') {
	MVD.CMS = { };
}

MVD.CMS.ComSend = function () {
	var f;
	var NickValido = false;
	var AutoForm = false;
	var NNotId = 0;
    var BlogId = 0;
	var no_com, env_status, com_form;
	var timerMsg;
	var messages = { comSendMod : 'El comentario fue enviado, el equipo de contenido decidir&aacute; si el mismo ser&aacute; publicado o no. Gracias.',
					 comSend : 'El comentario fue enviado con &eacute;xito. El Administrador se reserva el derecho de publicaci&oacute;n.',
					 comSendError : 'Ocurri&oacute; un error al enviar su comentario. Int&eacute;ntelo nuevamente en unos minutos. Gracias.',
					 nickEmptyError : 'Debe ingresar un Nick.',
					 comEmptyError: 'El texto del comentario no puede estar vac&iacute;o.',
					 nickNotAvailable: 'Ese nick est&aacute; siendo utilizado por otro usuario.',
					 nickSendError : 'Hubo un error al actualizar su nick. Int&eacute;ntelo nuevamente en unos minutos. Gracias.',
					 userBlocked: 'No puede dejar m&aacute;s comentarios.',
					 checkSesionError: 'Ocurri&oacute; un error en el servidor, vuelva a intentarlo m&aacute;s tarde. Gracias.',
					 noLoginMsg : 'Debe iniciar la sesi&oacute;n para enviar comentarios.'
					 };
	var actualizarNick; // Función, se define + adelante.

	
	var showMsg = function(id, keep) {
		var text = (id in messages) ? messages[id] : id;
		no_com.setHTML(text);
		if (!keep) {
			no_com.showAndHide(10000);
		} else {
			no_com.show();
		}
	};

	var showEnviacom2 = function () {
		var cc = 0;
		try {
			cc = MVD.CMS.ComPag.getCantComs();
		} catch(e) { }
		if (cc > 8) {
			MVD.getSafe('enviacom2').show();
		}
	};

	var comRecibido = function (res) {
        if (res === '1') { 
            // Comentario publicado
            MVD.CMS.ComPag.pag(1);
			showMsg('comSend');
            if (BlogId) {
                MVD.Ajax.updateGX("ablogultimoscomentariosj1", BlogId, "blogUltimosComentarios");
            }
        } else if (res === '2') { 
            // Comentario no publicado (moderado)
            showMsg('comSendMod');
        } else { 
            // Error al procesar comentario
            showMsg('comSendError');        
        }    
		MVD.get('enviacom').show();
		showEnviacom2();
		f.enable(true);
		env_status.hide();
		com_form.hide();
		f.getInput('comentario').value = '';
	};

	var comError = function () {
		showMsg('comSendError');
		env_status.hide();
		f.enable(true);
	};

	var enviarComentario = function() {
		MVD.Ajax.postGX('anguardacomentario', { NNotId: NNotId, BlogId: BlogId, comentario:f.get('comentario'), redirect:'0' }, comRecibido, comError);
	};

	var validarComentario = function() {
		f.init();
		f.clearErrors();
		if (!NickValido) {
			f.checkNotEmpty('nick', messages.nickEmptyError);
		}
		f.checkNotEmpty('comentario', messages.comEmptyError);
		f.showErrors();

		if (f.valid()) {
			f.enable(false);
			env_status.show();
			if (!NickValido) {
				actualizarNick();
			} else {
				enviarComentario();
			}
		}
		return false;
	};

	var resultadoCambioNick = function (result) {
		switch(result) {
			case '0':
					NickValido = true;
			     	MVD.get('nick').hide();
					MVD.get('usrnick').setHTML(f.get('nick')).show();
					enviarComentario();
					break;
			case '4':
					f.showErrors(messages.nickNotAvailable);
					env_status.hide();
					f.enable(true);
					f.getInput('nick').focus();
					break;
			default:
					f.showErrors(messages.nickSendError);
					env_status.hide();
					f.enable(true);
					f.getInput('nick').focus();
					break;
		}
	};

	actualizarNick = function () {
		MVD.Ajax.postGX('anupdnick', {nick: f.get('nick')}, resultadoCambioNick);
	};

	var checkAutoForm = function() {
		return (document.cookie.indexOf("comautoform=1") != -1);
	};

	var clearAutoForm = function () {
		MVD.delCookie('comautoform');
	};

	var setAutoForm = function () {
		document.cookie="comautoform=1";
	};

	var showform = function (txt) {
		var info;
		eval(txt);
		window.location.hash = 'form_com';
	    switch(info[0]) {
	        case 1:
				showMsg('noLoginMsg', true);
				if (!AutoForm) {
					setAutoForm();
				}
				AutoForm = false;
				break;
	        case 2:
				showMsg('userBlocked', true);
	          	break;
			case 4:
				showMsg(info[1]);
				break;
			case 3:
	        case 0:
				if (info[1]) {
					MVD.get('nick').hide();
					MVD.get('usrnick').setHTML(info[1]);
					NickValido = true;
				} else {
					MVD.get('usrnick').hide();
				}
				MVD.get('usrmail').setHTML(info[2]);
				com_form.show();
				window.location.hash = 'form_com';
				if (NickValido) {
					f.getInput('comentario').focus();
				} else {
					f.getInput('nick').focus();
				}
	            break;
		}

	};

	var comCheck = function () {

		MVD.get('enviacom').hide();
		MVD.getSafe('enviacom2').hide();

		MVD.Ajax.getGX('anusrregcom', NNotId,
			showform,
			function () {
				showMsg('checkSesionError');
				MVD.get('enviacom').show();
				showEnviacom2();
				});
		return false;
	};

	return {
		validar : validarComentario,

		init: function(id, blogId) {
			NNotId = id;
            BlogId = blogId || 0;
            if (BlogId) {
                messages.comSendMod = 'El comentario fue enviado, el propietario del blog decidir&aacute; si el mismo ser&aacute; publicado o no. Gracias.'
                messages.comSend = 'El comentario fue enviado con &eacute;xito';
            }
			no_com = MVD.get('no_com');
			env_status = MVD.get('env_status');
			com_form = MVD.get('com_form');
			MVD.get('enviacom').onclick = comCheck;
			MVD.getSafe('enviacom2').onclick = comCheck;
			f = new MVD.Form('MAINFORM');
			f.setErrorElem('blockerror');
			f.init();
			document.MAINFORM.onsubmit = validarComentario;
            return this;
		},

		autoForm: function () {
			if (checkAutoForm()) {
				AutoForm = true;
				clearAutoForm();
				comCheck();
			}
			showEnviacom2();
		},

		// No usar. Usar setMessage('noLoginMsg', txt)
		setNoLoginMsg: function (txt) {
			messages.noLoginMsg = txt;
            return this;
		},

		setMessage: function (id, txt) {
			messages[id] = txt;
            return this;
		}
	};
} ();
