var leerCookie = function(nombre) {
   a = document.cookie.substring(document.cookie.indexOf(nombre + '=') + nombre.length + 1,document.cookie.length);
   if(a.indexOf(';') != -1)a = a.substring(0,a.indexOf(';'))
   return a;
}

langx=leerCookie('lang');
if (langx=="eu"){
MooTools.lang.setLanguage('eu');
}else{
MooTools.lang.setLanguage('es-ES');
}

//var roar = new Roar({position: 'lowerRight'});

var alerta= function(frase){
	alert(traducir(frase));
}


var idioma={
  'es' : {  
	'login' : 'logueate',
	'email ya registrado, introduce otro' : 'email ya registrado, introduce otro',
    'enviar' : 'enviar',
	'Registro completado correctamente' : 'Registro completado correctamente',
	'Error al registrar, intentelo de nuevo' : 'Error al registrar, intentelo de nuevo',
	'Reto mal introducido, intentelo de nuevo.' : 'Reto mal introducido, intentelo de nuevo.',
	'No se pudo abrir el socket, error al enviar.' : 'No se pudo abrir el socket, error al enviar.',
	'Datos actualizados correctamente.' : 'Datos actualizados correctamente.',
	'Comentario añadido correctamente.' : 'Comentario añadido correctamente.',
	'¿Deseas borrar el comentario?' : '¿Deseas borrar el comentario?',
	'Comentario borrado correctamente.' : 'Comentario borrado correctamente.',
	'Comentario votado correctamente.' : 'Comentario votado correctamente.',
	'Error al actualizar el comentario.' : 'Error al actualizar el comentario.',
	'Los datos introducidos no son correctos!' : '¡Los datos introducidos no son correctos!',
	'¡No se han encontrado usuarios con este email y nick!' : '¡No se han encontrado usuarios con este email y nick!',
	'nick ya registrado, introduce otro' : 'nick ya registrado, introduce otro'
		
  },
  'eu' : {
    'login' : 'logueate',
    'email ya registrado, introduce otro' : 'Helbide hori dagoeneko erregistratuta dago, beste bat sartu',
    'enviar' : 'bialdu',
	'Registro completado correctamente': 'Ondo erregistratu zara.',
	'Error al registrar, intentelo de nuevo': 'Errorea erregistratzean. Saiatu berriro',
	'Reto mal introducido, intentelo de nuevo.':'Txarto sartu duzu. Saiatu berriro.',
	'No se pudo abrir el socket, error al enviar.':'Ezin izan dugu ireki. Errorea bidaltzean.',
	'Datos actualizados correctamente.':'Datuak eguneratu egin dira.',
	'Comentario añadido correctamente.':'Iruzkina gorde egin da.',
	'¿Deseas borrar el comentario?':'Iruzkina ezabatu nahi?',
	'Comentario borrado correctamente.':'Iruzkina ezabatu egin da.',
	'Comentario votado correctamente.':'Iruzkinari botoa eman diozu.',
	'Error al actualizar el comentario.':'Errorea iruzkina eguneratzean.',
	'Los datos introducidos no son correctos!' : 'Sartutako datuak ez dira zuzenak!',
	'¡No se han encontrado usuarios con este email y nick!' : 'Ez dago helbide elektroniko eta ezizen hori duen erabiltzailerik!',
	'nick ya registrado, introduce otro' : 'Ezizen hori dagoeneko erregistratuta dago, beste bat sartu'
		
  },
  'en' : {
    'login' : 'login',
    'enviar' : 'send',
	'Registro completado correctamente': 'You must enter the same password',
	'Error al registrar, intentelo de nuevo': 'Error made while signing up; try again',
	'Reto mal introducido, intentelo de nuevo.':'Incorrectly introduced, try again',
	'No se pudo abrir el socket, error al enviar.':'The socket could not be opened, error in sending.',
	'Datos actualizados correctamente.':'Details successfully updated.',
	'Comentario añadido correctamente.':'Comment successfully added.',
	'¿Deseas borrar el comentario?':'Do you wish to delete your comment?',
	'Comentario borrado correctamente.':'Comment successfully deleted.',
	'Comentario votado correctamente.':'Comment successfully voted.',
	'Error al actualizar el comentario.':'Error made while updating comment.'
  },
  'fr' : {
    'login' : 'Login',
    'enviar' : 'envoi',
	'Registro completado correctamente': 'Enregistrement réalisé correctement',
	'Error al registrar, intentelo de nuevo': 'Erreur denregistrement. Essayez à nouveau',
	'Reto mal introducido, intentelo de nuevo.':'Erreur. Essayez à nouveau',
	'No se pudo abrir el socket, error al enviar.':'Impossible douvrir le socket, erreur denvoi',
	'Datos actualizados correctamente.':'Mise à jour correcte.',
	'Comentario añadido correctamente.':'Commentaire ajouté correctement.',
	'¿Deseas borrar el comentario?':'Voulez-vous effacer le commentaire?',
	'Comentario borrado correctamente.':'Commentaire effacé correctement.',
	'Comentario votado correctamente.':'Commentaire voté correctement.',
	'Error al actualizar el comentario.':'Erreur de mise à jour du commentaire.'
  }
};

