var popupAuth = false;
var processedLogin = false;

function base64_encode(data){var b64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";var o1,o2,o3,h1,h2,h3,h4,bits,i=0,ac=0,enc="",tmp_arr=[];if(!data){return data}do{o1=data.charCodeAt(i++);o2=data.charCodeAt(i++);o3=data.charCodeAt(i++);bits=o1<<16|o2<<8|o3;h1=bits>>18&0x3f;h2=bits>>12&0x3f;h3=bits>>6&0x3f;h4=bits&0x3f;tmp_arr[ac++]=b64.charAt(h1)+b64.charAt(h2)+b64.charAt(h3)+b64.charAt(h4)}while(i<data.length);enc=tmp_arr.join('');switch(data.length%3){case 1:enc=enc.slice(0,-2)+'==';break;case 2:enc=enc.slice(0,-1)+'=';break}return enc}

$(document).ready(function()
{

  //Partner login accordion
  $('#form_signin h4').click(function(){
    var e = $(this).next()
    $('#form_signin h4').next().not(e).slideUp();
    e.slideDown();

    $('span', $('#form_signin h4').not(this)).html('+');
    $('span', this).html('-');
  });

  // Form validation //
  $('#form_signin').yav({
    errorMessage: msg.ERRORMESSAGE,
    errorPosition:'after',
    errorDiv: 'errorDiv1',
    onOk:function(the_form)
    {
      $('#errorDiv1').removeClass('error').empty();
      //lo ponemos usando scripts para cross_domain
      $.jCryption.getKeys(str_keys,function(receivedKeys) {
        keys = receivedKeys;
        var my_string = $('#username').val()+'|'+$('#password').val();
        $.jCryption.encrypt(my_string, keys, function(encrypted){
          var enc_string = base64_encode(encrypted);
          /*default script url*/
          var script_url = the_form.action + '/' + enc_string + '/' + str_keys.n + '/' + $('#redirect_to').val();
          try{
            $.getScript(script_url, function(){
              if(!processedLogin)
              {
                document.location.href = document.location.href + '?previous_error=error';
              }
            });
          }catch(e){
            document.location.href = document.location.href + '?previous_error=error';
          }
        });
      });

      return false;
    },
    onError: function()
    {
      var error_string = '';
      $.each($('p.error',$('#form_signin')), function(i, el){
        error_string += '<li>- ' + $(this).html() + '</li>';
        if(i == 0)
        {
          error_string = error_string.replace('<li>- ', '<li class="title">');
        }
        $(this).remove();
      });
      $('#errorDiv1').addClass('error').empty().append($('<ul></ul>').addClass('error').html(error_string));

      return false;
    }
  });

  $('#providers_list button').click(function(){
    window.open('/login/rpx/' + $(this).attr('rel'));
    return false;
  });

  // Recover password //
  $('#recoverpw-trigger').click(function(){
    msgbox($(this.rel));
    return false;
  });

  //MDPS: Reenviar confirmacion de registro
  $('#send-confirmation').live("click",function()
  {

    $.post(noCache("/registration/send_confirmation_email/"), {usrid: this.name},function(response)
    {
      //Intentamos evaluar los datos recibidos
      var data = '';
      try
            {
                data = evalJson(response);
      }
            catch(e)
            {
                data = {
          stat: 'ERROR',
          msg: 'error'
        }
      }
      if (data.stat == 'OK')
      {
        msgbox_info(data.msg);
      }
     });
    //return false;
  });

  $('#form_recoverpw').yav(
    {
    errorMessage: msg.ERRORMESSAGE,
    errorPosition: 'after',
    errorDiv: 'errorDiv_recoverpw',
        onOk:function(the_form)
        {
      $('.error', the_form).remove();

            $.post(noCache(the_form.action), $('#form_recoverpw').serialize(),function(response)
            {
                var data = evalJson(response);
        if (data.stat == 'ERROR')
                {
          $('#errorDiv_recoverpw').append($('<p></p>').addClass('error').text(msg[data.msg]));
        }
                else
                {
                    the_form.reset();
          msgbox_close('all');
          msgbox_success(msg.SUCCESS);
        }
      });

            return false;
    }
    });

});

function onLoginResponse(data){
	processedLogin = true;
	// hide progress bar
	msgbox_close('all');
	if(typeof(data)=='function')
	{
		$('#redirect_to')[0].redirect = data;
		$('#redirect_to')[0].urlredirect = $('#redirect_to').attr('value');
		$('#redirect_to').attr('value','#');
	}
	else
	{
		if (data.stat == 'ERROR')
		{
			//MDPS: Modificacion echa para poder diferenciar entre los textos localizados que hay que interpretar aquí
			//y el caso en el que el texto ya viene listo apra renderizar desde el servidor (opcion direct_render)
			if(data.type != null && data.type == 'direct_render')
			{
				$('#errorDiv1').append($('<p></p>').addClass('error').html(data.msg));
			}
			else
			{
				$('#errorDiv1').append($('<p></p>').addClass('error').html(msg[data.msg]));
			}

		}
		else
		{
			if (typeof(data.ajaxurl) != 'undefined')
			{
				$('#loginResponse').attr('src', _SERVERURI + data.ajaxurl);
			}
			else if ((r_url = $('#redirect_to').val()) !='#')
			{
				if (data.eventattend)
				{
					document.location.href = r_url;
				}
				else
				{
					if(typeof (data.redirect_to) == 'undefined' ){
						if (r_url.indexOf('@') == 0){
							r_url = r_url.substr(1);
						}
						document.location.href = _SERVERURI + r_url.replace(/@/gi,'/');
					}else{
						document.location.href = data.redirect_to;
					}
				}
			}
			else
			{
				$("#redirect_to")[0].redirect(data);
				$("#redirect_to").val($("#redirect_to")[0].urlredirect);
			}
		}
	}
}

function onLoginRedirect(data){
	onLoginResponse(
		$.extend(data, {
			eventattend: false
		})
	);
}

