function is_email(value) {
   return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);
}

function xml_to_errors(a) {
   var errores=[]
   var add_error=function() { errores.push($(this).text()) }
   $(a).find('actionErrors item').each(add_error)
   $(a).find('fieldErrors item').each(add_error)
   return errores
}

function Login() {
   var self=this

   this.max_remember_errors=1

   this.is_open=true
   this.id='#login'
   this.wrapper='#login-hide'

   this.is_error_open=false
   this.error_id='#loginerror'

   $('#loginform a').live("click",function() { 
      self.forgot_form() 
      return false
   })
   $('a.identify').live('click', function() {
   		if ($(this).parent("li").length > 0) {
			$(this).css('backgroundColor', '#c50000');
		}
      	self.is_open ? self.close() : self.open();
      	return false;
   })

   this.timeout=null

   $('#login-hide input').focus(function(){ self.clear_timeout() })
   $('#login-hide input').blur(function(){ self.add_timeout() })

   var login_closed=cookie('login_closed')
   if(login_closed) {
      this.close(true)
   } else {
      this.open(true)
      cookie('login_closed','true')
   }

   $('#loginform input.button').click(function() { 
      self.try_login()
      return false
   })
}

Login.prototype.close = function(now) {
   var self=this
   this.error_close()
   $(this.id).animate(
      { top: '-122px' },
      now==null ? 'normal' : 1,
      'swing',
      function() {
         self.is_open=false 
         self.close_wrapper() 
         self.button_off()
   })
}

Login.prototype.open = function(blur) {
   var self=this
   this.clear_timeout()
   this.open_wrapper()
   $(this.id).animate(
      { top: '0px' },
      'normal',
      'swing',
      function() { 
         self.is_open=true 
         self.add_timeout()
         self.button_on()
         if(!blur) 
            $('input:first',$(self.id)).focus()
      })
}

Login.prototype.error_open = function() {
   var self=this

   $(this.error_id).animate(
      { top: '-40px' },
      'normal',
      'swing',
      function() { 
         self.is_error_open=true 
         var inputs=$('input:first',$(self.error_id))
         if(inputs.size()>0) {
            log('inputs, focus and no timeout')
            inputs.focus()
         } else {
            log('no inputs, lets start timeout')
            self.add_timeout()
         }
      })
}

Login.prototype.error_close = function(now) {
   var self=this
   if(!this.is_error_open)
      return
   $(this.error_id).animate(
      { top: '-190px' },
      now==null ? 'normal' : 1,
      'swing',
      function() { self.is_error_open=false })
}

Login.prototype.error_add = function(e) {
   var self=this
   var element=$(e)
   $('#loginerror .in').children().remove()
   $('#loginerror .in').append(element)
   $('input',element).focus(function(){ self.clear_timeout() })
   $('input',element).blur(function(){ self.add_timeout() })
   this.error_open()
}

Login.prototype.forgot_form = function() {
   var self=this
   var form=$('#forgotfrm').clone().show()

    $('input.button',form).click(function() { 
      self.try_remember()
      return false
   })

   this.error_add(form)
}

Login.prototype.try_remember = function() {
   var self=this
   var email=$('#email2').val()
   if(!is_email(email)) {
      this.error_add('<span class="error">El e-mail que has introducido no es válido.</span>')
      return
   }

   log("trying to remember password (email: '"+email+"')")

   $('#forgotfrm input.button').attr('src','/img/button-enviando-rojo.gif')
   $.ajax({
      type: "POST",
      url: "recordarClave.html",
      data: {email: email},
      success: function(a) {
         $('#forgotfrm input.button').attr('src','/img/button-ok.gif')
         var errores=xml_to_errors(a)
         if(errores.length==0) {
            self.error_add('<span class="error">Mensaje enviado</span>')
         } else {
            var e=errores[0]
            self.error_add('<span class="error">'+e+'</span>')
         }
      },
      //timeout: 5000,
      error: function(request,error) {
         $('#forgotfrm input.button').attr('src','/img/button-ok.gif')
         self.error_add('<span class="error">Problema contactando al servidor.</span>')
      }
   })
}

Login.prototype.try_login = function() {
   var self=this

   var email=$('#email1').val()
   if(!is_email(email)) {
      this.error_add('<span class="error">El e-mail que has introducido no es válido.</span>')
      return
   }

   var passwd=$('#password1').val()
   if(passwd=='') {
      this.error_add('<span class="error">La contraseña es necesaria.</span>')
      return
   }

   log("trying to login with email: '"+email+"' password: '"+passwd+"'")
   $('#loginform input.button').attr('src','/img/button-enviando-negro.gif')

   $.ajax({
      type: "POST",
      url: "/login.html",
      data: {email: email, clave: passwd},
      success: function(a) {
         $('#loginform input.button').attr('src','/img/button-ok.png')
         var errores=xml_to_errors(a)
         if(errores.length==0) {
            log('login correct')
            if(ie6()) {
               window.location.reload(true);
            }
            else {
               document.location.href = document.location.href
            }
         } else {
            var e=errores[0]
            if(e=='non.active.user') {
               self.pendiente_validacion(email,passwd)
            } else {
               self.error_add('<span class="error">'+e+'</span>')
            }
         }
      },
      //timeout: 5000,
      error: function(request,error) {
         $('#loginform input.button').attr('src','/img/button-ok.png')
         self.error_add('<span class="error">Problema contactando al servidor.</span>')
      }
   })
}

// wrapper management
Login.prototype.close_wrapper = function() { 
	$('#header-right ul li#identificate a').css('backgroundColor', '#5E5E5E');
   $(this.wrapper).hide()
}

Login.prototype.open_wrapper = function() { 
   $('#header-right ul li#identificate a').css('background-color', '#c50000');
   $(this.wrapper).show()
}

// button management
Login.prototype.button_off = function() { 
   $('a.identify').removeClass('on')
}

Login.prototype.button_on = function() { 
   $('a.identify').addClass('on')
}


// timeout management
Login.prototype.clear_timeout = function() {
   if(this.timeout != null) clearTimeout(this.timeout)
   this.timeout = null
}

Login.prototype.add_timeout = function() {
   var self=this
   this.clear_timeout()
   this.timeout=setTimeout(function() { self.close() }, 20000)
}

// pendiente validacion

Login.prototype.pendiente_validacion = function(email,clave,fun) {
   var send_confirmation_on_click = function() { 
      var en=$('#email3').val()
      log('just pressed ok to send confirmation again to:'+en)
      $('#error-message').jqmHide()
      mandar_confirmacion(email,clave,en)
      return false
   } 

   var mandar_confirmacion=function(email,clave,new_email) {
      $.ajax({
         type: 'GET',
         url: 'reenviarConfirmacionEmail.html',
         data: {email: email,clave: clave, newEmail: new_email },
         success: function(a) {
            $('.error-ok').unbind('click',send_confirmation_on_click)
            var errores=xml_to_errors(a)
            if(errores.length==0) {
               mensaje.by_id('#correomandado')
            } else {
               mensaje.simple(errores[0])
            }
         },
         //timeout: 5000,
         error: function(request,error) {
            $('.error-ok').unbind('click',send_confirmation_on_click)
            mensaje.by_id('#problemservidor')
         }
      })
   }

   mensaje.by_id('#confirmacionemail',fun)
   $('#email3').val(email)

   $('#again a').click(function() { 
      $('#error-message').jqmHide()
      mandar_confirmacion(email,clave,email)
      return false
   })

   $('.error-ok').click(send_confirmation_on_click)
}

/*
$(function() { if($('#login-hide').size()>0)  new Login() });
*/
$(function() { new Login(); })

