/**
 * GameInvitationModule
 * @author Jae Cho
 * Subclass of Module that represents user's friends
 */
function GameInviteModule() {

    /** module name */
    this._name=GameInviteModule.NAME;
    
    /** map of user id to selection state (username if selected, null if not selected) */
    this._selectedFriends = new Object();

    /** pagination for friends */
    this._currentFriendsPage = 0;
                                               
    /** array of email invitation entries */
    this._inviteEmailEntries = null;
                  
    /** array of friends invitation entries */
    this._inviteFriendEntries= null;
    
    /** user id */
    this._userId = null;

    /** game id */
    this._gameId = null;

    /** game name */
    this._gameName = null;

    /** total number of friends */
    this._totalFriends = 0;

    /** selector that display's the dialog */
    this._inviteLink = null;

    /** number of selected friends */
    this._numSelectedFriends = 0;

    this.FRIENDS_PAGE_SIZE = 10;

    /** total number of pages; */
    this._totalPages = 0;

    this._inputDialogControl = null;
    this._confDialogControl = null;
    /** * @param gameId
     * @param gameName
     */
    /** set game informaion. */
    this.setGameInfo = function(gameId, gameName) {
        this._gameId = gameId;
        this._gameName = gameName;
        $("#gameNameSpan").html(gameName);
        $("#gameNameSpan2").html(gameName);
    }
    this._itemLoadCallback = function(){

    }
    
    this.initialize = function() {

         //Initialize the dialog modals
         this._inputDialogControl = new DialogControl("#gameInviteModInputDialog")
         this._confDialogControl = new DialogControl("#gameInviteModConfDialog")

        $("#gameInviteModSendButton").bind("click", this, function(e) {
            e.preventDefault();
            var module = e.data;
            module._sendInvitation();
        });

        $("#gameInviteModCancelButton").bind("click", this, function(e) {
             e.preventDefault();
            var module = e.data;
            module._hideInputDialog();
        });

        $("#gameInviteModOkButton").bind("click", this, function(e) {
             e.preventDefault();
            var module = e.data;
            module._hideConfDialog();
        });

        $("#gameInviteModPrevButton").bind("click", this, function(e) {
             e.preventDefault();
            var module = e.data;
            module._prevFriendPage();
        });

        $("#gameInviteModNextButton").bind("click", this, function(e) {
             e.preventDefault();
            var module = e.data;
            module._nextFriendPage();
        });

    }

    this.setUserId = function(userId) {
        this._userId = userId;
    }
    /**
     * lookup friends for the user
     * @param emails
     */
    this._getFriends = function() {
        var req = [{"methodName": "profileService.getFriends",
            "userId" : this._userId,
            "startIndex" : this._currentFriendsPage * this.FRIENDS_PAGE_SIZE,
            "resultSize" : this.FRIENDS_PAGE_SIZE}];
               // ,"order" : "name"}];

        this._page.makeModuleAjaxCall(this, req);
    }

    /** read emails from the text area, validate and send
     * @param emails
     * @return true if
     */
    this._sendInvitation = function()
    {
        var emails = $("#gameInviteModEmails").val();
        var errorMessage = "Error: You Must Enter a Valid Email Address";

        if (!this._numSelectedFriends && !emails) {
            this._handleErrorMessaging(errorMessage);
            return false;
        }

        var reqs = new Array();
        this._inviteFriendEntries = new Array();
        var j = 0;

        // send userid invites
        for (var i in this._selectedFriends) {
            if (this._selectedFriends[i]) {
                this._inviteFriendEntries[j] = new Object();
                this._inviteFriendEntries[j].userId = i;
                this._inviteFriendEntries[j].userName = this._selectedFriends[i];

                reqs.push({ "methodName" : "profileService.sendGameInvitationToUser",
                    "gameId": this._gameId, "userId" : i});
            }
            j++
        }

        // send email invites
        this._inviteEmailEntries = new Array();
        var parsedEntries = StringUtil.parseEmails(emails);

        if (parsedEntries.length > 200) {
            errorMessage = "Error: You've sent up to 200 email invitations";
            this._handleErrorMessaging(errorMessage);
            return;
        }


        for (var i = 0; i < parsedEntries.length; i++) {
            if (parsedEntries[i].status != "valid") {
                this._handleErrorMessaging(errorMessage);
                return;
            }

            this._inviteEmailEntries[i] = new Object();
            this._inviteEmailEntries[i].email = parsedEntries[i].email;

            reqs.push({ "methodName" : "profileService.sendGameInvitationToNonUser",
                "gameId" : this._gameId, "email": parsedEntries[i].email});
        }

        this._page.makeModuleAjaxCall(this, reqs);
        return false;
    }


    /** callback method - show next friends page */
    this._nextFriendPage = function() {
       if (this._currentFriendsPage < this._totalPages -1){
        this._currentFriendsPage++;
        this._getFriends();
       }

    }

    /** callback method - show previous friends page */
    this._prevFriendPage = function() {
       if (this._currentFriendsPage !=0){
        this._currentFriendsPage--;
        this._getFriends();
       }
    }

    this._updatePager =  function(){
       if(this._currentFriendsPage != 0){
           $("#gameInviteModPrevButton").addClass("on")
                   .find("img")
                   .attr("src","/static/images/dialogue_arrow_left_1.jpg");
       }else{
          $("#gameInviteModPrevButton").removeClass("on")
                  .find('img')
                  .attr("src","/static/images/dialogue_arrow_left_0.jpg");
       }
        
       if (this._currentFriendsPage != (this._totalPages -1) && this._totalPages > 1){
          $('#gameInviteModNextButton').addClass("on")
                 .find("img")
                 .attr("src","/static/images/dialogue_arrow_right_1.jpg");
       }else{
           $('#gameInviteModNextButton').removeClass("on")
                 .find("img")
                 .attr("src","/static/images/dialogue_arrow_right_0.jpg");
       }

    }
    this._handleErrorMessaging = function(msg){
        $("#gameInviteModEmailError").html("<span class='errorMsg'>"+msg+"</span>").show();
    }
    /** show input dialog */
    this.showInputDialog = function(args)
    {
        if (args) {
            if (args.userId){
                this.setUserId(args.userId);
            }else{
                 this._callLogin();
                  return;
            }
            if (args.gameId && args.gameName) {
                this.setGameInfo(args.gameId, args.gameName);
            }
        }

        this._getFriends();
        $(document).scrollTop(0); //scroll to the top
        this._inputDialogControl.showDialog();
    }

    /** hide input dialog */
    this._hideInputDialog = function() {
         this._inputDialogControl.hideDialog();
        $("#gameInviteModEmails").val(null).empty();
         $("#gameInviteModEmailError").hide();
    }

    /** show confirmation dialog */
    this._showConfDialog = function() {
        this._confDialogControl.showDialog();
        this._selectedFriends = new Object();
        $("#gameInviteModNumSelected").html("0")
    }

    /** hide confirmation dialog */
    this._hideConfDialog = function() {
        this._confDialogControl.hideDialog();
        $("#gameInviteModSent").hide();
        $("#gameInviteModNotSent").hide();

        $("#gameInviteModEmailsSent").empty();
        $("#gameInviteModEmailsNotSent").empty();
    }

    this._callLogin = function(){
        var args = { "headerMessage" : "Log In" };
            ag.widget.user.LoginPopup.showPopup(args);
    }

    /** handle response from the server on invitation */
    this._handleInvitationRes = function()
    {
        var sentString = "";
        var notSentString = "";

        for (var i = 0; i < this._inviteFriendEntries.length; i++) {
            var entry = this._inviteFriendEntries[i];
            if (entry.result == "Ok") {
                sentString += entry.userName + "<br/>";
            } else {
                notSentString += entry.userName + "<br/>";
            }
        }

        for (var i = 0; i < this._inviteEmailEntries.length; i++) {
            var entry = this._inviteEmailEntries[i];
            if (entry.result == "Ok") {
                sentString += entry.email + "<br/>";
            } else {
                notSentString += entry.email + "<br/>";
            }
        }

        if (sentString) {
            $("#gameInviteModSent").show();;
            $("#gameInviteModEmailsSent").html(sentString);
        }

        if (notSentString) {
            $("#gameInviteModNotSent").show();;
            $("#gameInviteModEmailsNotSent").html(notSentString);
        }

        this._hideInputDialog();
        this._showConfDialog();
    }

    /** handle get friends request and populate friends list */
    this._handleFriendsRes = function(res) {
        this._totalFriends = res.total;
        this._totalPages = Math.ceil(this._totalFriends /  this.FRIENDS_PAGE_SIZE);
        this._updatePager();
        if (this._totalFriends > 0){
           $("#gameInviteFriendslist").show();
        }else{
            return;
        }
        $("#gameInviteModFriendList").empty();

        var friends = res.friends;

        for (var i = 0; i < friends.length; i++) {
            var friend = friends[i];

            //check for innactive user and skip entry
            if (!friend.profilePath){
                continue;
            }
            var divId = "gameInviteModFriend_" + friend.userId;
            var chkId = "gameInviteModFriendChk_" + friend.userId;
            var name = friend.firstName ? friend.firstName + " " : "";
            name += friend.lastName ? friend.lastName : "";



            // append a friend div
            $("#gameInviteModFriendList").append(
                "<div class='friend float unselected' id='" + divId + "'>" +
                "   <input id='" + chkId + "' name='" + friend.userId + "'" +
                " userName='" + friend.userName + "' type='checkbox'></input>" +
                "   <div class='friend_info'>"+"" +
                "       <img class='friendImg' src='" + ProfileUtil.getImg({userId:friend.userId,userPicSet:friend.userPicSet,size:"small"}) + "'/><br/>" +
                "       <a href='/profile/"+friend.profilePath+"'>" + friend.userName + "</a><br/>" +
                "   </div>"+
                "</div>");
            if ((i + 1) % 5 == 0 || i + 1 == friends.length) {
                var dividerContent = "<br class='clearFloat'/>";
                 $("#gameInviteModFriendList").append(dividerContent);
            }


            // associate an event with checkbox
            $("#" + chkId).bind("click", this, function(e) {
                var module = e.data;
                var uid = $(this).attr("name");
                var checked = $(this).attr("checked");
                var divId = "gameInviteModFriend_" + uid;
                var userName = $(this).attr("userName");

                if (checked) {
                    module._selectedFriends[uid] = userName;
                    module._numSelectedFriends++;
                    $("#" + divId).attr("class", "friend float selected");
                } else {
                    module._selectedFriends[uid] = null;
                    module._numSelectedFriends--;
                    $("#" + divId).attr("class", "friend float unselected");
                }
                $("#gameInviteModNumSelected").html(module._numSelectedFriends.toString());
            });

            if (this._selectedFriends[friend.userId]){
                $("#" + chkId).attr("checked","checked");
                $("#" + divId).attr("class", "friend float selected");
            }
        }
    }


    /** handle AJAX response object */
    this.handleResObjects = function(resObjects)
    {
        var emailInviteIndex = 0;
        var friendInviteIndex = 0;

        for (var i = 0; i < resObjects.length; i++) {
            var res = resObjects[i];
            if (res["methodName"] == "profileService.sendGameInvitationToUser") {
                this._inviteFriendEntries[friendInviteIndex].result = res.response.result;
                friendInviteIndex++;
            } else if (res["methodName"] == "profileService.sendGameInvitationToNonUser") {
                this._inviteEmailEntries[emailInviteIndex].result = res.response.result;
                emailInviteIndex++;
            } else if (res["methodName"] == "profileService.getFriends") {
                this._handleFriendsRes(res.response);
            }
        }

        if (emailInviteIndex || friendInviteIndex) {
            this._handleInvitationRes();
        }
    }
}

GameInviteModule.NAME = "GameInviteModule";
                  
GameInviteModule.prototype = new Module();

