$(document).ready(function () {
    //catch form submit
 	$(".form-horizontal").submit(function () {
    	return false;
    });
	
	//button register click
    $("#btn-adduser").click(function () {
        if(registeruser.validateRegistration() === true) {
            //validation passed
            var regMail     = $("#reg-email").val(),
                regUser     = $("#reg-username").val(),
                regPass     = $("#reg-password").val(),
                regPassConf = $("#reg-repeat-password").val(),
				userRole   = $("#user_role").val();

            //create data that will be sent to server
            var data = { 
                userData: {
                    email           : regMail,
                    username        : regUser,
                    password        : regPass,
                    confirm_password: regPassConf,
					user_role       : userRole
                },
                fieldId: {
                    email           : "reg-email",
                    username        : "reg-username",
                    password        : "reg-password",
                    confirm_password: "reg-repeat-password",
					user_role       : "user_role"
                }
            };
            
            //send data to server
            registeruser.addUser(data);
        }                        
    });
});



/** REGISTER NAMESPACE
 ======================================== */

var registeruser = {};


/**
 * Registers new user.
 * @param {Object} data Register form data.
 */
registeruser.addUser = function (data) {
    //get register button
    var btn = $("#btn-adduser");
    
    //put button to loadin state
    asengine.loadingButton(btn, "Creating acount...");
    
    //hash passwords before send them through network
    data.userData.password = CryptoJS.SHA512(data.userData.password).toString();
    data.userData.confirm_password = CryptoJS.SHA512(data.userData.confirm_password).toString();
    
    //send data to server
    $.ajax({
        url: "ASEngine/ASAjax.php",
        type: "POST",
        data: {
            action  : "addUser",
            user    : data
        },
        success: function (result) {
            //return button to normal state
            asengine.removeLoadingButton(btn);
            
			
            //parse result to JSON
            var res = JSON.parse(result);
            
            if(res.status === "error") {
                //error
                
                //display all errors
                for(var i=0; i<res.errors.length; i++) {
                    var error = res.errors[i];
                    asengine.displayErrorMessage($("#"+error.id), error.msg);
                }
            }
            else {
                //display success message
                asengine.displaySuccessMessage($("#successuser"), res.msg);
				//asengine.displaySuccessMessage($(".adduser-form fieldset"), res.msg);
				//asengine.displaySuccessMessage($("#successuser"),"Details updated successfully.");
            }
        }
    });
};


/**
 * Validate registration form.
 * @returns {Boolean} TRUE if form is valid, FALSE otherwise.
 */
registeruser.validateRegistration = function () {
    var valid = true;
    
    //remove previous error messages
    asengine.removeErrorMessages();
    
    
    //check if all fields are filled
    $(".adduser-form").find("input").each(function () {
        var el = $(this);

        if($.trim(el.val()) === "") {
            asengine.displayErrorMessage(el);
            valid = false;
        }
    });

    //get email, password and confirm password for further validation
    var regMail     = $("#reg-email"),
        regPass     = $("#reg-password"),
        regPassConf = $("#reg-repeat-password");
    
    //check if email is valid
    if(!asengine.validateEmail(regMail.val()) && regMail.val() != "") {
        valid = false;
        asengine.displayErrorMessage(regMail,"Please insert valid email.");
    }

    //check if password and confirm password fields are equal
    if(regPass.val() !== regPassConf.val() && regPass.val() != "" && regPassConf.val() != "") {
        valid = false;
        asengine.displayErrorMessage(regPassConf, "Passwords don't match.");
    }

    return valid;
};