var url_idioma={
  'es' : {
    'registro' : '/comunidad/registro/',
    'remember' : '/comunidad/recordar/',
	'usuario' : '/comunidad/usuario/'
  },
  'eu' : {
    'registro' : '/komunitate/erregistroa/',
    'remember' : '/komunitate/gogoratu/',
	'usuario' : '/komunitate/erabiltzaile/'
  },
  'en' : {
    'registro' : '/community/registration/',
    'remember' : '/community/remember/',
	'usuario' : '/community/user/'
  },
  'fr' : {
    'registro' : '/communaute/inscription/',
    'remember' : '/communaute/rappelle/',
	'usuario' : '/communaute/user/'
  }
};
var txt_idioma={
  'es' : {
    'hola' : 'Hola ',
	'logout': 'Cerrar sesión '
  },
  'eu' : {
    'hola' : 'Kaixo ',
	'logout': 'Saioa itxi '  
  },
  'en' : {
    'hola' : 'Hello ',
	'logout': 'Logout '  
  },
  'fr' : {
    'hola' : 'Bienvenue ',
	'logout': 'Logout '  
  }
};


var traducir=function(frase){
  var langx=leerCookie('lang');
  if (idioma[langx][frase]!=undefined && idioma[langx][frase]!= null)
    return idioma[langx][frase];
  else
    return "X-"+frase+"-X";
}

