﻿$(document).ready(function() {   

    $("#SaveAccount").click(function() {
    
        var strU = $(".AccountUsername").val();
        var NewPassword = $("#tbxChangeNewPassword").val();
        var OldPassword = $("#tbxChangeOldPassword").val();
        var EmailAddress = $(".AccountEmail").val();
        var ErrorMessage ="";
        
        var chk=1;
        
        if (strU=="")
        {
            ErrorMessage+="Please enter username";
            chk=0;
        }
        
        if (EmailAddress=="")
        {
            ErrorMessage+="Please enter an email address";
            chk=0;
        }
        else
        {
            var re = new RegExp("^[a-zA-Z][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]\$","gi");
            var m = re.exec(EmailAddress);
            
            if (m==null)
            {
                ErrorMessage+="Please enter a valid email address";
                chk=0;
            }
        }
    
        if (OldPassword!="")
        {   
            if ((NewPassword!="") & ($("#tbxChangeNewPasswordConfirm").val()!=""))
            {
                if (NewPassword != $("#tbxChangeNewPasswordConfirm").val())
                {
                    ErrorMessage+="New password does not match confirmation of password";
                    chk=0;
                }
                else if (NewPassword.length<4)
                {
                    ErrorMessage+="New password must be over four characters";
                    chk=0;
                }
                
            }
            else
            {
                aErrorMessage+="You need to enter and confirm you new password";
                chk=0;
            }
        }
             
        if (chk==1)
        {
            $.post("_admin/__UpdateDetails.aspx", {usr: strU, oPsd: OldPassword, nPsd: NewPassword, emaL: EmailAddress}, function(xml) {
                var res = $("Result", xml).text();
                        
                if (res>0)
                {   
                    // we have saved something and that's cool             
                    top.location=ForumURL + "?thID=" + threadID;
                }
                else if (res==0)
                {
                    // username taken
                    alert("That username is already taken, please try a different username");
                }
                else if (res==-2)
                {
                    // there is nothing to save or do
                    top.location=ForumURL + "?thID=" + threadID;
                }
                else
                {
                    // something has gone wrong
                    alert("Something has gone wrong, please try again later");
                }
                
            });
        }
        else
        {
            alert(ErrorMessage);
        }

    });

});
