/**
 * AddFriendModule
 * @author Jae Cho
 * Subclass of Module that handles adding friend.
 * @dependencies
 * LoginModule - redirect to current page with friend action
 */
function AddFriendModule()
{

    /** name of this module */
    this._name = AddFriendModule.NAME;

    this._userName = null;

    this._userId = null;

    this._userPicSet = false;
    /** additional info is needed to send friend request */
    this._moreInfo =  AddFriendModule.MORE_INFO_NONE;
    this._infoEmail = null;
    this._infoFirstName = null;
    this._infoLastName = null;

    /** module container */
    this._addDlgCover = null;
    this._confDlgCover = null;
    this._moreInfoDlgCover = null;
    this._addDlgCommentCover = null;

    /** module container controls */
    this._addDlgCoverControl = null;
    this._confDlgCoverControl = null;
    this._moreInfoDlgCoverControl = null;
    this._addDlgCommentCoverControl = null;


    /** callback method - called when add friend req is made */
    this._callbackFunc = null;

    /** @return list of request actions that can be handled by this module */
    this.getPageActionNames = function()
    {
       return [ "addFriend" ];
    }

    /** handle request action
    * @action name of action to invoke
    * @params bean containing request parameters
    *
    * */
    this.handlePageAction = function(action, params)
    {
        if (action == "addFriend") {
            this.showAddDialog(parseInt(params._userId), params._userName, params._moreInfo);
        }
    }

    /**
     * called by the page during initialization
     */
    this.initialize = function()
    {
        this._addDlgCover = $("#afmDialog");
        this._confDlgCover = $("#afmConfDialog");
        this._moreInfoDlgCover = $("#afmMoreInfoDialog");
        this._addDlgCommentCover = $("#afmCommentDialog");

        this._addDlgCoverControl = new DialogControl("#afmDialog");
        this._confDlgCoverControl = new DialogControl("#afmConfDialog");
        this._moreInfoDlgCoverControl = new DialogControl("#afmMoreInfoDialog");
        this._addDlgCommentCoverControl = new DialogControl("#afmCommentDialog");

        // bind events with add dialog
        this._addDlgCover.find("#dlgAddButton").bind("click", this, function(e) {
            e.preventDefault();
            var module = e.data;
            module._makeFriendRequest();
        });

        this._addDlgCover.find("#dlgCancelButton").bind("click", this, function(e) {
            e.preventDefault();
            var module = e.data;
            $(".errorMsg").hide();
            module._addDlgCoverControl.hideDialog();
        });

         this._addDlgCommentCover.find("#cmFrndDlgYesButton").bind("click", this, function(e) {
            e.preventDefault();
            var module = e.data;
            module._makeFriendRequest();
        });

        this._addDlgCommentCover.find("#cmFrndDlgNoButton").bind("click", this, function(e) {
            e.preventDefault();
            var module = e.data;
            $(".errorMsg").hide();
            module._addDlgCommentCoverControl.hideDialog();
        });

        // bind events with conf dialog
        this._confDlgCover.find("#dlgOkButton").bind("click", this, function(e) {
            e.preventDefault();
            var module = e.data;
            $(".errorMsg").hide();
            module._confDlgCoverControl.hideDialog();
        });

        // bind events for more info dialog
        this._moreInfoDlgCover.find("#afmAddButton").bind("click", this, function(e) {
            e.preventDefault();
            var module = e.data;
            module._infoEmail = module._moreInfoDlgCover.find("#afmEmail").val();
            module._infoFirstName = module._moreInfoDlgCover.find("#afmFirstName").val();
            module._infoLastName = module._moreInfoDlgCover.find("#afmLastName").val();

            if (!module._infoEmail && !(module._infoFirstName && module._infoLastName)) {
                module._moreInfoDlgCover.find(".error:first").html("Please enter the user's info");
                module._moreInfoDlgCover.find(".errorMsg").show();
                return;
            }
            
            module._makeFriendRequest();
        });

        this._moreInfoDlgCover.find("#afmCancelButton").bind("click", this, function(e) {
            e.preventDefault();
            var module = e.data;
            $(".errorMsg").hide();
            module._moreInfoDlgCoverControl.hideDialog();
        });
    }



    /**
     * @param callbackArg - argument to call back
     * @param callback - method to call once a friend request has been sent.
     */
    this.setCallback = function(callbackFunc) {
        this._callbackFunc = callbackFunc;
    }
   this.getCallback = function() {
        return this._callbackFunc;
    }

    /**
     * show add to friend dialog for a user. set needed values and performs validation for login
     * @param userId - you know what this is.
     * @param userName
     * @param moreInfo - MORE_INFO_ value
     * @param useName - true if name and email input is to be shown
     */
    this.showAddDialog = function(userId, userName, moreInfo,userPicSet)
    {
        this._userName = userName;
        this._userId = userId;
        this._moreInfo = moreInfo;
        if (userPicSet){
            this._userPicSet = userPicSet;
        }

        var loggedInUid = this._page.getLoggedInUserId();
        if (!loggedInUid) {
            var args = { "headerMessage" : "Log in to be " + userName + "'s friend" };
            LoginModule.showLogin(args);
        } else{
            this._showAddDialog();
        }
    }

    this.showAddComment = function(userId, userName, moreInfo){
        this._userName = userName;
        this._userId = userId;
        this._moreInfo = moreInfo;

        var loggedInUid = this._page.getLoggedInUserId();
        if (!loggedInUid) {
            var args = { "headerMessage" : "Log in to be " + userName + "'s friend" };
            LoginModule.showLogin(args);
        }else{
           this._showCommentsAddDialog();
        }
    }
    /**
     * implement showing
     */
    this._showAddDialog = function()
    {
        if (this._moreInfo == AddFriendModule.MORE_INFO_NONE) {
            this._addDlgCover.find(".error").html("");
            this._addDlgCover.find(".afmUsername").html(this._userName);
            this._addDlgCover.find(".dialoguePic").html(
                    "<img src='" + ProfileUtil.getImg({userId: this._userId, userPicSet: this._userPicSet, size:"small"}) + "'/>");
            this._addDlgCoverControl.showDialog();
            return;
        }

        if (this._moreInfo == AddFriendModule.MORE_INFO_EMAIL) {
            this._moreInfoDlgCover.find("#afmMoreInfoDesc").html(
                "<span class='user_name'>" + this._userName + "</span> only receives friend requests from people he/she knows.<br/><br/> \
              You must enter <span class='user_name'>" + this._userName + "'s</span> email address in order to send your request.");
            this._moreInfoDlgCover.find("#afmMoreInfoNameCover").hide();
        } else if (this._moreInfo == AddFriendModule.MORE_INFO_EMAIL_OR_NAME) {
            this._moreInfoDlgCover.find("#afmMoreInfoDesc").html(
                "<span class='user_name'>" + this._userName + "</span> only receives friend requests from people he/she knows.<br/><br/> \
              You must enter <span class='user_name'>" + this._userName + "'s</span> first and last name or email address in \
              order to send your request.");
            this._moreInfoDlgCover.find("#afmMoreInfoNameCover").show();
        }         
        this._moreInfoDlgCover.find(".error").html("");
        this._moreInfoDlgCover.find("#afmEmail").val("");
        this._moreInfoDlgCover.find("#afmName").val("");
        this._moreInfoDlgCover.find(".afmUsername").html(this._userName);
        this._moreInfoDlgCover.find(".dialoguePic").html("<img src='" + ProfileUtil.getImg({userId:this._userId, userPicSet: this._userPicSet, size:"small"}) + "' />");
        this._moreInfoDlgCoverControl.showDialog();
    };

    this._showCommentsAddDialog = function(){
          this._addDlgCommentCover.find(".error").html("");
          this._addDlgCommentCover.find(".afmUsername").html(this._userName);
          this._addDlgCommentCoverControl.showDialog();
    }

    /** make friend request */
    this._makeFriendRequest = function()
    {
        var req = { "methodName": "profileService.addFriend", "userId" : this._userId };

        if (this._infoEmail) req["email"] = this._infoEmail;
        if (this._infoFirstName && this._infoLastName) {
            req["firstName"] = this._infoFirstName;
            req["lastName"] = this._infoLastName;
        }
        this._page.makeModuleAjaxCall(this, [req]);
    };

    /** */
    this._handleAddFriendRes = function(response)
    {
        if (response["result"] != "Ok") {
            if (this._moreInfo == AddFriendModule.MORE_INFO_NONE) {
                this._addDlgCover.find(".error").html(response.message);
                this._addDlgCover.find(".errorMsg").css("display","block");
            } else {
                this._moreInfoDlgCover.find(".error").html(response.message);
                this._moreInfoDlgCover.find(".errorMsg").css("display","block");
            }
            return;
        }

        //put username in confirmation dialog
        this._confDlgCover.find(".afmUsername").html(this._userName);
                   

        // hide add dialog
        this._moreInfoDlgCoverControl.hideDialog();
        this._addDlgCoverControl.hideDialog();
        this._addDlgCommentCoverControl.hideDialog();
        this._confDlgCoverControl.showDialog();

        // make the call back function invocation
        if (this._callbackFunc) this._callbackFunc();
    }



    /** handle AJAX response object */
    this.handleResObjects = function(resObjects) {
        for (var i = 0; i < resObjects.length; i++) {
            var res = resObjects[i];
            if (res.methodName == "profileService.addFriend") this._handleAddFriendRes(res.response);
        }
    }
}

 /**
 * determine the extra information needed to add a user as friend
 * @param profile
 * @return profile more info type
 */
AddFriendModule.getNeededInfo = function (profile)
{
    if (profile.needInfoToFriend ){
         if (profile.nameSet) return AddFriendModule.MORE_INFO_EMAIL_OR_NAME;
         else  return AddFriendModule.MORE_INFO_EMAIL;
    }
    else return AddFriendModule.MORE_INFO_NONE;
};


AddFriendModule.NAME = "AddFriendModule";

AddFriendModule.MORE_INFO_NONE = "none";

AddFriendModule.MORE_INFO_EMAIL = "email";

AddFriendModule.MORE_INFO_EMAIL_OR_NAME = "emailOrName";

AddFriendModule.prototype = new Module();