window.addEvent('domready',function(){
;
	SqueezeBox.assign($$('a.boxed'), {
		parse: 'rel'
	});
	SqueezeBox.assign($$('a.btn_boxed'), {
		parse: 'rel'
	});
	SqueezeBox.assign($$('a.btn_sub_boxed'), {
		parse: 'rel'
	});

	SqueezeBox.assign($$('a.menu_izq_boxed'), {
		parse: 'rel'
	});
	
	var lang = 'es';
	
	if ($('getIdioma')) {
		lang = $('getIdioma').get('value');	
	}
	//he cambiado que el lang lo pilla de la coockie
	lang=leerCookie('lang');
	
	var urls = url_idioma[lang];
	
	
	var rememberRequest = new Request.JSON({
		method: 'post',
        url: '/user/name/',		            
        onComplete: function(JSON, text){
			
        	if (JSON.user != null) {
				var saludo = new Element('a', {
					'id': 'nick_usuario_logeado',
					'rel': "shadowbox[user-data];width=565;height=520;options={handler:'iframe'}",
					'class': 'boxed user_data',
					'text': txt_idioma[lang]['hola'] + JSON.user,
					'href': urls['usuario'] + JSON.user + '/',
					//'href': '/comunidad/usuario/' + JSON.user + '/',
					'title': 'Info del usuario'
				});
				if ($$('.login ul')[0] != undefined) {
					$$('.login ul')[0].getElements('li')[0].set('html', "");
					saludo.inject($$('.login ul')[0].getElements('li')[0]);
					var logout = new Element('a', {
						'id': 'user_logout',
						'class': 'cerrar',
						'href': '/user/logout/',
						'title': 'Logout',
						'text': txt_idioma[lang]['logout']
					});
					$$('.login ul')[0].getElements('li')[1].set('html', "");
					logout.inject($$('.login ul')[0].getElements('li')[1]);
					
					if ($('user_logout')){
						if ($('user_logout').retrieve('cargado')!=true){
							$('user_logout').addEvent('click',function(e){
								e = new Event(e).stop();
								var url=window.location.href.toString();
								if (url.substr(url.length-1,1)=="/"){
									url=url.substr(0,url.length-1);
								}
								var logoutRequest = new Request({
						            method: 'post',
						            url: '/user/logout/',
						            data: { 'logout' : 'true' },
						            onComplete: function(response) {		            	
						             	window.location.reload();
									}
					        	}).send();
					        	$('user_logout').store('cargado',true);
							});
						}
					}
									
				}
			}
		}	
	}).send();


	if ($('remember_form')){
		if (this.retrieve('cargado')!=true){
			$('remember_form').addEvent('submit',function(e){
				e = new Event(e).stop();
				var rememberRequest = new Request.JSON({
				method: 'post',
		            url: '/user/remember/',
		            data:
					{
		            	'remember_email' : $('remember_email').get('value'),
						'remember_user' : $('remember_user').get('value'),
						'remember_idioma' : $('idioma').get('value'),
		            	'js' : true
					},
		            onComplete: function(JSON,text) {
		             	if (JSON.estado=='ok'){
		             		alerta('Se ha mandado una nueva contraseña al eMail introducido.');
		             		window.parent.SqueezeBox.close();
		             	}else if (JSON.estado=='no'){							
							/*var alerta = new SexyAlertBox();
							alerta.error('Los datos introducidos no son correctos!');*/
							alerta('¡No se han encontrado usuarios con este email y nick!');
		             	}
		             	//debugHandler(JSON);
					}
	        	}).send();
	        	this.store('cargado',true);
			});
		}
	}

	if ($('login_form')){
		if ($('login_form').retrieve('cargado')!=true){
			var loginSlide = new Fx.Slide('login_form');
			loginSlide.slideOut();
			var cl=$('login_form');
			cl.setStyle('display','block');
			$('login_form').store('cargado',true);
		}
	}

	if ($('user_login')){
		if ($('user_login').retrieve('cargado')!=true){
			$('user_login').addEvent('click',function(e){
				e = new Event(e).stop();
				var loginSlide = new Fx.Slide('login_form');
				loginSlide.toggle();
				$('user_login').store('cargado',true);
			});
		}
	}
	
	if ($('cerrar_login'))
	{
		$('cerrar_login').addEvent('click',function(e)
		{
			e = new Event(e).stop();
			$('login_form').slide('out');
		});
	}	

	$$('.login-secundario').each(function(el){
		if (el.retrieve('cargado')!=true){
			el.addEvent('click',function(e){
				e = new Event(e).stop();
				window.scrollTo(0,0);
				loginSlide.toggle();
				el.store('cargado',true);
			});
		}
	});	

	if ($('form_login')){
		if ($('form_login').retrieve('cargado')!=true){
			$('form_login').addEvent('submit',function(e){
				e = new Event(e).stop();
				//securePassword();
				if ($('username').get('value')=='' || $('password').get('value')==''){
					alerta('Los datos introducidos no son correctos!');
					return;
				}
				var loading=new Element('img',{
					'src':'/commons/img/ajax-loading.gif',
					'alt':'Cargando...'
				});
				var loginRequest = new Request.JSON({
		            method: 'post',
		            url: '/user/login/',
		            data: {
		            	'username' : $('username').get('value'),
		            	'password' : $('password').get('value'),
		            	'authsecret' : $('authsecret').get('value'),
		            	'js' : true
					},
					onRequest: function(){
						loading.inject($('doLogin'),'after');
					},
		            onComplete: function(JSON,text) {
		             	if (JSON.estado=='ok'){		             		
		             		window.location.reload();
		             	}else if (JSON.estado=='no'){
							loading.dispose();
							if (JSON.ban!=undefined){
								switch (JSON.ban){
									case 'permanente':
										alerta('Tu usuario ha sido baneado de manera permanente de este sitio<br/>Motivo: '+JSON.motivo);
									break;
									case 'validar':
										alerta('Tu usuario permanecera baneado hasta que un moderador revise que has corregido lo siguiente:<br/>'+JSON.motivo);
									break;
									default:
										alerta('Tu usuario ha sido baneado hasta '+JSON.ban+'.<br/>Motivo: '+JSON.motivo);
								}
							}else{
								alerta('Los datos introducidos no son correctos!');
							}
		             	}
		             	//debugHandler(JSON);
					}
	        	}).send();
	        	$('form_login').store('cargado',true);
			});
		}
	}

	if ($('user_register')){
		if ($('user_register').retrieve('cargado')!=true){
			var validator = new FormValidator.Inline($('user_register'),{
	   			onFormValidate: function(p,f,e){
	   				e = new Event(e).stop();
					var loading=new Element('img',{
						'src':'/commons/img/ajax-loading.gif',
						'alt':'Cargando...'
					});
					if (p){
						var registerRequest = new Request.JSON({
				            method: 'post',
				            url: '/user/register/',
				            data: {
				            	'user_register_id' : $('user_register_id').get('value'),
								'user_register_fb_uid' : $('user_register_fb_uid').get('value'),
				            	'clave' : $('user_register_clave').get('value'),
								
				            	'nombre' : $('user_register_nombre').get('value'),
				            	'apellido' : $('user_register_apellido').get('value'),
				            	'alias' : $('user_register_alias').get('value'),
				            	'email' : $('user_register_email').get('value'),
								'ocultar_email' : $('user_register_ocultar_email').checked,
								'telefono' : $('user_register_telefono').get('value'),
								'ocultar_telefono' : $('user_register_ocultar_telefono').checked,
				            	'recaptcha_challenge_field' : $('recaptcha_challenge_field').get('value'),
								'recaptcha_response_field' : $('recaptcha_response_field').get('value'),
				            	'js' : true
							},
							onRequest: function(){
								loading.inject($('doRegister'),'after');
		    					$('user_register').getElement('input[type=submit]').set('disabled', 'disabled');
							},
				            onComplete: function(JSON,text) {
								if (JSON.estado=='ok'){
									var alerta = new SexyAlertBox();
									alerta.info(traducir('Registro completado correctamente'),{
									onComplete:function(returnvalue){
						      				parent.location.reload(true);
						    			}
									});
				             	}else if (JSON.estado=='no'){
									loading.dispose();
				             		var alerta = new SexyAlertBox();
									alerta.error(traducir('Error al registrar, intentelo de nuevo'),{
									onComplete:function(returnvalue){
						      				Recaptcha.reload();
						      				$('user_register').getElement('input[type=submit]').erase('disabled');
						    			}
									});
				             	}else if (JSON.estado=='no_email'){
									loading.dispose();
				             		var alerta = new SexyAlertBox();
									alerta.error(traducir('email ya registrado, introduce otro'),{
									onComplete:function(returnvalue){
						      				Recaptcha.reload();
						      				$('user_register').getElement('input[type=submit]').erase('disabled');
						    			}
									});
				             	}else if (JSON.estado=='captcha'){
				             		loading.dispose();
				             		var alerta = new SexyAlertBox();
									alerta.error(traducir('Reto mal introducido, intentelo de nuevo.'),{
									onComplete:function(returnvalue){
						      			Recaptcha.reload();
						      			$('user_register').getElement('input[type=submit]').erase('disabled');
						    			}
									});
				             	}else if (JSON.estado=="no_socket"){
				             		loading.dispose();
				             		var alerta = new SexyAlertBox();
									alerta.error(traducir('No se pudo abrir el socket, error al enviar.'),{
									onComplete:function(returnvalue){
						      				Recaptcha.reload();
						      				$('user_register').getElement('input[type=submit]').erase('disabled');
						    			}
									});
				             	}else if (JSON.estado=="existe_id"){
				             		loading.dispose();
				             		var alerta = new SexyAlertBox();
									alerta.error(traducir('nick ya registrado, introduce otro'),{
									onComplete:function(returnvalue){
						      				Recaptcha.reload();
						      				$('user_register').getElement('input[type=submit]').erase('disabled');
						    			}
									});
				             	}
				             	//debugHandler(JSON);
							}
							
			        	}).send();
					}
	   			}
			});
			$('user_register').store('cargado',true);
		}
	}

	if ($('user_data')){
		if ($('user_data').retrieve('cargado')!=true){
			var validator = new FormValidator.Inline($('user_data'),{
	   			onFormValidate: function(p,f,e){
	   				e = new Event(e).stop();
					if (p){
						$('doUserUpdate').set('disabled','disabled');
						var registerRequest = new Request.JSON({
				            method: 'post',
				            url: $('user_data').action,
				            data: {
				            	'user_data_nombre' : $('user_data_nombre').get('value'),
				            	'user_data_apellido' : $('user_data_apellido').get('value'),
								'user_data_clave_nueva' : $('user_data_clave_nueva').get('value'),
				            	'user_data_usuario' : $('user_data_usuario').get('value'),
								'user_data_ocultar_email': $('user_data_ocultar_email').get('checked'),
								'user_data_telefono': $('user_data_telefono').get('value'),
								'user_data_ocultar_telefono': $('user_data_ocultar_telefono').get('checked'),
								'user_data_sexo' : $('user_data').getElement('input[name=user_data_sexo]:checked').value,
				            	'user_data_localidad' : $('user_data_localidad').get('value'),
				            	'user_data_cod_postal' : $('user_data_cod_postal').get('value'),
				            	'user_data_web' : $('user_data_web').get('value'),								
				            	'js' : true
							},
				            onComplete: function(JSON,text) {
			                    var alerta = new SexyAlertBox();
				            	if (JSON==null || JSON.estado=='no'){
									/*var alerta = new SexyAlertBox();
									alerta.error('Error al actualizar, intentelo de nuevo.');*/
									alerta.error(traducir('Error al actualizar, intentelo de nuevo.'));
				             	}else if (JSON.estado=='ok'){
									alerta.info(traducir('Datos actualizados correctamente.'),{
										onComplete:function(returnvalue){
						      				window.parent.SqueezeBox.close();
						    			}
									});
				             	}
			                    $('doUserUpdate').erase('disabled');
			                    //debugHandler(JSON);
							}
				        }).send();
						//console.log(registerRequest.data);
	     			}
				}
			});
			
			$('user_data').store('cargado',true);
		}
	}
	
	if ($('user_subidas_data')){
		if ($('user_subidas_data').retrieve('cargado')!=true){
			var validator = new FormValidator.Inline($('user_subidas_data'),{
	   			onFormValidate: function(p,f,e){
	   				e = new Event(e).stop();
					if (p){
						$('doUserSubidasUpdate').set('disabled','disabled');
						var registerRequest = new Request.JSON({
				            method: 'post',
				            url: $('user_subidas_data').action,
				            data: {
				            	'user_data_usuario' : $('user_data_usuario').get('value'),
								'user_data_biografia' : $('user_data_biografia').get('value'),
				            	'user_data_equipo_foto' : $('user_data_equipo_foto').get('value'),								
				            	'js' : true
							},
				            onComplete: function(JSON,text) {
								//console.log(registerRequest);
			                    var alerta = new SexyAlertBox();
				            	if (JSON==null || JSON.estado=='no'){
									alerta.error(traducir('Error al actualizar, intentelo de nuevo.'));
				             	}else if (JSON.estado=='ok'){
									alerta.info(traducir('Datos actualizados correctamente.'),{
										onComplete:function(returnvalue){
						      				window.parent.SqueezeBox.close();
						    			}
									});
				             	}
			                    $('doUserSubidasUpdate').erase('disabled');
			                    //debugHandler(JSON);
							}
				        }).send();
	     			}
				}
			});
			$('user_subidas_data').store('cargado',true);
		}
	}

	$$('.textcount').each(function(el){
		if (el.retrieve('cargado')!=true){
			el.addEvent('keydown',function(e){
				var totalCharsSpan=$('comment_data_text_span').getNext('span');
				var totalChars=totalCharsSpan.get('text');
				var currentChars=this.get('value').length;
				var supr=32;
				var del=8;
				var up=38;
				var down=40;
				var right=39;
				var left=37;
				if (currentChars>499 && e.code!=supr && e.code!=del && e.code!=up && e.code!=down && e.code!=right && e.code!=left ){
					e = new Event(e).stop();
				}else{
					totalCharsSpan.set('text',499-currentChars);
				}
				el.store('cargado',true);
			});
		}
	});
});

