// Declare namespaces
var UserAdmin = {};
UserAdmin.Common = UserAdmin.Common || {};

(function(UA) {
    UA.handlerPath = 'handlers/useradmin/';
    
    UA.nameSpace = function(name, obj) {
        var i = name.indexOf('.'), o = obj || UA;
        var pre = name, suf = '';
        if(i > -1) {
            pre = name.substring(0, i);
            suf = name.substr(i+1);
        }
        o[pre] = o[pre] || {};
        if(suf) {
            UA.nameSpace(suf, o[pre]);
        }
    };
	
    UA.Common.format = {
        date: function(val) {
            if(val && val.getDate) { return (val.getMonth() + 1) + '/' + val.getDate() + '/' + val.getFullYear(); } 
            else { return ''; }
        },
        time: function(val) {
            if(val && val.getDate) {
                var dt = val.clone(); // need to clone a new object because we need to do date math and don't want to affect the underlying value.
                dt = dt.add('MINUTE', dt.getTimezoneOffset());
                var mins = dt.getMinutes(), hours = dt.getHours(), ampm = 'AM';
                if(mins < 10) { mins = '0' + mins; }
                if(hours === 0) { hours = 12; } 
                else if(hours >= 12) {
                    if(hours > 12) { hours -= 12; }
                    ampm = 'PM';
                }
                return hours + ':' + mins + ' ' + ampm;
            } else {
                return '';
            }
        },
        datetime: function(val) {
            return UA.Common.format.date(val) + ' ' + UA.Common.format.time(val);
        }
    };
    
    UA.defaultUrl = 'Default.aspx';
    UA.logout = function(redirectUrl) {
        $.ajax({
            url: UA.handlerPath + 'authenticate.ashx',
            type: 'GET',
            data: { logout:true },
            dataType: 'text',
            cache: false,
            success: function(text) {
                if(text && text === 'logged out') {
                    window.location.href = redirectUrl || UA.defaultUrl;
                }
            }
        });
    };
    
    var _userInfo;
    UA.getUserInfo = function() {
        if(_userInfo === undefined) {
            $.ajax({
                url: UA.handlerPath + 'authenticate.ashx',
                async: false,
                type: 'GET',
                dataType: 'json',
                cache: false,
                success: function(resp) {
                    if(resp && resp.authenticated) {
                        _userInfo = resp;
                    } else {
                        _userInfo = null;
                    }
                }
            });
            return _userInfo;
        } else {
            return _userInfo;
        }
    };
})(UserAdmin);