//
// Class: Auth
// Description: Implements a client side proxy to access the BET central authorization service.
// Date: 8/6/2008


BET.registerNamespace("BET.js.services");

BET.js.services.Auth =  function(config) {

    var _private = {
            
        url : config.context.urlFromServiceRoot('/WebApplications/ProfileMigration/AuthService.aspx'),
        
        buildErrorResponse : function(response) {
            
            if(typeof(response.error) == 'object') {
                    
                response = {
                  
                    status : response.error.status,
                    authToken : null,
                    fluxData : null,
                    externalAuth : null
                    
                };
            
            }
            else {
                
                response = {
                  
                    status : response.error,
                    authToken : null,
                    fluxData : null,
                    externalAuth : null
                    
                };
                
            }
            
            return response;
            
        },
        
        handleExtAuth : function(response, success, fail) {
            
            //holds onto the loaded state of a frame
            var frameLoaded = [];
            
            //local function that returns true if all frames have been loaded, false otherwise
            var checkFrames = function() {
                
                var loaded = true;
                
                for(f = 0; f < response.externalAuth.length; f++) {
                    
                    loaded = loaded && frameLoaded[f];
                    
                    if(!loaded)
                        break;
                    
                }
                
                return loaded;
                
            };                         
            
            //every external authorization url needs to be hit so that any tokens can be written to the client's
            //browser
            jQuery.each(response.externalAuth,
                function(i, val) {
                    
                    frameLoaded[i] = false;
                    jQuery('body').append('<iframe style="width: 0px; height: 0px; border: 0px;" id="betjsservicesauth' + i + '" class="betjsservicesauth" src="' + val + '"></iframe>');
                        
                    jQuery('iframe#betjsservicesauth' + i).load(function() { frameLoaded[i] = true; });
                    
                }                                
            );
            
            //we now wait until all external authframes have been loaded, or until timeout occurs
            var waitTimeout = 10000;
            var waited = 0;                            
            var waitForExtAuth = function() {
                
                if(checkFrames) {
                    
                    //we have it
                    clearInterval(intervalID);
                    //setTimeout("jQuery('iframe.betjsservicesauth').remove()", 200);
                    success(response);
                    
                }
                else {
                    
                    if(waited < waitTimeout) {
                        
                        //wait more
                        waited = waited + 20;
                        
                    }
                    else {
                        
                        clearInterval(intervalID);
                        //setTimeout("jQuery('iframe.betjsservicesauth').remove()", 200);
                        //waited exceeds timeout so fail
                        if(typeof(fail) == "function") {
                            fail({
                                
                                status : "Login request has failed since it has exceeded the timeout",
                                authToken : null,
                                fluxData : null,
                                externalAuth : null
                                
                            });
                        }
                        
                    }
                    
                }
                
            };
            
            intervalID = setInterval(waitForExtAuth, 20);
            
        }
        
    };
        
    return {
        
        login : function(args) {            
            
            BET.js.JsonRPC.invoke(_private.url, "login", [{ username : args.username, password : args.password }],
            
                //function executed when the invoke completes
                function(response) {
                
                    if(response.error != null) {
                        
                        //some type of error condition has occured
                        response = _private.buildErrorResponse(response);
                        
                        //marshal a call to the failure callback if one as been specified
                        if(typeof(args.fail) == "function")
                            args.fail(response);
                        
                    }
                    else {                
                        
                        //we are assuming a successfuly login so far
                        if(typeof(args.success) == "function") {
                            
                            _private.handleExtAuth(response, args.success, args.fail);
                            
                        }
                        
                    }
                    
                }
            
            );
            
        }
        
        ,
        
        logout : function(args) {
            
            BET.js.JsonRPC.invoke(_private.url, "logout", [],
                
                //function executed when the invoke completes
                function(response) {
                    
                    if(response.error != null) {
                        
                        //some type of error occured
                        response = _private.buildErrorResponse(response);
                        
                        if(typeof(args.fail) == "function")
                            args.fail(response);
                        
                    }
                    else {
                     
                        if(typeof(args.success) == "function") {
                            
                            _private.handleExtAuth(response, args.success, args.fail);
                            args.success(response);
                            
                        }
                        
                    }                    
                
                }
                
            );
            
        }
    
    };
};