function facebookRegister(arguments){
	
	var registerRequest = new Request.JSON({
        method: 'post',
        url: '/user/check_fb/',
        onComplete: function(JSON,text) {
        	if (JSON==null || JSON.estado=='no'){
				var lang=leerCookie('lang');
				var urls = url_idioma[lang];
				Shadowbox.open({
			        content:    urls['registro']+'?facebook',
			        player:     "iframe",
			        width:      565,
					height:     660
			    });
         	}else if (JSON.estado=='ok'){
				location.reload(true);
         	}
		}
    }).send();
}



/*
	MooIPE - MooTools InPlace Editor
	By: SilverTab(Jean-Nicolas Jolivet), www.silverscripting.com

	Licensed under MIT License, Copyright (c) 2008 Jean-Nicolas Jolivet
	For More info: http://www.opensource.org/licenses/mit-license.php
*/
var mooipe = new Class({
	Implements: [Options],
	options : {
		hlColor: "#BEFFEF",
		restoreColor: "#FFFFFF",
		rows: 1,
		cols: 20,
		okText: 'Guardar',
		cancelText: 'Cancelar',
		savingText: 'Guardando...',
		method: 'post'
	},

	initialize: function(el,url,options) {
		var mooipe=this;
		mooipe.setOptions(options);
		this.el = ($type(el) == "string" ? $(el) : el);
		this.elid = el;
		this.displayStyle = this.el.getStyle('display');
		this.url=url;


		//this.hlEffect = new Fx.Style(this.el, , {duration: 800});
		this.hlEffect = new Fx.Tween(this.el,{duration: 800}).start('background-color');
		var mouseenter=(function(){this.el.setStyle('background-color', this.options.hlColor);}).bind(this);
		this.el.addEvent('mouseenter',mouseenter);
		var mouseleave=(function(){this.el.setStyle('background-color', this.options.restoreColor);}).bind(this);
		this.el.addEvent('mouseleave',mouseleave);
		var click=this.enterEditMode.bind(this);
		this.el.addEvent('click',click);

		this.editForm = new Element('form', {
			'name': this.elid + '-form',
			'events': {
				'submit': function(e) {
					this.exitEditMode(true);
					e.preventDefault();
				}.bind(this)
			}
		});

		if(this.options.rows != 1) {
			this.editField = new Element('textarea', {
				'name': 'fieldValue',
				'value': this.el.innerHTML,
				'cols': this.options.cols,
				'rows': this.options.rows
			});
		}
		else {
			this.editField = new Element('input', {
				'type': 'text',
				'name': 'fieldValue',
				'value': this.el.innerHTML,
				'size': this.options.cols
			});
		}

		this.okButton = new Element('input', {
			'type': 'button',
			'value': this.options.okText,
			'events' : {
				'click': this.exitEditMode.bind(this, true)
			}
		});
		this.cancelButton = new Element('input', {
			'id': this.elid + '-cancel',
			'type': 'button',
			'value': this.options.cancelText,
			'events': {
				'click': this.exitEditMode.bind(this)
			}
		});
		this.editField.inject(this.editForm,'inside');
		if(this.options.rows > 1) {
			lb = new Element('br');
			lb.inject(this.editForm,'inside');
		}
		this.okButton.inject(this.editForm,'inside');
		this.cancelButton.inject(this.editForm,'inside');
	},

	enterEditMode: function() {
		this.el.setStyle('display', 'none');
		this.editField.set('value',this.el.get('html'));
		this.editForm.inject(this.el,'after');
		this.editField.focus();
		this.editField.select();
	},

	exitEditMode: function(save) {

		var save = save == null || save == "" || $type(save) != 'boolean' ? false : true;
		if(save) {
			this.options.data = {
				'nuevotexto':this.editForm.fieldValue.get('value').trim(),
				'viejotexto':this.el.get('text').trim()
			};
			var ipeRequest = new Request.JSON({
				url : this.url,
				data: this.options.data,
				method : this.options.method,
				onFailure: this.ipeFailure.bind(this),
				onSuccess: this.ipeSuccess.bind(this)
			}).send();
			this.el.set('html',this.options.savingText);
		}
		else {
			this.editForm.dispose();
			this.el.setStyle('display', this.displayStyle);
			this.el.fireEvent('mouseleave');
		}
	},
	ipeSuccess: function(JSON,text){
		this.el.set('html',this.editForm.fieldValue.get('value'));
		if (JSON==null || JSON.estado=='no'){
			/*var alerta = new SexyAlertBox();
			alerta.error('Error al actualizar el comentario.');*/
			alerta('Error al actualizar el comentario.');
     	}else if (JSON.estado=='ok'){
     		/*var alerta = new SexyAlertBox();
			alerta.info('Comentario actualizado correctamente.');*/
			alerta('Comentario actualizado correctamente.');
     	}
		this.unload();
		//debugHandler(JSON);
	},
	ipeFailure: function(resp) {
		this.el.set('html',"Error! Code: " + resp.status + " Text: " + resp.statusText);
		alerta.error(traducir('Error al actualizar el comentario.'));
		//debugHandler(JSON);
	},

	unload: function(){
		this.editForm.dispose();
		this.el.setStyle('display', this.displayStyle);
		this.el.fireEvent('mouseleave');

		this.el.removeEvents('mouseenter');
		this.el.removeEvents('mouseleave');
		this.el.removeEvents('click');
	}

});


