/**
 * SiteInvitationModule
 * @author Jae Cho
 * Subclass of Module that represents user's friends.
 * Note that a single service call is made for each address. The AJAX request is
 * bundled to reduce the traffic.
 */
function SiteInviteModule() {

    /** module name */
    this._name= SiteInviteModule.NAME;

    /** array of entries for the invitation */
    this._inviteEntries = null;

    /**dialog containers*/
    this._inputDialogControl = null;
    this._confDialogControl = null;

    /** @return list of request actions that can be handled by this module */
      this.getPageActionNames = function()
      {
         return [ "inviteToSite" ];
      };

      /** handle request action
      * @action name of action to invoke
      * @params bean containing request parameters
      *
      * */
      this.handlePageAction = function(action, params)
      {
          if (action == "inviteToSite") {
              this._showInputDialog();
          }
      };



    this.initialize = function() {

        if(window.external_page){
            $("#siteInviteModLink").bind("click", this, function(e) {
                top.location="/?pageAction=inviteToSite";
            });
            return;
		};

        this._inputDialogControl = new DialogControl("#siteInviteModInputDialog");
        this._confDialogControl = new DialogControl("#siteInviteModConfDialog");

        $("#siteInviteModLink").bind("click", this, function(e) {
            e.preventDefault();
            var module = e.data;
            module._showInputDialog();
        });

        $("#siteInviteModSendButton").bind("click", this, function(e) {
            e.preventDefault();
            var module = e.data;
            var result = module._sendInvitation();
        });

        $("#siteInviteModCancelButton").bind("click", this, function(e) {
            e.preventDefault();
            var module = e.data;
            $("#siteInviteModErrorBox").hide();
            module._hideInputDialog();
        });

        $("#siteInviteModOkButton").bind("click", this, function(e) {
            e.preventDefault();
            var module = e.data;
            module._hideConfDialog();
        });
    }


    /** read emails from the text area, validate and send
     * @param emails
     * @return true if
     */
    this._sendInvitation = function(emails)
    {
        var emails = $("#siteInviteModEmails").val();
        var errorMessage = "Error: You Must Enter a Valid Email Address";

        if (!emails) {
            $("#siteInviteModError").html(errorMessage);
            $("#siteInviteModErrorBox").show();
            return false;
        }
        $("#siteInviteModErrorBox").hide();
        var parsedEntries = StringUtil.parseEmails(emails);
        var reqs = new Array();
        this._inviteEntries = new Array();

        if (parsedEntries.length > 200) {
            errorMessage = "Error: You can send up to 200 email invitations";
            $("#siteInviteModError").html(errorMessage);
            $("#siteInviteModErrorBox").show();
                return;
        }

        for (var i = 0; i < parsedEntries.length; i++) {
            if (parsedEntries[i].status != "valid") {
                $("#siteInviteModError").html(errorMessage);
                $("#siteInviteModErrorBox").show();
                return;
            }

            this._inviteEntries[i] = new Object();
            this._inviteEntries[i].email = parsedEntries[i].email;

            reqs.push({ "methodName" : "profileService.sendSiteInvitation",
                    "email": parsedEntries[i].email});
        }

        this._page.makeModuleAjaxCall(this, reqs);
    }

    /** show input dialog */
    this._showInputDialog = function()
    {
        var uid = this._page.getLoggedInUserId();
        var getProfileReq = [ { "methodName" : "profileService.getFullProfile", "userId" : uid} ];
        this._page.makeModuleAjaxCall(this, getProfileReq);

        $("#siteInviteModEmails").val("");
        this._inputDialogControl.showDialog();

    }

    /** hide input dialog */
    this._hideInputDialog = function() {
         this._inputDialogControl.hideDialog();
    }

    /** show confirmation dialog */
    this._showConfDialog = function() {
        this._confDialogControl.showDialog();
    }

    /** hide confirmation dialog */
    this._hideConfDialog = function() {

         this._confDialogControl.hideDialog();
        $("#siteInviteModSent").hide()
        $("#siteInviteModAlreadySent").hide();
        $("#siteInviteModAlreadyMember").hide();

        $("#siteInviteModEmailsSent").empty();
        $("#siteInviteModEmailsAlreadySent").empty();
        $("#siteInviteModEmailsAlreadyMember").empty();
    }

    /** handle response from the server on invitation */
    this._handleInvitationRes = function()
    {
        var sentString ="";
        var alreadySentString ="";
        var alreadyMemeberString = "";

        for (var i = 0; i < this._inviteEntries.length; i++) {
            var entry = this._inviteEntries[i];
            if (entry.result == "Ok") {
                sentString += entry.email + "<br/>";
            } else if (entry.result == "InvitationCountExceeded") {
                alreadySentString += entry.email + "<br/>";
            } else if (entry.result == "EmailAlreadyRegistered") {
                alreadyMemeberString += entry.email + "<br/>";
            }
        }

        if (sentString) {
            $("#siteInviteModSent").show();
            $("#siteInviteModEmailsSent").html(sentString);
        }

        if (alreadySentString) {
            $("#siteInviteModAlreadySent").show();
            $("#siteInviteModEmailsAlreadySent").html(alreadySentString);
        }

        if (alreadyMemeberString) {
            $("#siteInviteModAlreadyMember").show();
            $("#siteInviteModEmailsAlreadyMember").html(alreadyMemeberString);
        }

        this._hideInputDialog();
        this._showConfDialog();
    }

    /** get profile information */
    this._handleProfileRes = function(profile) {
        var invitorInfo = profile.userName;
        $("#siteInviteModFrom").html(invitorInfo);
    }

    
    /** handle AJAX response object */
    this.handleResObjects = function(resObjects) {
        var responseReceived = false;
        for (var i = 0; i < resObjects.length; i++) {
            var res = resObjects[i];
            if (res["methodName"] == "profileService.sendSiteInvitation") {
                responseReceived = true;
                this._inviteEntries[i].result = res.response.result;
            } else if (res["methodName"] == "profileService.getFullProfile") {
                this._handleProfileRes(res.response.profile);
            }
        }

        if (responseReceived) {
            this._handleInvitationRes();
        }
    }
}

SiteInviteModule.NAME = "SiteInviteModule";

SiteInviteModule.prototype = new Module();