﻿var redirectPage = "Index.aspx";
var userIP;
var visitorId;
//*******************************************************************************************************************************//
//
//  FUNCIONES PARA MANEJAR EVENTOS DE LOGIN
//
//*******************************************************************************************************************************//

////Chequea la autenticación
//function checkAutentication(redirect)
//{
//    redirectPage = "Index.aspx";
//    if(redirect!=undefined)
//        redirectPage = redirect;
//    $Ajax(basepath + "controllers/Login/Login.aspx?method=checkSession", {
//        cache: false, 
//        onfinish: function(html)
//        {
//            if(html=="True")
//            {
//                window.location = basepath + redirectPage; 
//            }
//            else{
//                login();
//            }
//        },
//        tipoRespuesta:$tipo.TEXTO});
//}

function RememberOrUnlock(){
    show('divMailEntry','blind');
}

function LogOut(){
    $Ajax(basepath + "controllers/Login/login.aspx?method=logOut", {
            cache: false, 
            onfinish: function(result) {
                if(result=="1"){
                   window.location = basepath+redirectPage; 
                }
            },
            tipoRespuesta:$tipo.TEXTO});
}

function DeleteAccount(step){

    switch(step){
        case 'check':
            show('divPassCheck','blind');
            break;
        case 'sure':
            if($F("txtPassCheck").replace(/\s/g,'') == ""){
                $("lblErrorDelete").innerHTML = "Enter Password";  
            }
            else{
                hide('divPassCheck','blind');
                setTimeout(function(){show('divDeleteCheck','blind');},500);
            }
            break;
        case 'delete':
            RemoveUser();
            break;
        case 'cancel':
            hide('divDeleteCheck','blind');
            break;
        default:
            break;
                      
    }
}

function onEnterLogin(ev,type)
{
    if(ev==13)
    {
        switch(type){
            case 'login':
                return fireLogin();
                break;
            case 'remember':
                return SendRememberPass();
                break;
            case 'delete':
                return DeleteAccount('sure');
                break;
            default:
                break;
        
        }
        
    }  
}


function fireLogin()
{
    var retorno = true;
    userIP = $('userIP').innerHTML;
    visitorId = $('visitorId').innerHTML; 
       
    //Cheque que haya ingresado bien los datos    
    var user = $F("txtUser");
    var pass = $F("txtPassword");

    if(user.replace(/\s/g,'') == '')
    {
        $('lblUser').innerHTML = '*';
        retorno = false;
    }
    else
    {
        $('lblUser').innerHTML = '';
    }
    
    if(pass.replace(/\s/g,'') == '')
    {
        $('lblPassword').innerHTML = '*';
        retorno = false;
    }
    else
    {
        $('lblPassword').innerHTML = '';
    }
    
    if(retorno)
    {
        invocarLogin();
    }
          
    return false;

}


function invocarLogin(){
    
    var pass_md5 = hex_md5($F("txtPassword").replace(/\s/g,''));
    $Ajax(basepath+"controllers/Login/Login.aspx?method=checkLogin", {
            cache: false, 
            metodo: $metodo.POST,
            parametros: {"UserName":$F("txtUser").replace(/\s/g,''),"Password":pass_md5,"ip":trim(userIP)},
            onfinish: function(login) {
                                
                switch(login[0].result){                           
                    case '0': //Login Correcto
                        //Llamo al controlador para que coloque en la session
                        $('lblLoginError').innerHTML = '';                            
                        setSession($F("txtUser"),login[0].userid,login[0].id,login[0].type);   
                        hide('divLogin');
                        show('divUserMenu');                  
                        break;
                
                    case '1': 
                        $('lblLoginError').innerHTML = 'Invalid Password';                            
                        break;
                        
                    case '2': 
                        $('lblLoginError').innerHTML = 'Locked for Invalid Password';
                        break;
                        
                    case '3': 
                        //Me llega de la forma "unlockHour - locks_types.detail"
                      $('lblLoginError').innerHTML = "User locked. You must wait for " + login[0].locktime + " hour/s. " + login[0].locktype;
                       break;
                        
                    case '4': 
                        $('lblLoginError').innerHTML = 'User not validated. You must validate user';
                        break;
                
                    case '5': 
                        $('lblLoginError').innerHTML = 'Invalid User';
                        break;
                        
                     case '6': 
                        $('lblLoginError').innerHTML = 'Locked for Invalid User';                            
                        break;
                
                    case '7': 
                        $('lblLoginError').innerHTML = 'We are sorry, your request could not be completed';
                        break;
                }   
            },
            tipoRespuesta:$tipo.JSON});

}

function setSession(username,userid, id, type){
    $Ajax(basepath+"controllers/Login/Login.aspx?method=generateSession", {
            cache: false, 
            metodo: $metodo.POST,
            parametros: {"UserName":username,"UserId":userid,"Id":id,"Type":type,"cookie": setCookie()},
            onfinish: function(html) {
                window.location.reload();  
            },
            tipoRespuesta:$tipo.TEXTO});

}

function setCookie()
{
    if($("cookieTrue").checked)
    {
        return "1";
    }
    else
    {
        return "0"; 
    }
}

function waterUser()
{
    if($('txtUser') != null)
    watermark('txtUser', 'Enter Username', 'input_marcagua');
}

function waterEmail()
{
    if($('txtEmail') != null)
    watermark('txtEmail', 'Enter the email you registered with', 'input_marcagua');
}

function SendRememberPass()
{
    if(!checkEmail($F('txtEmail'))){
        $("lblMailError").innerHTML = "Invalid Email!";  
    }
    else{
        $("lblMailError").innerHTML = "";  
        $Ajax(basepath + "controllers/Login/login.aspx?method=sendRemember", {
            parametros: {"email":$F("txtEmail")},
            cache: false        
            });
        hide('divMailEntry','blind');
        setTimeout(function(){show('divThanksEmail','blind');},500);
        setTimeout(function(){hide('divThanksEmail','blind');},2000);
    }
}

function RemoveUser(){
    $Ajax(basepath + "controllers/Login/login.aspx?method=deleteAccount", {
            cache: false, 
            metodo: $metodo.POST,
            parametros: {"Password":hex_md5($F('txtPassCheck'))},
            onfinish: function(result) {
                if(result=="2"){
                    $('lblErrorDelete').innerHTML = 'Invalid Password';
                }
                else if (result == "1"){
                   window.location = basepath+redirectPage; 
                }
                else{
                    $('lblErrorDelete').innerHTML = 'Unexpected Error, Try Again.';
                }
            },
            tipoRespuesta:$tipo.TEXTO});
}