/*var hexcase = 0;
var b64pad  = "";
var chrsz   = 8;
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }
function md5_vm_test()
{
  return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}
function core_md5(x, len)
{
  x[len >> 5] |= 0x80 << ((len) % 32);
  x[(((len + 64) >>> 9) << 4) + 14] = len;

  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;

    a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
    d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
    c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
    b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
    a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
    d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
    c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
    b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
    a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
    d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
    c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
    b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
    a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
    d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
    c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
    b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);

    a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
    d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
    c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
    b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
    a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
    d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
    c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
    b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
    a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
    d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
    c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
    b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
    a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
    d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
    c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
    b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);

    a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
    d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
    c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
    b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
    a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
    d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
    c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
    b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
    a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
    d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
    c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
    b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
    a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
    d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
    c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
    b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);

    a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
    d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
    c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
    b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
    a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
    d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
    c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
    b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
    a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
    d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
    c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
    b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
    a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
    d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
    c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
    b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
  }
  return Array(a, b, c, d);

}
function md5_cmn(q, a, b, x, s, t)
{
  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
  return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
  return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
  return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
  return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
function core_hmac_md5(key, data)
{
  var bkey = str2binl(key);
  if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);

  var ipad = Array(16), opad = Array(16);
  for(var i = 0; i < 16; i++)
  {
    ipad[i] = bkey[i] ^ 0x36363636;
    opad[i] = bkey[i] ^ 0x5C5C5C5C;
  }

  var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
  return core_md5(opad.concat(hash), 512 + 128);
}
function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}
function bit_rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}
function str2binl(str)
{
  var bin = Array();
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < str.length * chrsz; i += chrsz)
    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
  return bin;
}
function binl2str(bin)
{
  var str = "";
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < bin.length * 32; i += chrsz)
    str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
  return str;
}
function binl2hex(binarray)
{
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i++)
  {
    str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
           hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
  }
  return str;
}
function binl2b64(binarray)
{
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i += 3)
  {
    var triplet = (((binarray[i   >> 2] >> 8 * ( i   %4)) & 0xFF) << 16)
                | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
                |  ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
    for(var j = 0; j < 4; j++)
    {
      if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
      else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
    }
  }
  return str;
}
*/
var debugConsole=function(str){
	console.log(str);
}
var debugWeb=function(str){
	var divDebug=new Element('div',{
		'class': 'debug_panel',
		'styles':{
			'position': 'absolute',
			'top': '0px',
			'width': '100%',
			'background-color':'gray',
			'z-index':'9999'
		},
		'text':str
	});
	var spanDebug=new Element('span',{
		'styles':{
			'color': 'white',
			'float': 'right'
		}
	});
	var aDebug=new Element('a',{
		'events':{
			'click': function(e){
				e = new Event(e).stop();
				this.getParent().getParent().dispose();
			}
		},
		'title': 'Cerrar consola',
		'text': 'Cerrar [X]'
	});
	aDebug.inject(spanDebug);
	spanDebug.inject(divDebug,'top');
	divDebug.inject(document.body,'top');
}

