/**
 * UserInfoModule
 * @author Jae Cho
 * Represents a module displays logged-in user information on the page naviagation.
 *
 * @dependencies
 * dojo
 * CookieUtil,
 * ag.widget.user
 * ag.widget.user.LoginPopup (dojo)
 */
function UserInfoModule()
{
    this._name = UserInfoModule.NAME;

    /**  external page object   */
    this.external_page=null;


    /** profile path - set when logged in */
    this._profilePath = null;

    /** user id  - set when logged in */
    this._uid = null;

    /** set interval id */
    this._intervalId = null;

    this._rotatingMsgs = [
        "Create Your Own AG Profile",
        "Play Games with Friends",
        "Save Your Favorite Games",
        "Save Your High Scores"];

    /**
     * true if this module is on external page. In that case,
     * login/register should redirect to the AG home page
     */
    this.setExternal = function() {
        this._isExternal = true;
    };

    this.initialize = function()
    {
        this._cont = $("#userInfoMod");

		if(window.external_page){
			this.external_page=window.external_page;
		}

        // logged out controls
        if(window.external_page && this.external_page.page_status==1){
            $('#uimRegisterLink').html("<a href='"+ this.external_page.register_link +"' target='_top'>Join Now-IT'S FREE!</a>");
            $('#uimLoginLink').html("<a href='"+ this.external_page.login_link +"' target='_top'>Login</a>");
        }else{
            this._cont.find("#uimRegisterLink").click(ag.widget.user.RegisterPopup.showPopup);
            this._cont.find("#uimLoginLink").click(ag.widget.user.LoginPopup.showPopup);
        }

        var random = Math.floor(Math.random() * 4);
        this._cont.find("#uimRegMsgLink")
                .html(this._rotatingMsgs[random])
                .click(bindContext(this, this._register));

        this._cont.find("#uimLoginLink").click(bindContext(this, this._login));
        this._cont.find("#add_your_pic").click(bindContext(this, this._register));
        this._cont.find("#uimLoggedOutCover").find(".user_icon").click(bindContext(this, this._register));

        // logged in controls
        this._cont.find("#uimLogoutLink").click(ag.user.logout);

        this._cont.find("#uimProfileLink").bind("click", this, function(e) {
            var module = e.data;
            window.location = "/profile/" + module._profilePath;
        });

        this._cont.find("#uimProfileImgLink").bind("click", this, function(e) {
            var module = e.data;
            window.location = "/profile/" + module._profilePath;
        });

        this.updateAndGetLoginChangeRequests();


         // ------------------------------------
        // Show an upgrade message to IE 6 users
        // ------------------------------------

        // if the user has not previously closed the upgrade message and a reskin is not active and reskinIsActive is not true and the browser is IE6 or less, show it
        if ( ( $.cookie("swHideIE6Upgrade") != "true")  && ( typeof reskinIsActive == "undefined" ) && (typeof document.body.style.maxHeight === "undefined") && $(".brand-mamabar").length ) {
            $("body").css({backgroundPosition: "center 80px"});
            $(".brand-mamabar").after("<div id='ie6Upgrade'><div><h3>You are using an outdated browser<\/h3><p>For a better experience using this site please upgrade to a modern web browser. It's quick, it's easy, and it's safe!<\/div><\/div>");
            $("#ie6Upgrade div").append("<ul><li><a href='http://firefox.com/' target='_new' onclick='sendLinkEvent( \"ie6-upgrade-to-firefox\" );' class='clearLink b-ff'><\/a><\/li><li><a href='http://www.microsoft.com/windows/internet-explorer/default.aspx' target='_new' onclick='sendLinkEvent( \"ie6-upgrade-to-ie8\" );' class='clearLink b-ie'><\/a><\/li><li><a href='http://www.apple.com/safari/' target='_new' onclick='sendLinkEvent( \"ie6-upgrade-to-safari\" );' class='clearLink b-sf'><\/a><\/li><\/ul>");
            $("#ie6Upgrade div").append("<a href='#' onclick='sendLinkEvent( \"ie6-upgrade-dismissed\" );' class='icon16Lft icon16Close clearLink'><\/a>");
        }

        //close the ie6upgrade bar
        $("#ie6Upgrade .icon16Close").live("click", function(){
            $("#ie6Upgrade").hide();
            $("body").css({backgroundPosition: "center 20px"});
            //user has clicked the close button, don't show again for 30 days
            var cookieOptions = { path: '/', domain: '.addictinggames.com', expires: 30 };
            $.cookie("swHideIE6Upgrade", "true", cookieOptions);
            return false;
        });
    };

    this._login = function() {

        if (this._isExternal) {
            top.location="/?pageAction=showLoginPopup&redirect="
                    + top.location.pathname;
        } else {
            ag.widget.user.LoginPopup.showPopup();

}
    };

    this._register = function() {
        if (this._isExternal) {
            top.location="/?pageAction=showRegisterPopup&redirect="
                    + top.location.pathname;
       } else {
           ag.widget.user.RegisterPopup.showPopup();
       }
    };


    this.updateAndGetLoginChangeRequests = function() {
        // logged in controls
        var uid = this._page.getLoggedInUserId();
        if (uid == this._uid) return;

        this._uid = uid;
        if (this._uid) this._updateForLoggedInUser();
        else this._updateForLoggedOutUser();

        return [];
    };

    this._updateForLoggedInUser = function() {
        var reqs = [
            { "methodName" : "profileService.getFullProfile", "userId" : this._uid },
            { "methodName" : "profileService.getNumNotifications", "userId" : this._uid }
        ];

        this._page.makeModuleAjaxCall(this, reqs);

        var boundUpdateMethod = bindContext(this, this._updateNumNotif);
        this._intervalId = setInterval(boundUpdateMethod, 60000);
    };

    this._updateNumNotif = function() {
        if (!this._page.getLoggedInUserId()) ag.user.logout();
        var reqs = [ { "methodName" : "profileService.getNumNotifications", "userId" : this._uid } ];
        this._page.makeModuleAjaxCall(this, reqs);
    };

    this._updateForLoggedOutUser = function() {
        this._cont.find("#uimLoggedInCover").hide();
        this._cont.find("#uimLoggedOutCover").show();

        $("#subnavProfilePgLink").click(bindContext(this, this._login));
        $("#subnavFriendsPgLink").click(bindContext(this, this._login));
        $("#subnavFavGamesPgLink").click(bindContext(this, this._login));
        $("#subnavHsGamesPgLink").click(bindContext(this, this._login));
        $("#subnavMyAccountLink").click(bindContext(this, this._login));
    };

    this._updateProfileNav = function(profile) {
        $("#subnavProfilePgLink").attr({href: "/profile/" + profile.profilePath, target:"_top"});
        $("#subnavFriendsPgLink").attr({href: "/profile/friendsPage.php?userId=" + profile.userId, target:"_top"});
        $("#subnavFavGamesPgLink").attr({href: "/static/php/account/myFavoritesPage.php", target:"_top"});
        $("#subnavHsGamesPgLink").attr({href: "/profile/highScoresPage.php?uuid=" + profile.uuid, target:"_top"});
        $("#subnavMyAccountLink").attr({href: "/static/php/account/myAccountPage.php", target:"_top"});
    };

    this._handleProfileRes = function(profile) {
        this._cont.find("#uimProfileLink").attr({href: "/profile/" + profile.profilePath, target: "_top"});
        this._cont.find("#uimProfileImgLink").attr({href: "/profile/" + profile.profilePath, target: "_top"});
        this._cont.find("#uimGreeting").html("Hello, <a target='_top' href='/profile/" + profile.profilePath+"'>" + profile.userName + "</a>!");

        this._cont.find("#uimLoggedInCover").show();
        this._cont.find("#uimProfileImg").attr("src", ProfileUtil.getImg({userId: this._uid,size:"mini",userPicSet: profile.userPicSet}));
        this._cont.find("#uimLoggedOutCover").hide();

        this._updateProfileNav(profile);
    };

    this._handleNumNotifications = function(numNotifs) {
        if (!this._page.getLoggedInUserId()) ag.user.logout();
        this._cont.find("#uimNumNotifs").html(" (" + numNotifs + ")");
    };

    /** handle AJAX response object */
    this.handleResObjects = function(resObjects) {
        for (var i = 0; i < resObjects.length; i++) {
            var res = resObjects[i];
            if (res.methodName == "profileService.getFullProfile") {
                this._handleProfileRes(res.response.profile);
            } else if (res.methodName == "profileService.getNumNotifications") {
                this._handleNumNotifications(res.response.total);
            }
        }
    };
}

UserInfoModule.NAME = "UserInfoModule";

UserInfoModule.prototype = new Module();



