NickLog.debug('authenticationWidget.js');



KIDS.flux = {};
(function($){
    KIDS.flux.username = "";
    KIDS.flux.populateNametag = function(context){
        if(context.user){
            if(!$.cookie('RtxAuth2407')){ KIDS.flux.authenticationWidget.onSignInRefresh(); }
            KIDS.flux.username = context.user.displayName;
           	KIDS.flux.shortUsername = (KIDS.flux.username.length > 26)?KIDS.flux.username.substring(0,23) + "..." : KIDS.flux.username;
            $(".usernameLink").html(KIDS.flux.shortUsername);
            $(".userAvatar").attr("src",context.user.avatarUrls['70x70']);
        } else {
        	if($.cookie('RtxAuth2407')){
        		KIDS.flux.cleanupCookiesAndReload();
        	}
        }
    };
    KIDS.flux.cleanupCookiesAndReload = function(){
        KIDS.flux.killBNWFavoriteNamesCookie();
        KIDS.flux.crumbleCookies();
        location.href = 'http://' + location.host + '/';
    };
    KIDS.flux.killBNWFavoriteNamesCookie = function () {//I'm not sure why this was abstracted into a function since it only appears to be called once but I'm going to leave it this way just so it's a little clearer what this code does.
        var name = 'bnw_favorite_names';
        var value = '';
        var cdays = -7;
        var domain = window.location.host.toString().substring(window.location.host.toString().indexOf('.'));
        var path = '/';
        var expire = new Date();
        expire.setTime(expire.getTime() + (3600000 * 24 * cdays));
        document.cookie = name + "=" + escape(value) +
        ((expire == null) ? "" : "; expires=" + expire.toGMTString()) +
        ((path == null)   ? "" : "; path=" + path) +
        ((domain == null) ? "" : "; domain=" + domain);
    };
    //this redirect to login_sync which syncs the flux cookie with the subdomains(gck,3dp,bnw). login_sync then grabs the "ReturnUrl" cookie and redirects back to there
    //eventually I would like to see the default onSignIn drop this redirect and allow the callback in roadblockFunction to control which pages get refreshed...
    KIDS.flux.crumbleCookies = function(){//If you understand what this is for, a comment here would be helpful...
    	//there are two cookies set (at least on relaunch): .relaunch.nickjr and .nickjr, this will remove them both */
        $.cookie('RtxAuth2407', null, { domain: '.' + location.host, path: '/', expires: -1});
        $.cookie('RtxAuth2407', null, { domain: KIDS.flux.cookieDomain(), path : '/', expires: -1});
    };
   KIDS.flux.cookieDomain = function(){
       var loc = null;
       if (location.host.indexOf('.') != -1) {
           var temp = location.host.split('.');
           temp.splice(0,1);
           loc =  '.' + temp.join('.');
       }
       return loc;
   }
   KIDS.flux.authenticationWidget = {
        onSignOutHasFired: false,//this is a hack beacuse onSignOut is not firing
        forceOnSignOut: function(){
            if(!KIDS.flux.authenticationWidget.onSignOutHasFired){
                KIDS.flux.authenticationWidget.onSignOut();
            }
        },
        onSignOut: function(){
            KIDS.flux.authenticationWidget.onSignOutHasFired = true;
            KIDS.flux.cleanupCookiesAndReload();
        },
        onSignIn: function(){
            //a callback that just changes the nametag
            Flux.loadContext(function(context){
                KIDS.flux.populateNametag(context);
                $("#notAMemberNametag").css("display","none");
                $("#loggedOutNametag").css("display","none");
                $("#loggedInNametag").css("display","block");
            });
        },
        onSignInRefresh: function(){
            //a callback that will refresh the entire page
        	// let's make sure we can even load cookies
            $.cookie('ReturnUrl', location.href, {domain: KIDS.StageVars.mainDomain, path: '/', raw: true});
            if($.cookie('ReturnUrl')){
            	location.href = KIDS.StageVars.fluxAuth + '/-/GetAuthCookie.ashx?returnUrl=http://' + KIDS.StageVars.pcDynabossDomain + "/flux/login_sync.jhtml";
            } else {
            }
        },
        inPageCookieSneak: function(callbackName){
        	$('#nametagDepository').append('<iframe height="0" width="0" src="http://widgets.flux.com/-/GetAuthCookie.ashx?'+
        			'returnUrl=http%3a%2f%2f' + window.location.host + '%2fassets%2fspacer.gif" ' +
        			'onload="KIDS.flux.authenticationWidget.parseAndSetCookie(this.contentWindow.location.href, this.contentWindow.location.search, function(){' 
        			+ callbackName + '();});"/>')
        },
        parseAndSetCookie: function (href, search, callback){
        	// do a better job with this
        	var qsa = search.replace("/^?/","");
        	var splits = qsa.split('&');
        	for(i=0;i<splits.length;i++){
        		if(splits[i].indexOf("authCookie=")>-1){
        			var keyVal=splits[i].split('=');
        			$.cookie('RtxAuth2407', keyVal[1],{ domain: KIDS.flux.cookieDomain(), path : '/'});
        			callback();
        		}
        	}
        },
        facebookConnect : function(){
        	Flux.createWidget('Rpx', {}, function(widget) { widget.connectWith('Facebook') } );
        },
        createSignInWidget: function(){
            Flux.createWidget('Authentication', {}, function (widget) {
                widget.showSignInForm();
                document.getElementById('authenticationFrame').allowTransparency = true;
            });
        },
        createSignUpWidget: function(){
            Flux.createWidget('Authentication', {}, function (widget) {
                widget.showSignUpForm();
                document.getElementById('authenticationFrame').allowTransparency = true;
            });
        },
        createInterimWidget: function() {
            Flux.createWidget('Authentication', {}, function (widget) {
                widget.showInterimForm();
                document.getElementById('authenticationFrame').allowTransparency = true;
            });
        },
        extractUserLoginName: function(){//kept to support legacy code
            return KIDS.flux.username;
        },
        /*** roadblockFunction params ***
        shouldReloadOnLogin: if true, page will refresh itself after sign in
        callback: eventually, this should be used for more complex functionality. ie refreshing certain elements on the page rather than the entire page.
        settings:this is so we can pass settings to Flux.createWidget which is needed to fix a bug that occurs when calling Flux.createWidget in $.safeDocumentReady.add
        */
        // TODO - This function makes no sense and has been perverted from its original form 
        roadblockFunction: function(callback,shouldReloadOnLogin,settings){
            settings = settings || {};
            Flux.loadContext(function(context){//calling widget.performRoadBlockerCheck may trigger a signup so we need to attach the callback hefirst
                Flux.createWidget('Authentication', settings, function (widget) {
                    if(widget.performRoadBlockerCheck()){
                        if(!$.cookie('RtxAuth2407')){ KIDS.flux.authenticationWidget.onSignInRefresh(); }
                    }else{
                        //user is being shown a login overlay
                        if(callback){
                            context.onSignIn = callback;
                        }else if(shouldReloadOnLogin){
                            context.onSignIn = KIDS.flux.authenticationWidget.onSignInRefresh;
                        }
                    }
                });
            });
        },
        inPageRoadblockFunction: function(callback,settings){
            settings = settings || {};
            Flux.loadContext(function(context){
                Flux.createWidget('Authentication', settings, 
                	function (widget) {
                		if(widget.performRoadBlockerCheck()){
                			callback();
                		}else{
                			//user is being shown a login overlay
                			if(callback){
                				context.onSignIn = function() {
                					KIDS.flux.authenticationWidget.inPageRoadblockCallback = 
                						function(){
            							Flux.loadContext(function(innerContext){
            								if(innerContext.user != null){ 
            									callback();
            									KIDS.flux.authenticationWidget.onSignIn();
            								} else {
            									alert("Couldn't sneak the user");
            								} 
            							});
            						};
                					KIDS.flux.authenticationWidget.inPageCookieSneak('KIDS.flux.authenticationWidget.inPageRoadblockCallback');
                				};
                			}
                        }
                    }
                );
            });
        },
        /** roadblockFunctionTopNav
         * @author thomatop
         * unfortunately this needs to be a separate copy of roadblockFunction
         * because roadblockFunction triggers if(widget.performRoadBlockerCheck()){
         * on complete which wont refresh the window even if you have shouldReloadOnLogin
         * since it never makes it to that block statement did not want to modify the above
         * code since it might break something else
         */
        roadblockFunctionTopNav: function(){
        	Flux.reloadWidgets();
        	Flux.loadContext(function(context){//calling widget.performRoadBlockerCheck may trigger a signup so we need to attach the callback first
				context.onSignIn = KIDS.flux.authenticationWidget.onSignInRefresh;
				context.performRoadBlockerCheck();
            });
        }
    }

    $.safeDocumentReady.add(function(){
    	if(KIDS.StageVars.useSocialMedia4Features == 'true'){
    		return;
    	}
        KIDS.flux.populateNametag(Flux.context);
        if(!Flux.context.user){//not logged in
            $("#loggedOutNametag").css("display","block");
        }else if(Flux.context.user.communityMember){
            $("#loggedInNametag").css("display","block");
        }else{//logged in but not a member
            $("#notAMemberNametag").css("display","block");
        }
        $('#loginInitUser').click(function(ev) {
            ev.preventDefault();
            if (Flux.context.user && !Flux.context.user.communityMember) {
                KIDS.flux.authenticationWidget.createInterimWidget();
            } else {
                KIDS.flux.authenticationWidget.createSignUpWidget();
            }
        });
        $('#signupUser').click(function(ev) {
            ev.preventDefault();
            KIDS.flux.authenticationWidget.createSignUpWidget();
        });
        $('#signinUser').click(function(ev) {
            ev.preventDefault();
            Flux.loadContext(function(context){
                context.onSignIn = KIDS.flux.authenticationWidget.onSignInRefresh;
                KIDS.flux.authenticationWidget.createSignInWidget();
            });
        });
        $('#facebookConnect').click(function(ev){ KIDS.flux.authenticationWidget.facebookConnect();});
        $('#interimUser').click(function(ev) {
            ev.preventDefault();
            KIDS.flux.authenticationWidget.createInterimWidget();
        });
        $('.logoutUser').click(function(ev) {
            ev.preventDefault();
            Flux.loadContext(function(context){
                context.onSignOut = KIDS.flux.authenticationWidget.onSignOut;
                context.signOut(false, function(error) {});
                window.setTimeout("KIDS.flux.authenticationWidget.forceOnSignOut()",3500);
            });
        });
        $(window).load(function () {
        	if (document.location.search.match(/[&?]register=true/) !== null) {
        		KIDS.flux.authenticationWidget.createSignUpWidget();
        	}
        });
    });
    //For some reason these have to be assign via the context returned by Flux.loadContext even though I would prefer to just assign them here
    //Flux.context.onSignOut = KIDS.flux.authenticationWidget.onSignOut;
    //Flux.context.onSignIn = KIDS.flux.authenticationWidget.onSignIn;
})(jQuery); // $ is overridden...probably by flux loading in prototype.js
var authenticationWidget = KIDS.flux.authenticationWidget;//to preserve code that references this as authenticationWidget instead of KIDS.flux.authenticationWidget