var debugHandler=function(JSON){
	if (JSON==null) return;
	if (JSON.debugType!=null && JSON.debugType!=undefined){
		switch (JSON.debugType){
 			case 'console':
 				debugConsole(JSON.debug);
 			break;
 			case 'web':
 				debugWeb(JSON.debug);
 			break;
 		}
   	}
}

/*
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */

/*
 * Configurable variables. You may need to tweak these to be compatible with
 * the server-side, but the defaults work in most cases.
 */
var hexcase = 0;   /* hex output format. 0 - lowercase; 1 - uppercase        */
var b64pad  = "";  /* base-64 pad character. "=" for strict RFC compliance   */

/*
 * These are the functions you'll usually want to call
 * They take string arguments and return either hex or base-64 encoded strings
 */
function hex_md5(s)    { return rstr2hex(rstr_md5(str2rstr_utf8(s))); }
function b64_md5(s)    { return rstr2b64(rstr_md5(str2rstr_utf8(s))); }
function any_md5(s, e) { return rstr2any(rstr_md5(str2rstr_utf8(s)), e); }
function hex_hmac_md5(k, d)
  { return rstr2hex(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d))); }
function b64_hmac_md5(k, d)
  { return rstr2b64(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d))); }
function any_hmac_md5(k, d, e)
  { return rstr2any(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d)), e); }

