(function(){
    var launchLoginCheck = function(){
        new Ajax.Request("/gu/IsSessionAlive.html", {
            method: "get",
            onSuccess: function(transport){
                var apiResponse = transport.responseText.evalJSON(true);
                if (apiResponse.isSessionAlive == true) {
                    Lightview.hide();
                    $("sign-in-link-map").update("SIGN OUT");
                    $("main-header-my-account-container").appear();
                }
                else {
                    if ($("lightview").visible()) {
                        window.setTimeout(launchLoginCheck, 1000);
                    }
                    else {
                    }
                }
            },
            onFailure: function(transport){
                window.setTimeout(launchLoginCheck, 1000);
            },
            onException: function(transport){
                window.setTimeout(launchLoginCheck, 1000);
            }
        });
    }
    document.observe("dom:loaded", function(e){
		document.observe(gg.UserEvent.UserLoggedIn, function(e) {
			gg.log("%o", e);
			$("sign-in-link-map").update("SIGN OUT");
			$("main-header-my-account-container").appear();
		});
		
		new Ajax.Request("/gu/IsSessionAlive.html", {
            method: "get",
            onSuccess: function(transport){
                var apiResponse = transport.responseText.evalJSON(true);
                if (apiResponse.isSessionAlive == true) {
                    Lightview.hide();
                    $("sign-in-link-map").update("SIGN OUT");
                    $("main-header-my-account-container").appear();
                }
            },
        });
		
        $("sign-in-link-map").observe("click", function(e){
            e.stop();
            if (e.element().innerHTML == "SIGN OUT") {
				FB.logout(function(response) {
					gg.log("FB logout response is %o", response);
					new Ajax.Request("/gu/LogOut.html", {
                    onSuccess: function(transport){
                        $("sign-in-link-map").update("SIGN IN");
                        $("main-header-my-account-container").fade();
                    },
                    onFailure: function(transport){
                    },
                    onException: function(transport){
                    }
                });	
				});
                
            }
            else {
				/*
                Lightview.show({
                    href: String.format("https://$0/gu/loggedin.html", document.location.host),
                    options: {
                        width: 430,
                        height: 410,
                        menubar: false,
                        topclose: true
                    }
                });
                window.setTimeout(launchLoginCheck, 1000);
                */
				gg.userWantsToLogIn2();
            }
        })
    })
})();



