/**********************************For Registering***************************/
function getFirstLastName(name)
{
    var split1 = name.split("@");
    var firstName = '';
    for(var i =0; i < split1[0].length; i++)
    {
        if(split1[0][i].match(/\_|\.|\d/) )
            break;
        else
            firstName += split1[0][i];
    }

    return firstName;

}

function validateRegistration(){

    var emailExpression =/^[\w-]+(\.[\w-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$/;
    mail = document.getElementById("register_username").value;

    if (!emailExpression.test(mail)) {
        hidePleaseWait();
        alert('The E-mail address is invalid!');
        return false; }

    //var expression = /^(?=.*[A-Za-z])(?=.*[0-9])(?!.*[^A-Za-z0-9]).{6,15}$/;
    var password = document.getElementById("rpassword").value;

    /*if(!expression.test(password))*/
    if(password=="")
    {
        hidePleaseWait();
        alert('Password should be atleast 6 character long'); return false;}

    if(password.length <6)
    {
        hidePleaseWait();
        alert('Password should be atleast 6 character long'); return false;}

    var mobileExpression =/^[0-9]{10}$/;
    var mobile = document.getElementById("mobile").value;

    if (mobile == "") {
        hidePleaseWait();
        alert('Please Enter Phone number'); return false; }

    if (!mobileExpression.test(mobile)) {
        hidePleaseWait();
        alert('The Phone number is invalid'); return false; }

    return true;

}

function registerUser(){
    if(validateRegistration()){
        var register_username = document.getElementById("register_username").value;
        var password = document.getElementById("rpassword").value;
        var mobile = document.getElementById("mobile").value;
        var firstname = getFirstLastName(register_username);
        var url = "";
        var tosend = "{\"firstName\": \""+firstname+"\",\"username\": \""+register_username+"\",\"password\": \""+password+"\",\"email\": \""+register_username+"\",\"countryCode\": \"91\",\"phoneNumber\": \""+mobile+"\",\"userPersonalDetail\": {}}";
        //var tosend = "{\"firstName\": \""+firstname+"\",\"lastName\": \""+lastname+"\",\"username\": \""+register_username+"\",\"password\": \""+password+"\",\"email\": \""+email+"\",\"countryCode\": \"91\",\"phoneNumber\": \""+mobile+"\",\"userPersonalDetail\": {}}";

        if(document.getElementById("user").value == 'User'){
            url = "/mgz/services/rest/unauthorize/register";
        }
        else{
            if(document.getElementById("user").value == 'Analyst'){
                url = "/mgz/services/rest/unauthorize/registerasAnalyst";
            }
            else{
                alert("We will contact you shortly");
            }
        }
        $.ajax({
        type: "POST",
        url: url, // URL of the rest layer
        contentType: "application/json; charset=utf-8",
        dataType: "application/json",
        data: tosend,
        async: false,
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        if(XMLHttpRequest.status == 200){
            showLoginForm();
            alert("Thanks for registering with MoneyGuruz. You will shortly receive activation link on your configured email id")
        }
        else{
            var errorMessage  = XMLHttpRequest.responseText;
            var rohit = eval("["+ errorMessage + "]");
            var toShowMessage = rohit[0].errorMsg.replace(/<(?:.|\n)*?>/gm, '');
            hidePleaseWait();
            alert(toShowMessage);
        }

        }, // error
        success: function(data){
            showLoginForm();
            hidePleaseWait();
            alert("Thanks for registering with MoneyGuruz. You will shortly receive activation link on your configured email id");
        } // success
      }); // ajax

    }

}

/**********************************For Login***************************/
$(document).ready(function(){
  $("form#loginForm").submit(function() { // loginForm is submitted

    var username = $('#username').attr('value'); // get username
    var password = $('#password').attr('value'); // get password
    var market = $('#market').attr('value');//get market


    var qry = '<login><username>'+ username + '</username><password>'+password + '</password><market>'+ market + '</market></login>';

    if (username && password) { // values are not empty
      $.ajax({
        type: "POST",
        url: "/mgz/services/rest/unauthorize/login", // URL of the rest layer
        contentType: "text/xml",
        dataType: "text/xml",
        // send username and password as parameters to the Perl script
        data: qry,
        // script call was *not* successful
        error: function(XMLHttpRequest, textStatus, errorThrown) {

         if(XMLHttpRequest.status == 200){
        var values = [Base64.encode(username), Base64.encode(password), false, market];
        createCookie (COOKIE_KEYS, values, COOKIE_EXPIRY_DAYS);
            window.location = "/mgz/pages/main.jsp";
        }
        else
            alert("Authentication failed! Please enter correct username/email-id and password");
        }, // error
        // script call was successful
        // data contains the JSON values returned by the Perl script
        success: function(data){
            var values = [Base64.encode(username), Base64.encode(password), false, market];
            createCookie (COOKIE_KEYS, values, COOKIE_EXPIRY_DAYS);
            window.location = "/mgz/pages/main.jsp";
        } // success
      }); // ajax
    } // if
    else {
      $('div#loginResult').text("enter username/email-id and password");
      $('div#loginResult').addClass("error");
    } // else
    $('div#loginResult').fadeIn();
    return false;
  });
});

/**********************************For Forgot Password***************************/
function validateEmailForm(){
    var emailExpression = /^[\w-]+(\.[\w-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$/;
    mail = document.getElementById("forgotpassword").value;

    if (!emailExpression.test(mail)) {
        alert('The E-mail address is invalid!'); return false; }

    return true;
}

function recoverPassword(){
    if(validateEmailForm()){
        var username = document.getElementById("forgotpassword").value;
        var url = "/mgz/services/rest/unauthorize/recoverpassword/"+username;
        $.ajax({
        type: "GET",
        url: url, // URL of the rest layer
        contentType: "application/json; charset=utf-8",
        dataType: "application/json",
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("Please enter valid email id");
        }, // error
        success: function(data){
            alert("New Password has been sent to your reistered email-id");
        } // success
      }); // ajax
    }
}

