/**
 * UserInfoModule
 * @author Jae Cho
 * Represents a module displays logged-in user information on the page naviagation.
 *
 * @dependencies
 * CookieUtil,
 */
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(this._register);
            this._cont.find(".uimLoginLink").click(this._login);
        }

        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(this._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();
    };

    this._login = function() {

        if (this._isExternal) {
            top.location="/?pageAction=showLoginPopup&redirect="
                    + top.location.pathname;
        } else {
            var module = g_page.getModule("LoginModule");
            module.login();
          }
    };
    this._logout = function() {
        var module = g_page.getModule("LoginModule");
        module.logout();
    };
    this._register = function() {
        if (this._isExternal) {
            top.location="/?pageAction=showRegisterPopup&redirect="
                    + top.location.pathname;
       } else {
          var module = g_page.getModule("RegisterModule");
          module.register();
       }
    };


    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()) this._logout();
        var reqs = [ { "methodName" : "profileService.getNumNotifications", "userId" : this._uid } ];
        this._page.makeModuleAjaxCall(this, reqs);
    };

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

		if ( typeof g_page.useFacebook != 'undefined' && g_page.useFacebook ) {
			this._cont.find("#uimLoggedOutFB").show();
		} else {
        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()) this._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();

