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.extend(Array.prototype, {
    contains : function (e) {
        for (var i=0,l=this.length; i<l; i++) {
			if (this[i] === e) 
				return true;
		}
        return false;
    },    
    filter : function (f) {
        var r = [];
        for (var i=0,l=this.length; i<l; i++) {
			if (f(this[i])) {
                r.push[this[i]];
            }				
		}    
        return r;
    },
    
    foreach : function (f) {
        for (var i=0,l=this.length; i<l; i++) {
			f(i, this[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;
	},
    
    hasClass : function(name) {
        return this.className.split(" ").contains(name);		
	},
      
    childWithClass : function (name) {
        if (0 && this.getElementsByClassName) {
            console.log(this, name);
            console.log(this.getElementsByClassName(name));
            return this.getElementsByClassName(name);          
        } else {
            return MVD.filter(this.getElementsByTagName("*"), 
                function (n) {                    
                    return n.className && n.className.split(" ").contains(name);
                });
        }
    },
    
    firstWithClass : function (name) {
        if (this.getElementsByClassName) {
            var r = this.getElementsByClassName(name);
            if (r.length) {
                return MVD.extendElement(r[0]);
            }                               
        } else {
            var desc = this.getElementsByTagName("*");
            var n;
            for (var i=0,l=desc.length; i<l; i++) {
                n = desc[i];                
                if (n.className && n.className.split(" ").contains(name)) {
                    return MVD.extendElement(n);
                }				
            }                
        }
        return null;
    },
    
    allWithClass : function (name) {
        if (this.getElementsByClassName) {
            return this.getElementsByClassName(name);
        } else {
            var desc = this.getElementsByTagName("*"), res = [], n;            
            for (var i=0,l=desc.length; i<l; i++) {
                n = desc[i];                
                if (n.className && n.className.split(" ").contains(name)) {
                    res.push(MVD.extendElement(n));
                }				
            }
            return res;
        }
        return null;
    }
};

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;
	},
    
    // Agrega un aviso (mensaje) depues del elemento id.
    addNotice : function (parent, id_notice, msg, className) {
        var el = typeof parent === "string" ? MVD.get(parent) : parent;
        var d = null;
        if (el && !MVD.get(id_notice)) {
            d = MVD.createElem("span");
            d.id = id_notice;
            d.hide();
            d.style.position = 'absolute';
            d.className = className;
            d.setHTML(msg);
            el.parentNode.insertBefore(d, el.nextSibling);                                  
        } 
        return d;
    },
    
    filter : function (f) {
        var r = [];
        for (var i=0,l=this.length; i<l; i++) {
			if (f(this[i])) {
                r.push[this[i]];
            }				
		}    
        return r;
    }, 
    
    getSelectValue : function(id) {
        var sel = (typeof id === "string") ? MVD.get(id) : id;
        return sel.options && sel.options[sel.selectedIndex].value;
    }
});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;
};
if (typeof MVD === 'undefined') {
	MVD = {};
}

if (!MVD.Ajax) {
    MVD.Ajax = function() {
    	var getXMLHttpObject = function () {
    		var ret = false;
    	    if (window.XMLHttpRequest) {
    	        ret = new XMLHttpRequest ();
    			if(ret.readyState === null){
    					ret.readyState = 1;
    					ret.addEventListener('load', function(){
    						ret.readyState = 4;
    						if( typeof (ret.onreadystatechange) === 'function') {
    							ret.onreadystatechange();
    						}
    					}, false);
    			}
    	    } else if (window.ActiveXObject) {
    	        try { ret = new ActiveXObject ("Msxml2.XMLHTTP"); }
    	        catch (e)
    	        { try { ret = new ActiveXObject ("Microsoft.XMLHTTP"); }
    	          catch (e2) { }
    	        }
    	    }
    	    return ret;
    	};
    	
    	var prefix = '';
    	var ext = '.aspx';

    	var encode = encodeURIComponent;
    	
    	var newXmlHttp = function (onComplete, onError) {
    		var xmlHttp = getXMLHttpObject();
    		if (xmlHttp) {
    			xmlHttp.onreadystatechange = function () {
    				if (xmlHttp.readyState == 4 || xmlHttp.readyState=="complete") {
    					var res_status = 0;
    					try {
    						res_status = xmlHttp.status;
    					} catch(e) {}
    					if ((res_status >= 200) && (res_status < 300)) {
    						if(onComplete) {
    							onComplete(xmlHttp.responseText);
    						}
    					} else {
    						if(onError) {
    							onError(xmlHttp.responseText);
    						}
    					}
    				}
                };
    		}
    		return xmlHttp;
    	};

    	var doGet = function (url, onComplete, onError) {		
    		var xmlHttp = newXmlHttp(onComplete, onError);
    		if (xmlHttp) {				
    			xmlHttp.open ('GET', url, true);											
    			// Evitar cache en IE
    			xmlHttp.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" );
    			xmlHttp.send (null);
    		}
    	};

    	var doPost = function(url, parms, onComplete, onError ) {
    		var xmlHttp = newXmlHttp(onComplete, onError);
    		if (xmlHttp) {			
    			xmlHttp.open ('POST', url, true);
    			xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    			var qstr = '';
    			for (var parm in parms) if (parms.hasOwnProperty(parm)) {
    				if (qstr) {
    					qstr += '&';
    				}
    				qstr += parm + '=' + encode(parms[parm]);
    			}
    			xmlHttp.send (qstr);
    		}
    	};

    	return {
    			
    			get: doGet,
    			getGX : function (url, params, onComplete, onError) {
    				doGet(prefix + url + ext + '?' + params, onComplete, onError);
    			},

                updateGX : function (url, param, elemId) {
                    var e = document.getElementById(elemId);
                    if (e) {
                        this.getGX(url, param, function (c) { e.innerHTML = c; });                  
                    }
                },
                
    			post: doPost,			
    			postGX : function (url, params, onComplete, onError) {
    				doPost(prefix + url + ext, params, onComplete, onError);
    			},
    			
    			setEncode: function(enc) {
    				encode = (enc == 'UTF8') ? encodeURIComponent : escape;
    				return this;
    			},
    			setPrefix : function(p) {
    				prefix = p;
    				return this;
    			},
    			setExt : function(e) {
    				ext = e;
    				return this;
    			}			
    		};
    }();

    // Backcompatibility
    var jxcll = MVD.Ajax.get;
    var jxcllPost = MVD.Ajax.post;
}
MVD.EventManager = function () {
    this.events = {};
}

