﻿function changePassword(obj)
{
    var oldpassword = document.getElementById('new_oldpassword').value;
    var newpassword = document.getElementById('new_new_password').value;
    var confirmp    = document.getElementById('new_new_password_confirm').value;
    
    var re  = '^[\.a-zA-Z0-9]+$';
    if(!oldpassword.match(re) || !newpassword.match(re) || !confirmp.match(re) || oldpassword.length >= 45 || newpassword.length >= 45 || confirmp.length >= 45) {
        alert('Khong hop le, yeu cau nhap lai');
        return false;
    }
    
    if(newpassword  != confirmp) {
        alert('Yeu cau nhap lai, ban phai nhap 2 o cuoi nhu nhau');
        return false;
    }
    
    // password nhap vao da hop le
    
    if(!confirm('Ban co chac ban se thay doi password ?')) { // khong doi password nua
        obj.style.display   = 'none';
        return false;
    }
    
    obj.style.display   = 'none';
    
    var XMLhttp = getAjaxCore();
    
    XMLhttp.onreadystatechange  =   function()
    {
        // prepare
        var inner       = document.getElementById('ajax_loading');
        
        var availWidth  = parseInt(document.documentElement.clientWidth)/2 - 300 + 'px';
        
        inner.style.left    = availWidth;
        inner.style.top     = 300 + 'px';
        
        inner.style.display = 'block';
        
        // case
        if(XMLhttp.readyState   != 4) {
            var img = '<center><img src="gui/ajax-loader3.gif"></center>'; 
            
            if(inner.innerHTML  != img) inner.innerHTML = img;
        }
        
        // catch return
        else {
            
            if(XMLhttp.responseText == 'true') { // succ
                
                var content = '<center>Thay doi password hoan tat</center>';
                inner.innerHTML = content;
                location.href   = 'redirect.html';
                
            }  else { // catch error
            
                var content = '<center style="color:red;">Co loi xay ra. Password cua ban khong khop voi password trong CSDL.</center>';
                inner.innerHTML = content;
                
            }
            
        }
    }
    
    
    // sending information
    var url = 'Ajax_script/changePassword.ajax.php?old={old}&new={new}&tmp={random}';
    
    url     = url.replace('{old}', encodeURIComponent(oldpassword));
    url     = url.replace('{new}', encodeURIComponent(newpassword));
    url     = url.replace('{random}', Math.random());
    
    XMLhttp.open('GET', url, true);
    XMLhttp.send(null);
    
    
    return true;
}