/*
 * Perform a simple self-test to see if the VM is working
 */
function md5_vm_test()
{
  return hex_md5("abc").toLowerCase() == "900150983cd24fb0d6963f7d28e17f72";
}

/*
 * Calculate the MD5 of a raw string
 */
function rstr_md5(s)
{
  return binl2rstr(binl_md5(rstr2binl(s), s.length * 8));
}

/*
 * Calculate the HMAC-MD5, of a key and some data (raw strings)
 */
function rstr_hmac_md5(key, data)
{
  var bkey = rstr2binl(key);
  if(bkey.length > 16) bkey = binl_md5(bkey, key.length * 8);

  var ipad = Array(16), opad = Array(16);
  for(var i = 0; i < 16; i++)
  {
    ipad[i] = bkey[i] ^ 0x36363636;
    opad[i] = bkey[i] ^ 0x5C5C5C5C;
  }

  var hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8);
  return binl2rstr(binl_md5(opad.concat(hash), 512 + 128));
}

/*
 * Convert a raw string to a hex string
 */
function rstr2hex(input)
{
  try { hexcase } catch(e) { hexcase=0; }
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var output = "";
  var x;
  for(var i = 0; i < input.length; i++)
  {
    x = input.charCodeAt(i);
    output += hex_tab.charAt((x >>> 4) & 0x0F)
           +  hex_tab.charAt( x        & 0x0F);
  }
  return output;
}

/*
 * Convert a raw string to a base-64 string
 */
function rstr2b64(input)
{
  try { b64pad } catch(e) { b64pad=''; }
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var output = "";
  var len = input.length;
  for(var i = 0; i < len; i += 3)
  {
    var triplet = (input.charCodeAt(i) << 16)
                | (i + 1 < len ? input.charCodeAt(i+1) << 8 : 0)
                | (i + 2 < len ? input.charCodeAt(i+2)      : 0);
    for(var j = 0; j < 4; j++)
    {
      if(i * 8 + j * 6 > input.length * 8) output += b64pad;
      else output += tab.charAt((triplet >>> 6*(3-j)) & 0x3F);
    }
  }
  return output;
}

/*
 * Convert a raw string to an arbitrary string encoding
 */