MVD.extend(MVD.EventManager.prototype, {
    addEventListener: function (type, listener) {
        var e = this.events;
        if (e[type]) {
            e[type].push(listener);
        } else {
            e[type] = [ listener ];
        }
    },
    
    dispatchEvent: function (type, context) {
        var e = this.events;
        if (e[type]) {
            for (var i=0,l=e[type].length;i<l;i++) {
                e[type][i](context);
            }
        }    
    }
});/*
    http://www.JSON.org/json_parse.js
    2008-09-18

    Public Domain.

    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

    This file creates a json_parse function.

        json_parse(text, reviver)
            This method parses a JSON text to produce an object or array.
            It can throw a SyntaxError exception.

            The optional reviver parameter is a function that can filter and
            transform the results. It receives each of the keys and values,
            and its return value is used instead of the original value.
            If it returns what it received, then the structure is not modified.
            If it returns undefined then the member is deleted.

            Example:

            // Parse the text. Values that look like ISO date strings will
            // be converted to Date objects.

            myData = json_parse(text, function (key, value) {
                var a;
                if (typeof value === 'string') {
                    a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
                    if (a) {
                        return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
                            +a[5], +a[6]));
                    }
                }
                return value;
            });

    This is a reference implementation. You are free to copy, modify, or
    redistribute.

    This code should be minified before deployment.
    See http://javascript.crockford.com/jsmin.html

    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.
*/

/*members "", "\"", "\/", "\\", at, b, call, charAt, f, fromCharCode,
    hasOwnProperty, message, n, name, push, r, t, text
*/

/*global json_parse */