function rstr2any(input, encoding)
{
  var divisor = encoding.length;
  var i, j, q, x, quotient;

  /* Convert to an array of 16-bit big-endian values, forming the dividend */
  var dividend = Array(Math.ceil(input.length / 2));
  for(i = 0; i < dividend.length; i++)
  {
    dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1);
  }

  /*
   * Repeatedly perform a long division. The binary array forms the dividend,
   * the length of the encoding is the divisor. Once computed, the quotient
   * forms the dividend for the next step. All remainders are stored for later
   * use.
   */
  var full_length = Math.ceil(input.length * 8 /
                                    (Math.log(encoding.length) / Math.log(2)));
  var remainders = Array(full_length);
  for(j = 0; j < full_length; j++)
  {
    quotient = Array();
    x = 0;
    for(i = 0; i < dividend.length; i++)
    {
      x = (x << 16) + dividend[i];
      q = Math.floor(x / divisor);
      x -= q * divisor;
      if(quotient.length > 0 || q > 0)
        quotient[quotient.length] = q;
    }
    remainders[j] = x;
    dividend = quotient;
  }

  /* Convert the remainders to the output string */
  var output = "";
  for(i = remainders.length - 1; i >= 0; i--)
    output += encoding.charAt(remainders[i]);

  return output;
}

/*
 * Encode a string as utf-8.
 * For efficiency, this assumes the input is valid utf-16.
 */
function str2rstr_utf8(input)
{
  var output = "";
  var i = -1;
  var x, y;

  while(++i < input.length)
  {
    /* Decode utf-16 surrogate pairs */
    x = input.charCodeAt(i);
    y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
    if(0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF)
    {
      x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF);
      i++;
    }

    /* Encode output as utf-8 */
    if(x <= 0x7F)
      output += String.fromCharCode(x);
    else if(x <= 0x7FF)
      output += String.fromCharCode(0xC0 | ((x >>> 6 ) & 0x1F),
                                    0x80 | ( x         & 0x3F));
    else if(x <= 0xFFFF)
      output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F),
                                    0x80 | ((x >>> 6 ) & 0x3F),
                                    0x80 | ( x         & 0x3F));
    else if(x <= 0x1FFFFF)
      output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07),
                                    0x80 | ((x >>> 12) & 0x3F),
                                    0x80 | ((x >>> 6 ) & 0x3F),
                                    0x80 | ( x         & 0x3F));
  }
  return output;
}

/*
 * Encode a string as utf-16
 */
function str2rstr_utf16le(input)
{
  var output = "";
  for(var i = 0; i < input.length; i++)
    output += String.fromCharCode( input.charCodeAt(i)        & 0xFF,
                                  (input.charCodeAt(i) >>> 8) & 0xFF);
  return output;
}

function str2rstr_utf16be(input)
{
  var output = "";
  for(var i = 0; i < input.length; i++)
    output += String.fromCharCode((input.charCodeAt(i) >>> 8) & 0xFF,
                                   input.charCodeAt(i)        & 0xFF);
  return output;
}

/*
 * Convert a raw string to an array of little-endian words
 * Characters >255 have their high-byte silently ignored.
 */
function rstr2binl(input)
{
  var output = Array(input.length >> 2);
  for(var i = 0; i < output.length; i++)
    output[i] = 0;
  for(var i = 0; i < input.length * 8; i += 8)
    output[i>>5] |= (input.charCodeAt(i / 8) & 0xFF) << (i%32);
  return output;
}

/*
 * Convert an array of little-endian words to a string
 */
function binl2rstr(input)
{
  var output = "";
  for(var i = 0; i < input.length * 32; i += 8)
    output += String.fromCharCode((input[i>>5] >>> (i % 32)) & 0xFF);
  return output;
}

/*
 * Calculate the MD5 of an array of little-endian words, and a bit length.
 */
function binl_md5(x, len)
{
  /* append padding */
  x[len >> 5] |= 0x80 << ((len) % 32);
  x[(((len + 64) >>> 9) << 4) + 14] = len;

  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;

    a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
    d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
    c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
    b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
    a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
    d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
    c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
    b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
    a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
    d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
    c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
    b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
    a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
    d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
    c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
    b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);

    a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
    d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
    c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
    b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
    a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
    d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
    c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
    b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
    a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
    d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
    c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
    b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
    a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
    d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
    c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
    b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);

    a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
    d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
    c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
    b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
    a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
    d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
    c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
    b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
    a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
    d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
    c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
    b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
    a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
    d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
    c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
    b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);

    a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
    d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
    c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
    b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
    a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
    d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
    c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
    b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
    a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
    d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
    c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
    b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
    a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
    d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
    c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
    b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
  }
  return Array(a, b, c, d);
}

/*
 * These functions implement the four basic operations the algorithm uses.
 */
function md5_cmn(q, a, b, x, s, t)
{
  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
  return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
  return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
  return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
  return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}

/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

/*
 * Bitwise rotate a 32-bit number to the left.
 */
function bit_rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}