json_parse = function () {

// This is a function that can parse a JSON text, producing a JavaScript
// data structure. It is a simple, recursive descent parser. It does not use
// eval or regular expressions, so it can be used as a model for implementing
// a JSON parser in other languages.

// We are defining the function inside of another function to avoid creating
// global variables.

    var at,     // The index of the current character
        ch,     // The current character
        escapee = {
            '"':  '"',
            '\\': '\\',
            '/':  '/',
            b:    '\b',
            f:    '\f',
            n:    '\n',
            r:    '\r',
            t:    '\t'
        },
        text,

        error = function (m) {

// Call error when something is wrong.

            throw {
                name:    'SyntaxError',
                message: m,
                at:      at,
                text:    text
            };
        },

        next = function (c) {

// If a c parameter is provided, verify that it matches the current character.

            if (c && c !== ch) {
                error("Expected '" + c + "' instead of '" + ch + "'");
            }

// Get the next character. When there are no more characters,
// return the empty string.

            ch = text.charAt(at);
            at += 1;
            return ch;
        },

        number = function () {

// Parse a number value.

            var number,
                string = '';

            if (ch === '-') {
                string = '-';
                next('-');
            }
            while (ch >= '0' && ch <= '9') {
                string += ch;
                next();
            }
            if (ch === '.') {
                string += '.';
                while (next() && ch >= '0' && ch <= '9') {
                    string += ch;
                }
            }
            if (ch === 'e' || ch === 'E') {
                string += ch;
                next();
                if (ch === '-' || ch === '+') {
                    string += ch;
                    next();
                }
                while (ch >= '0' && ch <= '9') {
                    string += ch;
                    next();
                }
            }
            number = +string;
            if (isNaN(number)) {
                error("Bad number");
            } else {
                return number;
            }
        },

        string = function () {

// Parse a string value.

            var hex,
                i,
                string = '',
                uffff;

// When parsing for string values, we must look for " and \ characters.

            if (ch === '"') {
                while (next()) {
                    if (ch === '"') {
                        next();
                        return string;
                    } else if (ch === '\\') {
                        next();
                        if (ch === 'u') {
                            uffff = 0;
                            for (i = 0; i < 4; i += 1) {
                                hex = parseInt(next(), 16);
                                if (!isFinite(hex)) {
                                    break;
                                }
                                uffff = uffff * 16 + hex;
                            }
                            string += String.fromCharCode(uffff);
                        } else if (typeof escapee[ch] === 'string') {
                            string += escapee[ch];
                        } else {
                            break;
                        }
                    } else {
                        string += ch;
                    }
                }
            }
            error("Bad string");
        },

        white = function () {

// Skip whitespace.

            while (ch && ch <= ' ') {
                next();
            }
        },

        word = function () {

// true, false, or null.

            switch (ch) {
            case 't':
                next('t');
                next('r');
                next('u');
                next('e');
                return true;
            case 'f':
                next('f');
                next('a');
                next('l');
                next('s');
                next('e');
                return false;
            case 'n':
                next('n');
                next('u');
                next('l');
                next('l');
                return null;
            }
            error("Unexpected '" + ch + "'");
        },

        value,  // Place holder for the value function.

        array = function () {

// Parse an array value.

            var array = [];

            if (ch === '[') {
                next('[');
                white();
                if (ch === ']') {
                    next(']');
                    return array;   // empty array
                }
                while (ch) {
                    array.push(value());
                    white();
                    if (ch === ']') {
                        next(']');
                        return array;
                    }
                    next(',');
                    white();
                }
            }
            error("Bad array");
        },

        object = function () {

// Parse an object value.

            var key,
                object = {};

            if (ch === '{') {
                next('{');
                white();
                if (ch === '}') {
                    next('}');
                    return object;   // empty object
                }
                while (ch) {
                    key = string();
                    white();
                    next(':');
                    if (Object.hasOwnProperty.call(object, key)) {
                        error('Duplicate key "' + key + '"');
                    }
                    object[key] = value();
                    white();
                    if (ch === '}') {
                        next('}');
                        return object;
                    }
                    next(',');
                    white();
                }
            }
            error("Bad object");
        };

    value = function () {

// Parse a JSON value. It could be an object, an array, a string, a number,
// or a word.

        white();
        switch (ch) {
        case '{':
            return object();
        case '[':
            return array();
        case '"':
            return string();
        case '-':
            return number();
        default:
            return ch >= '0' && ch <= '9' ? number() : word();
        }
    };

// Return the json_parse function. It will have access to all of the above
// functions and variables.

    return function (source, reviver) {
        var result;

        text = source;
        at = 0;
        ch = ' ';
        result = value();
        white();
        if (ch) {
            error("Syntax error");
        }

// If there is a reviver function, we recursively walk the new structure,
// passing each name/value pair to the reviver function for possible
// transformation, starting with a temporary root object that holds the result
// in an empty key. If there is not a reviver function, we simply return the
// result.

        return typeof reviver === 'function' ? function walk(holder, key) {
            var k, v, value = holder[key];
            if (value && typeof value === 'object') {
                for (k in value) {
                    if (Object.hasOwnProperty.call(value, k)) {
                        v = walk(value, k);
                        if (v !== undefined) {
                            value[k] = v;
                        } else {
                            delete value[k];
                        }
                    }
                }
            }
            return reviver.call(holder, key, value);
        }({'': result}, '') : result;
    };
}();MVD.Cookies = function() {
    function trim(str) {
        return (str || "").replace( /^\s+|\s+$/g, "" );
    }

    return {
        getAll : function() {            
            var c = {};
            if(document.cookie) {
                var nV, ls = document.cookie.split(";");                            
                for (var i=0,l=ls.length; i<l; i++) {
                    nV = ls[i].split("=");                
                    c[trim(nV[0])] = unescape(nV[1]);
                }
            }
            return c;
        },
        
        check : function (str) {
            return (document.cookie.indexOf(str) != -1);
        },
        
        get : function(name) {            
            return this.getAll()[trim(name)];        
        },
        
        del : function(name) {
            var d = new Date();
            d.setTime(d.getTime() - 1);
            document.cookie=name + "=;expires=" + d.toGMTString() + ";path=/";  
        },
        
        set : function(name, value) {
            var d = new Date(2100, 12, 31);
            document.cookie=name + "=" + escape(value) + ";expires=" + d.toGMTString() + ";path=/";  
        }
    }
} ();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}$/,
        numberExp : /^[0-9]+$/,

		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];
		},

        setValue : function(id, value) {
            this.getInput(id).value = value;
        },

        getSelectValue : function(id) {
            var sel = (typeof id === "string") ? this.getInput(id) : id;
            return sel.options && sel.options[sel.selectedIndex].value;
        },

        setSelectValue : function(id, val) {
            var sel = (typeof id === "string") ? this.getInput(id) : id;
            if (sel.options) {
                var i = sel.options.length - 1;
                while (i > 0) {
                    if (sel.options[i].value === val) {
                        sel.selectedIndex = i;
                        return true;
                    }
                    i --;
                }
            }
            return false;
        },

        // Setea las opciones del combo (id) con las opciones en opts (objeto).
        setSelectOptions : function(id, opts) {
            var opt, combo = (typeof id === "string") ? this.getInput(id) : id;
            combo.options.length = 0;
            for (var o in opts) if (opts.hasOwnProperty(o)) {
                opt = document.createElement("option");
                opt.setAttribute("value", o);
                opt.innerHTML = opts[o];
                combo.appendChild(opt);
            }
        },

        getSelectOptions : function(id) {
            var opts = {}, combo = (typeof id === "string") ? this.getInput(id) : id;
            var o = combo.options;
            for (var i=0,l=o.length;i<l;i++) {
                opts[o[i].value] = o[i].innerHTML;
            }
            return opts;
        },

		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;
		},

        checkNumber : function(input, msg) {
			if(!this.form[input].value.match(this.numberExp)){
				this.errors.push(msg);
				return false;
			}
			return true;
		},

        checkRegExp : function(input, regexp, msg) {
        	if(!this.form[input].value.match(regexp)){
				this.errors.push(msg);
				return false;
			}
			return true;
        },

        addError : function(msg) {
            this.errors.push(msg);
        },

		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 50 milesimas de segundo por cada caracter.
					el.showAndHide(this.errors.join('').length * 50);
				} 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);
    this.base.style.outline = 'none';

	// 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);

    // Agregar salto de línea
    var aux = base.cloneNode(true);
    aux.style.visibility = 'hidden';
    this.menuCont.appendChild(aux);
    if (MVD.getComputedStyle(aux, 'display') != 'block') {
        this.menuCont.appendChild(MVD.createElem('br'));
    }

	// Crear nodo del menu
	var menuDiv = MVD.createElem('div');
    this.menuDiv = menuDiv;

	menuDiv.className = className;
	// menuDiv.style.position = 'absolute';
	this.menuCont.appendChild(menuDiv);

    // var sizeRefElement = (parseInt(base.style.width, 10)) ? base : base.firstChild;
    // console.log(base.style.width, "choose=", sizeRefElement);
    /*
    var w = parseInt(MVD.getComputedStyle(sizeRefElement, 'width'), 10);
    var h = parseInt(MVD.getComputedStyle(sizeRefElement, 'height'), 10);

    menuDiv.setLeft(-w).setTop(h);
    */
	// menuDiv.setLeft(-base.firstChild.width).setTop(base.firstChild.height);

	var that = this;

	menuDiv.onmouseout = function (ev) {
		if (!ev) { var ev = window.event; }
		var tg = menuDiv;       
        var rel = (ev.relatedTarget || ev.toElement);
        while ((rel != tg) && (rel.nodeName != 'BODY')) {
            rel = rel.parentNode;            
        }
        if (rel != tg) {
           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;
	};
    this.base.menu = this;
};

MVD.extend(MVD.MenuDespl.prototype, {
	close : function () {
		this.base.menu = null;
		this.base.parentNode.removeChild(this.menuCont);
	},

    createOption : function (texto, callback) {
        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;
		};
        return opc;
    },

	appendOption : function (texto, callback) {
		// Se espera que se aplique un display:block a estos <a> dentro del menu.
		this.menuDiv.appendChild(this.createOption(texto, callback));
	},

    appendSeparation : function () {
        this.menuDiv.appendChild(document.createElement('hr'));
    },

    appendCheck : function (texto, defvalue, callback) {
        var opc = this.createOption(texto, callback);
        opc.className = "menuItemCheck" + (defvalue ? "On" : "Off");
        this.menuDiv.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.elemExtension.fadeIn = function(time) {
		var that = this;
		if (!time) {
			time = 500;
		}
		var t = new MVD.Tween({	from: 0, to: 100,
							time: time,
							update: function(x) {
								that.setOpacity(x);
							},
							onStart: function() {
                                that.setOpacity(0);
								that.show();								
							}                            
						});
		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.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.ComHidden = function () {
	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.' };
    
    // usrH : diccionario con usuarios ocultos. si usrH[usrId] = true entonces el usuario está oculto.
    var usrH;
   
	/* Dado un array a, devuelve un objeto h, donde h[a[i]] = true para todo i. */
	function listToObject(list) {
		var h = {};
		if (list) {
			for (var i=0;i<list.length;i++) {
				h[list[i]] = true;
			}
		}
		return h;
	}
    
	// Función que se ejecuta al responder el ajax que desoculta un usuario, invocado dentro del menu de configuración.
	function cambioBloqueadoCallBack(txt) {
		var data = json_parse(txt);				
		if (data[0] == -1) {
			MVD.CMS.LoginDialog.show(dialogTxt.errSesionHide);
		} else {
			usrH = listToObject(data[1]);
			MVD.CMS.ComPag.refreshPage();	 		
		}
	}

	function crearMenuComOculto(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;
	}

    function crearMenuComVisible(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;
	}
    
    function programarMenu(node, id, usr) {    
        var visible = !(usrH[usr]);
        var el;
        var l = node.allWithClass('btnMenuCom');
        for (var i=0;i<l.length;i++) {
            el = l[i];
            if (el) {
                el.onclick = function () {
                    if (!this.menu) {
                        (visible ? crearMenuComVisible : crearMenuComOculto)(this, id, usr);                                               
                    }
                    return false;
                }
           }
        }
	}
    
    return { setUsers: function (list) {
                usrH = listToObject(list);
             },                          
             isUserHidden: function (usrid) {
                return usrH[usrid];
             },
             programarMenu:programarMenu};
    
} ();

MVD.CMS.ComPag = function () {
    // Altura maxima de texto de comentario, en pixels.
    var MAX_COMMENT_HEIGHT = 60;

    // Id de la UC actual
	var NNotId;

    // DOMElement donde se guarda el html generado de los comentarios.
	var elem_lista;
	// var elem_nuevos;
    // DOMElement contenedor de todo el bloque comentarios: paginados, lista comentarios, etc. Si no hay comentarios ï¿½ste estï¿½ oculto.
    var elem_com;

    // DOMElement contenedor del bloque de comentarios, paginado y formularo. Si el usuario elige no ver comentarios Ã©ste se oculta.
    var elem_view;

	// html con "Plantilla" para un comentario (Visible u Oculto).
	var htmlComentarioVisible, htmlComentarioOculto;
	// 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 filterText = {
        'buenos':'que aportan (0 o mejor)',
        'inter': 'intermedios (-4 o mejor)',
        'mejores':'ordenados por calificaci&oacute;n',
        'todos':'todos',
        'no':'ninguno'
    };

    // Si esta habilitado o no el cambio de pagina.
	var enabled;

    // Numeros de los comentarios de la uc.
    var cantComs, pagAct, cantPag;
    // Comentarios de la pagina actual
	var comsActuales;

	var timer = 0;
	var timProg = 0;

    // Imagen "cargando" ajax
	var imgProgreso = new Image();
	var currPageClass = '';
	var primPag = true;

    // Arrays de Objetos con los DOMElement de los botones y etiquetas de cada paginado.
	var paginado = [];
    // OpciÃ³n para filtrar comentarios ("todos","buenos")
    var filterSelect = MVD.Cookies.get("filterSelect") || "inter";
    var reputationSelect = parseInt(MVD.Cookies.get("reputationSelect") || "0", 10);   
    
    var viewLowReputation = function () {
        return !reputationSelect;
    }

    var events = new MVD.EventManager();

    // Funciones definidads mas adelante
    /*
	var genHTMLComentarios;
	var getPagina;
	var getPrimeraPagina;
*/
    // Obtiene la plantilla para los comentarios
	function getStrCom() {
		var strCom = elem_lista.innerHTML;
		elem_lista.innerHTML = '';
		var reVisible = /%%ComentarioVisible_INI%%([\s\S]*)%%ComentarioVisible_FIN%%/g;

		var match = reVisible.exec(strCom);
		if (match) {
			htmlComentarioVisible = match[1];
		} else {
			htmlComentarioVisible = strCom;
			htmlComentarioOculto = strCom;
			return;
		}

		var reOculto = /%%ComentarioOculto_INI%%([\s\S]*)%%ComentarioOculto_FIN%%/g;
		match = reOculto.exec(strCom);
		if (match) {
			htmlComentarioOculto = match[1];
		} else {
			htmlComentarioOculto = htmlComentarioVisible;
		}
	};

	var armarPaginado = function () {

		/* Devuelve el html a incluir para un numero de pagina.
			nro = numero de pagina.
			ad = postfijo a agregar al numero (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;
		}
        return tp;
	};

    // Cambiar los ascii 173 (0xad) y 160 (0xa0) por un guion, ya que no son visibles en el html.
    var fixNickRegExp = /[\xad|\xa0]/g;

    var fixNick = function (nick) {
        return nick.replace(fixNickRegExp, "-");
    }

	function commentTohtml(com, aceptable, forceView) {
        var usrHidden = forceView || MVD.CMS.ComHidden.isUserHidden(com.usr);
		var html = (forceView || (!usrHidden && aceptable)) ? htmlComentarioVisible : htmlComentarioOculto;
		for(var i in reTags) if (reTags.hasOwnProperty(i)) {
			html = html.replace(reTags[i], ( i === "nick" ? fixNick(com[i]) : com[i]) );
		}
		return html;
	}

    function showHiddenComment(com) {
        var n = MVD.get("comment" + com.id)
        n.setHTML(commentTohtml(com, 1, 1));
        MVD.CMS.ComHidden.programarMenu(n, com.id, com.usr);
        MVD.CMS.ComCal.setup(n, com.id, com.pos, com.neg);
        setupComment(n, com);
    }

    function setupComment(node, com) {
        var view = node.firstWithClass("btnShowComment");
        if (view) {
            view.onclick = function () {
                showHiddenComment(com);
                return false;
            }
        }
        var showocu = node.firstWithClass("uoculto");
        if (showocu) {
            if (MVD.CMS.ComHidden.isUserHidden(com.usr)) {
                showocu.setHTML('(Comentarista Oculto)').show();
            } else {
                if (!com.vis && !viewLowReputation()) {
                    showocu.setHTML('<a href="http://www.montevideo.com.uy/hnnoticiaj1.aspx?87987" target="_blank">(Baja valoraci&oacute;n en el Portal)</a>').show();
                } else {
                    showocu.hide();
                }
            }
        }
    }

    var _removeWordRegExp = /^(.+)[ ,.;](.+)$/;
    function removeWord(text) {
        var match = _removeWordRegExp.exec(text);
        return match && match[1];
    }

    function fixCommentHeight(id, node) {
        var textnode = node.firstWithClass("commentText");
        var org;

        function getCurrentHeight() {
            return textnode.offsetHeight || parseInt(MVD.getComputedStyle(textnode, "height"), 10);
        }

        function getH(l) {
            var t,s;
            if (l < org.length) {
                s = removeWord(org.slice(0, l-1));
                t = s ? s + ' ...' : org;
            } else {
                t = org;
            }
            textnode.innerHTML = t;
            return getCurrentHeight();
        }

        function optimunHeight(i, t) {
            if (i == t) {
                return i;
            }
            if ((i+1) == t) {
                if (getH(t) < MAX_COMMENT_HEIGHT) {
                    return t;
                } else {
                    return i;
                }
            }
            var m = Math.floor((i + t) / 2);
            if (getH(m) < MAX_COMMENT_HEIGHT) {
                return optimunHeight(m, t);
            } else {
                return optimunHeight(i, m);
            }
        }

        if (textnode) {
            org = textnode.innerHTML;
            // No mostrar texto mientras se ajusta el alto.
            textnode.style.visibility = 'hidden';
            setTimeout(function () {
                var fullHeight = getCurrentHeight();
                if (fullHeight > MAX_COMMENT_HEIGHT) {
                    getH(optimunHeight(0, org.length));
                    var contractedHeight = getCurrentHeight();
                    var cont = node.firstWithClass("commentExpand");
                    if (cont) {
                        cont.show();
                        cont.onclick = function () {
                            // console.log("De", contractedHeight, "a", fullHeight);
                            cont.hide();
                            this.onclick = null;
                            textnode.setHeight(contractedHeight);
                            textnode.innerHTML = org;
                            (new MVD.Tween({
                                from: contractedHeight,
                                to: fullHeight,
                                update: function (h) {
                                    textnode.setHeight(h);
                                },
                                time: (fullHeight - contractedHeight) * 2
                            })).start();
                            return false;
                        };
                    }

                }
                // Mostrar texto una vez ajustado.
                textnode.style.visibility = 'visible';
            }, 10);
        }
    }

    /* FunciÃ³n que indica si un comentario es aceptable (true) o no (false)*/
    function isAcceptable(pos, neg) {
        var d = (pos - neg);
        return (filterSelect != 'inter') ? (d >= 0) : (d >= -4);
    }

    function getOrder() {
        return (filterSelect == 'mejores') ? 'C':'F'
    }

    /* Devuelve true si el usuario eligiÃ³ mostrar solo los buenos comentarios, false si hay que mostrar todos.
       Si no existe el combo, devuelve false. */
    function justGoodComments() {
        return (filterSelect != "todos") && (filterSelect != 'mejores');
        // return !(!filterSelect || (MVD.getSelectValue(filterSelect) == "todos"));
    }

	/**
	 * Genera el HTML con los comentarios.
	 */
	function genHTMLComentarios() {
		// Generar el codigo html con los comentarios
		var node, com;
        elem_lista.innerHTML = '';
        comsActuales.foreach(function(i,com) {
            node = MVD.createElem("div");
            node.setAttribute("id", "comment" + com.id);
            node.className = "comment"; // (i < (l-1)) ? "comment" : "lastcomment";
			node.setHTML(commentTohtml(com, (viewLowReputation() || com.vis) && (!justGoodComments() || isAcceptable(com.pos, com.neg))));
            setupComment(node, com);
            MVD.CMS.ComHidden.programarMenu(node, com.id, com.usr);
            MVD.CMS.ComCal.setup(node, com.id, com.pos, com.neg);
            elem_lista.appendChild(node);
            fixCommentHeight(com.id, node);
		});
	}

    function viewCommentsPage() {
        if (filterSelect != 'no') {
            genHTMLComentarios();
            elem_view.show();
        } else {
            elem_view.hide();
        }
    }

	function mostrarUnPaginado(p) {
		// Mostrar u ocultar botones segï¿½n la cantidad de pï¿½ginas y la pï¿½gina actual.
		if (cantPag > 1) {
            p.anterior[(pagAct <= 1) ? 'hide' : 'show']();
            p.siguiente[(pagAct == cantPag) ? 'hide' : 'show']();
            p.container.show();
		} else {
            p.container.hide();
		}
	}

    function mostrarPaginados() {
        var t = armarPaginado();
        paginado.foreach(function(i,e) {
            mostrarUnPaginado(e);
            e.paginas.setHTML(t);
        });
    }

    function ocultarPaginados() {
        paginado.foreach(function(i,e) {
            e.container.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;
        data = json_parse(text);
       

		if (data !== null) {
			// Guardar lista de usuarios ocultos
            MVD.CMS.ComHidden.setUsers(data.hidden);

            comsActuales = data.coms;
            pagAct = data.nroPag;
			cantPag = data.cantPag;
			cantComs = data.cantComs;

			// Reemplazar las propiedades generales (cantComs, nroPag, etc) en el html de la pagina

            var commentsPageCounter = MVD.getSafe("commentsPageCounter");
            for(i in elemsPag) if (elemsPag.hasOwnProperty(i)) {
    			MVD.getSafe(i).innerHTML = data[elemsPag[i]];
    		}

            if (cantPag > 1) {
                commentsPageCounter.show();
                mostrarPaginados();
            } else {
                commentsPageCounter.hide();
                ocultarPaginados();
            }

            // generar HTML com Comentarios
            viewCommentsPage();

			enabled = true;
			// Mostrar todo el bloque de comentarios.
			elem_com.show();
			// Si no es la primera pagina que se carga (la que se carga por defecto)
			// Mover la pagina 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;
		}
	};

	function getPagina(nro) {
		enabled = false;
		timProg = setTimeout(showProgress, 1000);
		MVD.Ajax.postGX('ancomgetpag', { uc: NNotId, pag: nro, order: getOrder() } , setPagina, showError);
	}

	function getPrimeraPagina() {
		MVD.Ajax.postGX('ancomgetpag', { uc: NNotId, pag: 1, order: getOrder() } ,
					   function(txt) {
							setPagina(txt);
                            events.dispatchEvent("onFirstLoad");
					   });
	}

	/*
	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);
	}*/

    function setupFilter() {
        var base = MVD.get('commentsFilter');
        if (base) {
            base.onclick = function () {
                var menu = new MVD.MenuDespl(base, "menuCom");
                for (var id in filterText) if (filterText.hasOwnProperty(id)) {
                    (function () {
                        var opc = id;
                        menu.appendOption(filterText[id], function () {
                            var order1 = getOrder();
                            filterSelect = opc;
                            MVD.Cookies.set("filterSelect", filterSelect);
                            base.setHTML(filterText[filterSelect]);
                            if (order1 != getOrder())
                                MVD.CMS.ComPag.pag(1);
                            else {
                                MVD.CMS.ComPag.refreshPage();
                            }
                        });
                    }) ();
                }
                menu.appendSeparation();
                menu.appendCheck("Ver cerrados los comentarios de usuarios con baja valoraci&oacute;n", reputationSelect, function () {
                    reputationSelect = !reputationSelect;
                    MVD.Cookies.set("reputationSelect", reputationSelect ? "1" : "0");
                    MVD.CMS.ComPag.refreshPage();
                });
                return false;
            }
            base.setHTML(filterText[filterSelect]);
        }

    }

    function setupPaginado(id_elem) {

        var container = MVD.get(id_elem);
        var p = { container : container };

        ['primero', 'anterior', 'siguiente', 'ultimo', 'paginas'].foreach(function (i, e) {
			p[e] = container.firstWithClass(e) || MVD.elemNull;
        });

        p.primero.onclick = function () {
			if (enabled && pagAct > 1) {
				getPagina(1);
			}
			return false;
		};

		p.anterior.onclick = function () {
            if (enabled && pagAct > 1) {
				getPagina(pagAct - 1);
			}
			return false;
		};
        p.siguiente.onclick = function () {
			if (enabled && pagAct < cantPag) {
				getPagina(pagAct + 1);
			}
			return false;
		};
		p.ultimo.onclick = function () {
			if (enabled && pagAct < cantPag) {
				getPagina(99999);
			}
			return false;
		};
        paginado.push(p);
    }


    /* Prepara la pagina para los comentarios paginados:
        * Obtiene la "plantilla" de comentarios.
		* Obtiene los botones de navegacion y los programa.
	*/
	function setup() {
		elem_lista = MVD.get('lista_comentarios');
		getStrCom();

		var sep = MVD.get('com_separador');
		if (sep) {
			strSep = sep.innerHTML;
			sep.innerHTML = '';
		}

        setupPaginado('com_pag1');
        setupPaginado('com_pag2');

		elem_com = MVD.get('commentsBlock');
		// elem_nuevos = MVD.get('com_nuevos')
        elem_view = MVD.get('commentsView');

        getPrimeraPagina();

        setupFilter();
	}

	return {
		init : function(notid) {
			NNotId = notid;
            MVD.CMS.ComCal.init(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;
		},
        refreshPage : function() {
            viewCommentsPage();
        },

        /* Registro de listeners para eventos.
         * Disponibles:
         *   onFirstLoad - lanzado una vez se carga la primera pÃ¡gina.
         */
        addEventListener : function (type, listener) {
            events.addEventListener(type, listener);
        },

 		updateCommentCalification: function(id, pos, neg) {
			var com;
			for (var i=0, l=comsActuales.length; i<l; i++) {
				com = comsActuales[i];
				if (com.id == id) {
					com.pos = pos;
					com.neg = neg;
					return;
				}
			};
		}
	};
}();

MVD.CMS.ComCal = function () {
    var NNotId;

    function showTotal(el, pos, neg) {
        var total = pos - neg;
        el.innerHTML = '' + total;               
        el.className = (total > 0) ? 'comment_pos' : (total <= -4) ? 'comment_neg' : 'comment_med';
    }
    
    function deshabilitar_calificacion(elpos, elneg) {
        elneg.className += ' btnCalDisabled';
        elpos.className += ' btnCalDisabled';
        elneg.onclick = elpos.onclick = function () { return false; };                
    }
    
    return {
        init : function (notid) {
            NNotId = notid;
        },
    
        setup : function (node, id, pos, neg) {
            var eltot = node.firstWithClass("caltot");
            if (!eltot) { return }
            
            showTotal(eltot, pos, neg);
            
            var elpos = node.firstWithClass("calpos");
            if (!elpos) { return }
            
            var elneg = node.firstWithClass("calneg");                                         
            
            function showCalError(res) {
                var texto;
                switch(res) {                
                case '2': texto = "Ya calificaste el comentario"; break;
                case '3': texto = "No puedes calificar tu propio comentario"; break;
                default:
                    texto = 'Hubo un error al procesar su calificaci&oacute;n. Int&eacute;ntelo m&aacute;s tarde'; break;
                }            
                var n = MVD.addNotice(eltot, "avicaltot" + id, texto, "calError");
                n.fadeIn();
                var t = setTimeout(function () { n.fadeOut(); }, 3000);
            }
                                    
            elpos.onclick = function () {
                deshabilitar_calificacion(elpos, elneg);
                MVD.Ajax.postGX('annotcomcal', 
                                { NNotId: NNotId, NNotComId: id, Cal: 1 }, 
                                function (res) { 
                                    if (res=='0') {
										MVD.CMS.ComPag.updateCommentCalification(id, pos + 1, neg);
                                        showTotal(eltot, pos + 1, neg);
                                    } else {
                                        showCalError(res);
                                    }
                                } );
                return false;
            }
            elneg.onclick = function () {
                deshabilitar_calificacion(elpos, elneg);
                MVD.Ajax.postGX('annotcomcal', 
                                { NNotId: NNotId, NNotComId: id, Cal: -1 }, 
                                function (res) { 
                                    if (res=='0') {
										MVD.CMS.ComPag.updateCommentCalification(id, pos, neg + 1);
                                        showTotal(eltot, pos, neg + 1);
                                    } else {
                                        showCalError(res);
                                    }
                                } );
                return false;
            }                          
        }          
    }
} ();

if (typeof MVD.CMS === 'undefined') {
	MVD.CMS = { };
}

MVD.CMS.ComSend = function () {
	var f;
	var nickValido = false;
    var docValido = false;
    var docRequired;
	var AutoForm = false;
	var NNotId = 0;
    var NICK_REGEXP = /^[0-9A-Za-z_]+$/;

    // BlogId actual, si no es pagina de blogs BlogId = 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.',
					 generalError: 'Ocurri&oacute; un error inesperado, vuelva a intentarlo m&aacute;s tarde. Gracias.',
					 noLoginMsg : 'Debe iniciar la sesi&oacute;n para enviar comentarios.',
                     docWarning: 'Incluir el d&iacute;gito verificador, sin punto ni guiones.<br>Nota: No podr&aacute;s cambiar tu c&eacute;dula despu&eacute;s de que la ingreses.',
                     nickFormatError: 'El nick solo puede tener letras, n&uacute;meros y gui&oacute;n bajo (_).',
                     docEmptyError: 'Debe ingresar su n&uacute;mero de documento.',
                     docFormatError: 'El documento solo debe tener n&uacute;meros',
                     docCountryError: 'Debe seleccionar el pa&iacute;s de su documento.',
                     docCIError: 'El n&uacute;mero de documento ingresado no corresponde a una c&eacute;dula de identidad v&aacute;lida.',
                     docConfirmError: 'Estimado usuario: para poder comentar debe enviar una constancia de domiclio (recibo, carnet social, mutualista, etc) a comentarios@montevideo.com.uy',
                     docDuplicatedError: 'Ya hay un usuario registrado con el mismo documento.',
                     tooManyDocErrors: 'Se excedi&oacute; la cantidad de errores permitidos en el ingreso de documento.',
                     mustUseOtherUserError: 'Ya hay otro usuario habilitado con el mismo documento para dejar 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(text.length * 50);
		} else {
			no_com.show();
		}
	};

    // Muestra el segundo cartel de cantidad de comentarios.
	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') }, comRecibido, comError);
	};

    function sendFormComentario() {
        if (!nickValido) {
            actualizarNick();
        } else {
            if (docRequired && !docValido) {
                actualizarDoc();
            } else {
                enviarComentario();
            }
        }
    }

    function enableFormEdit() {
        env_status.hide();
        if (docRequired && !docValido) {
           f.getInput('paisdoc').onchange();
        }
        f.enable(true);
    }

    function disableFormEdit() {
        f.enable(false);
        MVD.getSafe('paisnotice').hide();
        env_status.show();
    }

	var validarComentario = function() {
		f.init();
		f.clearErrors();
		if (!nickValido) {
			if (f.checkNotEmpty('nick', messages.nickEmptyError)) {
                f.checkRegExp('nick', NICK_REGEXP, messages.nickFormatError);
            }
		}
        if (docRequired && !docValido) {
            if (f.checkNotEmpty('doc', messages.docEmptyError)) {
                if(f.checkNumber('doc', messages.docFormatError)) {
                    if (parseInt(f.get('doc'),10)==0) {
                        f.addError(messages.docEmptyError);
                    }
                }
            }
            var val = f.getSelectValue('paisdoc');
            if ( !val || (val === '0') || (val == 'ND')) {
                f.addError(messages.docCountryError);
            }
        }
		f.checkNotEmpty('comentario', messages.comEmptyError);
		f.showErrors();

		if (f.valid()) {
            disableFormEdit();
            sendFormComentario();
		}
		return false;
	};

	var resultadoCambioNick = function (result) {
		switch(result) {
			case '0':
					nickValido = true;
			     	MVD.get('nick').hide();
					MVD.get('usrnick').setHTML(f.get('nick')).show();
					sendFormComentario();;
					break;
			case '4':
					f.showErrors(messages.nickNotAvailable);
                    enableFormEdit();
					f.getInput('nick').focus();
					break;
			default:
					f.showErrors(messages.nickSendError);
					enableFormEdit();
					f.getInput('nick').focus();
					break;
		}
	};

    function resultadoCambioDoc(json) {
        var res = json_parse(json);

        // console.log(res);
        switch(res.result) {
            case 0: // Operacion exitosa
                docValido = true;
                MVD.get('doc').hide();
                MVD.get('usrdoc').setHTML(f.get('doc')).show();
                MVD.get('paisdoc').hide();
                MVD.get('usrpaisdoc').setHTML(f.getSelectOptions('paisdoc')[f.getSelectValue('paisdoc')]).show();
                sendFormComentario();
                break;
            case 3: // Error al ingresar CI uruguaya
                f.showErrors(messages.docCIError);
                enableFormEdit();
                f.getInput('doc').focus();
                break;
            case 4: // NO PUEDE PARTICIPAR HASTA QUE MANDE MAIL A PRENSA.
                com_form.hide();
                showMsg('docConfirmError');
                break;
            case 6: // Muchos errores con la cedula
                com_form.hide();
                showMsg('tooManyDocErrors');
                break;
            case 7: // Tiene que participar con otro usuario
                com_form.hide();
                var err = messages.mustUseOtherUserError;
                showMsg(err.replace(/%%user%%/, res.usrmustuse));
                break;
            case 8: // Ya hay un usuario con el mismo doc
                f.showErrors(messages.docDuplicatedError);
                enableFormEdit();
                f.getInput('doc').focus();
                break;
            // 1: Datos incorrectos, 2: No existe el usuario,  5: SE LE CERRO LA SESIÓN
            default:
                com_form.hide();
                showMsg('generalError'); // Error genérico
                break;
        }
    }

	function actualizarNick() {
		MVD.Ajax.postGX('anupdnick', {nick: f.get('nick')}, resultadoCambioNick);
	}

    function actualizarDoc() {
        MVD.Ajax.postGX('anupddoc', {doc: f.get('doc'), paisdoc: f.get('paisdoc')}, resultadoCambioDoc);
    }

	var checkAutoForm = function() {
		return MVD.Cookies.check("comautoform=1");
	};

	var clearAutoForm = function () {
		MVD.Cookies.del('comautoform');
	};

	var setAutoForm = function () {
        MVD.Cookies.set('comautoform', '1');		
	};


    function noLogin() {
        showMsg('noLoginMsg', true);
        if (!AutoForm) {
            setAutoForm();
        }
        AutoForm = false;
    }

    // Configura el formulario de comentarios
    function setupCommentsForm (info) {

        // console.log("setupCommentsForm", info)
        // Mostrar mail
        MVD.get('usrmail').setHTML(info.mail);

        // tiene nick?
        if (info.nick && NICK_REGEXP.test(info.nick)) {
            MVD.get('nick').hide(); // Ocultar input
            MVD.get('usrnick').setHTML(info.nick); // mostrar nick
            nickValido = true;
        } else {
            f.setValue('nick', info.nick);
            MVD.get('usrnick').hide();
        }
        docRequired = info.docRequired;
        if (info.docRequired) {
            // tiene el documento validado?
            if (info.docValid) {
                MVD.get('doc').hide();
                MVD.get('usrdoc').setHTML(info.docNum);
                MVD.get('paisdoc').hide();
                MVD.get('usrpaisdoc').setHTML(info.docCtryName);
                docValido = true;
            } else {
                MVD.get('usrdoc').hide();
                f.setValue('doc', info.docNum);
                MVD.get('usrpaisdoc').hide();
                var combo = f.getInput('paisdoc');
                f.setSelectOptions(combo,info.ctryLst);
                f.setSelectValue(combo, info.docCtry || 'UY');  // Poner Uruguay por defecto

                var docnota = MVD.addNotice('paisdoc', 'paisnotice', messages.docWarning, 'avisoDocumentoComentarios');
                combo.onchange = function () {
                    if (f.getSelectValue(this) === 'UY') {
                        docnota.fadeIn();
                    } else {
                        docnota.fadeOut();
                    }
                    // docnota.style.display = (f.getSelectValue(this) === 'UY') ? 'inline':'none';
                }
                combo.onchange();
            }
        } else {
            // Ocultar filas doc y pais doc
            var trs = MVD.get('com_form').getElementsByTagName("table")[0].getElementsByTagName("tr");
            trs[1].style.display = 'none';
            trs[2].style.display = 'none';
        }

        com_form.show();
        if (!nickValido) {
            f.getInput('nick').focus();
        } else {
            f.getInput('comentario').focus();
        }
        f.enable(true);
    }

    // Procesa el estado del usuario (funcion de respuesta ajax al chequeo de sesión)
	var processUserState = function (json) {

		var info = json_parse(json);

		window.location.hash = 'form_com';

        if (info && info.state) {
    	    switch(info.state) {
                // No logueado
    	        case 0:
                    noLogin();
    				break;
                // Usuario bloqueado
    	        case 2:
    				showMsg('userBlocked', true);
    	          	break;
                // Sin doc y no puede probar mas
                case 3:
                    showMsg('tooManyDocErrors');
                    break;
                // Hay otro usuario con el mismo doc validado y que es comentarista
                case 4:
                    com_form.hide();
                    /*
                    var err = messages.mustUseOtherUserError;
                    showMsg(err.replace(/%%user%%/, info.usrmustuse));
                    */
                    showMsg('mustUseOtherUserError', true);
                    break;
                // Otros errores
    			case 9:
    				showMsg(info.errmsg);
    				break;
                // Logueado
    	        case 1:
                    setupCommentsForm(info);
    	            break;
    		}
        } else {
            noLogin();
        }
	};

	var getUserState = function () {
		MVD.get('enviacom').hide();
		MVD.getSafe('enviacom2').hide();
		MVD.Ajax.getGX('anusrregcom2', NNotId,
			processUserState,
			function () {
				showMsg('generalError');
				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 = getUserState;
			MVD.getSafe('enviacom2').onclick = getUserState;
            var textocomentario = MVD.get('comentario');
            if (textocomentario) {
                textocomentario.onpaste = function () { return false; };
            }
			f = new MVD.Form('MAINFORM');
			f.setErrorElem('blockerror');
			f.init();
			document.MAINFORM.onsubmit = validarComentario;
            
            if (MVD.CMS.ComPag) {                            
                MVD.CMS.ComPag.addEventListener("onFirstLoad", function () {
                    if (checkAutoForm()) {
        				AutoForm = true;
        				clearAutoForm();
                        // getUserState(); // comCheck(); ???
        			}
                    showEnviacom2();
                    })
            }
            return this;
		},

		// No usar. Usar setMessage('noLoginMsg', txt)
		setNoLoginMsg: function (txt) {
			messages.noLoginMsg = txt;
            return this;
		},

		setMessage: function (id, txt) {
			messages[id] = txt;
            return this;
		}
	};
} ();

