public static qPtl_Invitation GenerateInvite(int userID, DateTime startDate, DateTime endDate, int createdBy, int familyID, int inviteLength, string invitationType, int roleID, int functionalRoleID)
        {
            qPtl_Invitation invite = new qPtl_Invitation();

            if (inviteLength > 32)
            {
                inviteLength = 32;
            }

            string          inviteCode         = GenerateInviteCode(inviteLength);
            qPtl_Invitation existingInvitation = new qPtl_Invitation(inviteCode);

            for (int attemptCount = 0; existingInvitation.InvitationID != 0 && attemptCount < 100; attemptCount++)
            {
                inviteCode         = GenerateInviteCode(inviteLength);
                existingInvitation = new qPtl_Invitation(inviteCode);
            }

            invite.InviteCode = inviteCode;

            invite.Created          = DateTime.Now;
            invite.LastModified     = invite.Created;
            invite.CreatedBy        = createdBy;
            invite.StartDate        = startDate;
            invite.EndDate          = endDate;
            invite.UserID           = userID;
            invite.FamilyID         = familyID;
            invite.InvitationType   = invitationType;
            invite.RoleID           = roleID;
            invite.FunctionalRoleID = functionalRoleID;

            invite.InvitationID = invite.AddInvitation();

            return(invite);
        }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        invitation_id = Convert.ToInt32(Request.QueryString["invitationID"]);

        qPtl_Invitation invite = new qPtl_Invitation(invitation_id);
        invite.LastModified = DateTime.Now;
        invite.LastModifiedBy = Convert.ToInt32(Context.Items["UserID"]);
        invite.Available = "No";
        invite.MarkAsDelete = 1;
        invite.Update();

        Response.Redirect("invitations-list-families.aspx");
    }
        public static qPtl_Invitation GetInvitationByUserID(Int32 user_id)
        {
            var invitation = new qPtl_Invitation();

            invitation.container.Select(
                new DbQuery
            {
                Where      = "UserID = @UserID",
                Parameters = new SqlQueryParameter[] { new SqlQueryParameter("@UserID", user_id) }
            });

            return(invitation.InvitationID > 0 ? invitation : null);
        }
        static public bool InvitationValid(int userID, string inviteCode)
        {
            qPtl_Invitation invite = new qPtl_Invitation(userID, inviteCode);

            if (invite.invitationID.Value == -1 || (invite.StartDate >= DateTime.Now || invite.InvitationStatus == "Redeemed" || invite.EndDate <= DateTime.Now))
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            int invitation_id = 0;
            invitation_id = Convert.ToInt32(Request.QueryString["invitationID"]);

            qPtl_Invitation invite = new qPtl_Invitation(invitation_id);
            int space_id = invite.SpaceID;

            qSoc_Space space = new qSoc_Space(space_id);

            var group_invites = qPtl_Invitation_View.GetInvitationsBySpaceID(space_id);

            string tableHTML = string.Empty;
            tableHTML =     "<table align=\"center\" width=\"650\" border=\"0\" cellspacing=\"0\" cellpadding=\"2\" style=\"border:solid 1px #000; background:#CCC;\">";
            tableHTML +=    "<tr>";
            tableHTML +=    "<td colspan=\"2\" style=\"text-align: center; font-weight:bold; font-size:16px;\"><div style=\"height:10px;\"></div>Group: " + space.SpaceShortName + "<div style=\"height:10px;\"></div>";
            tableHTML +=    "</td><tr>";
            tableHTML +=    "<td align=\"center\"><b>Group Members</b></td><td align=\"center\"><b>Invitation Code</b></td></tr>";

            if (group_invites != null)
            {
                foreach (var i in group_invites)
                {
                    tableHTML += "<tr><td align=\"center\">";
                    tableHTML += Convert.ToString(i.RoleName);
                    tableHTML += "</td><td align=\"center\">";
                    tableHTML += Convert.ToString(i.InviteCode);
                    tableHTML += "</td><td align=\"center\">";
                }
            }

            tableHTML += "<br /><div style=\"height:10px;\"></div></td></tr></table>";

            litInvitationHTML.Text = tableHTML;
            lblSpaceID.Text = "Space ID=" + invite.SpaceID;

            int scope_id = Convert.ToInt32(Context.Items["ScopeID"]);
            qPtl_InvitationTemplate template = qPtl_InvitationTemplate.GetTemplateByScopeID(scope_id);
            litHeader.Text = template.Header;
            litFooter.Text = template.Footer;
        }
    }
        public static qPtl_Invitation[] GenerateInvites(int count, DateTime startDate, DateTime endDate, int createdBy, int familyID, int inviteLength, string invitationType, string invitationStatus, int roleID, int functionalRoleID)
        {
            List <qPtl_Invitation> invites = new List <qPtl_Invitation>();

            if (inviteLength > 32)
            {
                inviteLength = 32;
            }

            for (int i = 0; i < count; i++)
            {
                qPtl_Invitation invite = new qPtl_Invitation();

                string          inviteCode         = GenerateInviteCode(inviteLength);
                qPtl_Invitation existingInvitation = new qPtl_Invitation(inviteCode);

                for (int attemptCount = 0; existingInvitation.InvitationID != 0 && attemptCount < 100; attemptCount++)
                {
                    inviteCode         = GenerateInviteCode(inviteLength);
                    existingInvitation = new qPtl_Invitation(GenerateInviteCode(inviteLength));
                }

                invite.InviteCode = inviteCode;

                invite.Created          = DateTime.Now;
                invite.LastModified     = invite.Created;
                invite.CreatedBy        = createdBy;
                invite.StartDate        = startDate;
                invite.EndDate          = endDate;
                invite.UserID           = 0;
                invite.FamilyID         = familyID;
                invite.InvitationType   = invitationType;
                invite.InvitationStatus = invitationStatus;
                invite.RoleID           = roleID;
                invite.FunctionalRoleID = functionalRoleID;

                invite.InvitationID = invite.AddInvitation();

                invites.Add(invite);
            }

            return(invites.ToArray());
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            // get invitation information
            int invitation_id = 0;
            invitation_id = Convert.ToInt32(Request.QueryString["invitationID"]);

            qPtl_Invitation invite = new qPtl_Invitation(invitation_id);

            string audience_name = string.Empty;
            string code = string.Empty;

            if (invitation_id > 0)
            {
                audience_name = Convert.ToString(invite.InvitationAudienceName);
                code = Convert.ToString(invite.InviteCode);
            }
            else
            {
                audience_name = "Example Group";
                code = "1234";
            }

            string tableHTML = string.Empty;
            tableHTML = "<table align=\"center\" width=\"350\" border=\"0\" cellspacing=\"0\" cellpadding=\"15\" style=\"border:solid 1px #000; background:#CCC;\">";
            tableHTML += "<tr>";
            tableHTML += "<td colspan=\"2\" style=\"text-align: center; font-weight:bold; font-size:16px;\"><div style=\"height:15px;\"></div>Your Invitation";
            tableHTML += "<br /><b>" + audience_name + "</b><br /><br /><b>Invitation Code</b><br>";
            tableHTML += code + "<br />";
            tableHTML += "<br /></td></tr></table>";

            litInvitationHTML.Text = tableHTML;
            lblInvitationID.Text = Request.QueryString["invitationID"];

            int scope_id = Convert.ToInt32(Context.Items["ScopeID"]);
            qPtl_InvitationTemplate template = qPtl_InvitationTemplate.GetTemplateByScopeID(scope_id);
            litHeader.Text = template.Header;
            litFooter.Text = template.Footer;
        }
    }
        static public bool InvitationValid(string inviteCode)
        {
            qPtl_Invitation invite = new qPtl_Invitation(inviteCode);

            if (invite.invitationID.Value == -1 || (invite.StartDate >= DateTime.Now || invite.InvitationStatus == "Redeemed" || invite.EndDate <= DateTime.Now))
            {
                return(false);
            }
            else
            {
                if (invite.MaxRedemptions == -1)
                {
                    return(true);
                }
                else if (invite.MaxRedemptions > 0 && invite.MaxRedemptions > invite.CurrRedemptions)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
        }
 public static bool InvitationValid(string inviteCode)
 {
     qPtl_Invitation invite = new qPtl_Invitation(inviteCode);
     if (invite.invitationID.Value == -1 || (invite.StartDate >= DateTime.Now || invite.InvitationStatus == "Redeemed" || invite.EndDate <= DateTime.Now))
         return false;
     else
     {
         if (invite.MaxRedemptions == -1)
             return true;
         else if (invite.MaxRedemptions > 0 && invite.MaxRedemptions > invite.CurrRedemptions)
             return true;
         else
             return false;
     }
 }
 public static bool InvitationValid(int userID, string inviteCode)
 {
     qPtl_Invitation invite = new qPtl_Invitation(userID, inviteCode);
     if (invite.invitationID.Value == -1 || (invite.StartDate >= DateTime.Now || invite.InvitationStatus == "Redeemed" || invite.EndDate <= DateTime.Now))
         return false;
     else
         return true;
 }
        public static qPtl_Invitation GetInvitationByUserID(Int32 user_id)
        {
            var invitation = new qPtl_Invitation();

            invitation.container.Select(
                new DbQuery
                {
                    Where = "UserID = @UserID",
                    Parameters = new SqlQueryParameter[] { new SqlQueryParameter("@UserID", user_id) }
                });

            return invitation.InvitationID > 0 ? invitation : null;
        }
        public static qPtl_Invitation[] GenerateInvites(int count, DateTime startDate, DateTime endDate, int createdBy, int familyID, int inviteLength, string invitationType, string invitationStatus, int roleID, int functionalRoleID)
        {
            List<qPtl_Invitation> invites = new List<qPtl_Invitation>();

            if (inviteLength > 32)
                inviteLength = 32;

            for (int i = 0; i < count; i++)
            {
                qPtl_Invitation invite = new qPtl_Invitation();

                string inviteCode = GenerateInviteCode(inviteLength);
                qPtl_Invitation existingInvitation = new qPtl_Invitation(inviteCode);

                for (int attemptCount = 0; existingInvitation.InvitationID != 0 && attemptCount < 100; attemptCount++)
                {
                    inviteCode = GenerateInviteCode(inviteLength);
                    existingInvitation = new qPtl_Invitation(GenerateInviteCode(inviteLength));
                }

                invite.InviteCode = inviteCode;

                invite.Created = DateTime.Now;
                invite.LastModified = invite.Created;
                invite.CreatedBy = createdBy;
                invite.StartDate = startDate;
                invite.EndDate = endDate;
                invite.UserID = 0;
                invite.FamilyID = familyID;
                invite.InvitationType = invitationType;
                invite.InvitationStatus = invitationStatus;
                invite.RoleID = roleID;
                invite.FunctionalRoleID = functionalRoleID;

                invite.InvitationID = invite.AddInvitation();

                invites.Add(invite);
            }

            return invites.ToArray();
        }
        public static qPtl_Invitation GenerateInvite(int userID, DateTime startDate, DateTime endDate, int createdBy, int familyID, int inviteLength, string invitationType, int roleID, int functionalRoleID)
        {
            qPtl_Invitation invite = new qPtl_Invitation();

            if (inviteLength > 32)
                inviteLength = 32;

            string inviteCode = GenerateInviteCode(inviteLength);
            qPtl_Invitation existingInvitation = new qPtl_Invitation(inviteCode);
            for (int attemptCount = 0; existingInvitation.InvitationID != 0 && attemptCount < 100; attemptCount++)
            {
                inviteCode = GenerateInviteCode(inviteLength);
                existingInvitation = new qPtl_Invitation(inviteCode);
            }

            invite.InviteCode = inviteCode;

            invite.Created = DateTime.Now;
            invite.LastModified = invite.Created;
            invite.CreatedBy = createdBy;
            invite.StartDate = startDate;
            invite.EndDate = endDate;
            invite.UserID = userID;
            invite.FamilyID = familyID;
            invite.InvitationType = invitationType;
            invite.RoleID = roleID;
            invite.FunctionalRoleID = functionalRoleID;

            invite.InvitationID = invite.AddInvitation();

            return invite;
        }
    protected bool CheckAge()
    {
        bool valid_age = false;

        // if invitation is being used then get associated role; then check age range based on role
        if (plhInvitation.Visible == true && !String.IsNullOrEmpty(txtInvitationCode.Text))
        {
            qPtl_Invitation invite = new qPtl_Invitation(txtInvitationCode.Text);
            if (invite != null)
            {
                if (invite.RoleID > 0)
                {
                    qPtl_Role role = new qPtl_Role(invite.RoleID);

                    if (role != null)
                    {
                        if (role.RoleName.Contains("Teen"))  // use teen age ELSE assume adult user
                        {
                            regMinAge = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Register_MinAge"]);
                            regMaxAge = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Register_TeenMaxAge"]);
                        }
                        else
                        {
                            regMinAge = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Register_TeenMaxAge"]) + 1;
                            regMaxAge = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Register_MaxAge"]);
                        }
                    }
                }
            }
        }
        else
        {
            regMinAge = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Register_MinAge"]);
            regMaxAge = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Register_MaxAge"]);
        }

        try
        {
            string selectedMonth = string.Empty;
            if (!String.IsNullOrEmpty(Convert.ToString(ddlMonth.SelectedValue)))
                selectedMonth = Convert.ToString(ddlMonth.SelectedValue);
            string selectedDay = string.Empty;
            if (!String.IsNullOrEmpty(Convert.ToString(ddlDay.SelectedValue)))
                selectedDay = Convert.ToString(ddlDay.SelectedValue);

            //DateTime DOB = Convert.ToDateTime(selectedMonth + "/" + selectedDay + "/" + ddlYear.SelectedValue);
            DateTime DOB = new DateTime(int.Parse(ddlYear.SelectedValue),int.Parse( ddlMonth.SelectedValue), int.Parse(ddlDay.SelectedValue));
            DateTime currDate = DateTime.Now;
            int numYears = 0;
            try
            {
                /*TimeSpan age = currDate.Subtract(DOB);
                numYears = (age.Days / 365);*/
                numYears = currDate.Year - DOB.Year;
                if (currDate.Month < DOB.Month) numYears--;
                else if (currDate.Month == DOB.Month && currDate.Day < DOB.Day) numYears--;

            }
            catch
            {
                valid_age = false;
            }

            if (numYears >= regMinAge && numYears <= regMaxAge)
            {
                valid_age = true;
            }
            else
            {
                valid_age = false;
            }
        }
        catch
        {
            valid_age = false;
        }

        return valid_age;
    }
    protected void btnSignUp_Click(object sender, EventArgs e)
    {
        Page.Validate("register");

        if (Page.IsValid)
        {
            string sqlCode = string.Empty;
            string returnMessage = string.Empty;
            qDbs_SQLcode sql = new qDbs_SQLcode();
            string register_mode = "new";
            int existing_user_id = 0;
            int scope_id = 1;   // would have to be changed to support multiple organizations on a single platform
            int role_id = 0;
            int moderator_role_id = 0;
            if (!String.IsNullOrEmpty(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["Register_ModeratorRoleID"])))
                moderator_role_id = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Register_ModeratorRoleID"]);

            // ****************************************************
            // STEP 1: DETERMINE IF USER IS ALREADY A LIMITED MOBILE USER
            if (plhMobileNumber.Visible == true)
            {
                //Determine if upgrade of mobile account or new registration
                qPtl_UserProfile mobile_test = qPtl_UserProfile.GetProfileByMobileNumber(txtMobileNumber.Text);

                if (mobile_test != null)
                {
                    if (mobile_test.UserID > 0)
                    {
                        // make sure that the user is eligible for upgrade from mobile only status
                        qPtl_User eval_user = new qPtl_User(mobile_test.UserID);

                        if (eval_user.HighestRole == "Mobile")
                        {
                            register_mode = "update";
                            existing_user_id = mobile_test.UserID;
                        }
                    }
                    else
                    {
                        register_mode = "new";
                    }
                }
                else
                {
                    register_mode = "new";
                }
            }

            // ****************************************************
            // STEP 2a: Mode == new; then add new user
            string currAvailableStatus = string.Empty;
            currAvailableStatus = "Yes";

            if (register_mode == "new")
            {
                qPtl_User new_user = new qPtl_User();
                new_user.Available = "Yes";
                new_user.ScopeID = scope_id;
                new_user.Created = DateTime.Now;
                new_user.CreatedBy = 0;
                new_user.LastModified = DateTime.Now;
                new_user.LastModifiedBy = 0;
                new_user.MarkAsDelete = 0;
                new_user.Status = "";       // used to include a default message for their status, now leave blank
                new_user.FirstName = txtFirstName.Text;
                new_user.LastName = txtLastName.Text;
                new_user.Email = txtEmail.Text;
                new_user.UserName = txtUserName.Text;
                string password_for_storing = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "sha1");
                new_user.Password = password_for_storing;
                new_user.AccountStatus = "Active";
                new_user.Insert();
                existing_user_id = new_user.UserID;

                DateTime DOB;
                try
                {
                    DOB = new DateTime(int.Parse(ddlYear.SelectedValue), int.Parse(ddlMonth.SelectedValue), int.Parse(ddlDay.SelectedValue)); ;//Convert.ToDateTime(ddlMonth.SelectedValue + "/" + ddlDay.SelectedValue + "/" + ddlYear.SelectedValue);
                }
                catch
                {
                    // no valid date so use default value
                    DOB = new DateTime(1900, 1, 1); ////Convert.ToDateTime("1/1/1900");
                }
                qPtl_UserProfile new_profile = new qPtl_UserProfile();
                new_profile.UserID = existing_user_id;
                new_profile.ScopeID = scope_id;
                new_profile.Available = "Yes";
                new_profile.Created = DateTime.Now;
                new_profile.CreatedBy = existing_user_id;
                new_profile.LastModified = DateTime.Now;
                new_profile.LastModifiedBy = existing_user_id;
                new_profile.MarkAsDelete = 0;
                new_profile.Style = "default";
                new_profile.Visibility = "all";
                new_profile.Gender = ddlGender.SelectedValue;
                new_profile.DOB = DOB;

                if (plhRace.Visible == true)
                {
                    string race = string.Empty;
                    int n = 0;
                    foreach (ListItem item in cblRace.Items)
                    {
                        if (item.Selected)
                        {
                            if (n > 0)
                            {
                                race += "," + item.Value;
                            }
                            else
                            {
                                race += item.Value;
                            }
                            n++;
                        }
                    }
                    n = 0;
                    new_profile.Race = race;
                }
                new_profile.Insert();
            }
            qPtl_User user = new qPtl_User(existing_user_id);

            // STEP 2b: Mode == update; then update mobile info
            //mode mobile = update existing account
            if (register_mode == "update")
            {
                user.FirstName = txtFirstName.Text;
                user.LastName = txtLastName.Text;
                user.UserName = txtEmail.Text;
                user.Email = txtEmail.Text;
                string password_for_storing = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "sha1");
                user.Password = password_for_storing;
                user.AccountStatus = "Mobile Verification Pending";
                user.Update();
            }

            // ****************************************************
            // STEP 3: Process invitation & perform invitation-specific work
            // OPTION #1 -- an invitation is required as part of the registration process and a collection of additional actions are related to that
            string code = string.Empty;
            string process_code_mode = string.Empty;
            if (plhInvitation.Visible == true)
            {
                code = txtInvitationCode.Text;
                if (String.IsNullOrEmpty(process_code_mode))
                    process_code_mode = "invitation";                // deal with default/null values
            }
            else if (plhSpaceCode.Visible == true)
            {
                code = txtSpaceCode.Text;
                if (String.IsNullOrEmpty(process_code_mode))
                {
                    qSoc_Space space = new qSoc_Space(code);

                    if (space.SpaceID > 0)
                    {
                        process_code_mode = "space";
                    }
                    else
                    {
                        qSoc_Campaign campaign = new qSoc_Campaign(code);

                        if (campaign.CampaignID > 0)
                        {
                            process_code_mode = "campaign";
                        }
                    }
                }
            }

            if (!String.IsNullOrEmpty(code) && process_code_mode == "invitation")
            {
                //Process invitation
                int invitationID = 0;
                qPtl_Invitation invite = null;
                invite = new qPtl_Invitation(code);
                invitationID = invite.InvitationID;
                role_id = invite.RoleID;

                // update invitation records as necessary
                if (invite.InvitationAudience == "family")
                {
                    invite.UserID = user.UserID;
                    invite.InvitationStatus = "Redeemed";
                    invite.LastModified = DateTime.Now;
                    invite.LastModifiedBy = user.UserID;
                    invite.CurrRedemptions = invite.CurrRedemptions + 1;
                }
                else if (invite.InvitationAudience == "individual")
                {
                    invite.UserID = user.UserID;
                    invite.InvitationStatus = "Redeemed";
                    invite.LastModified = DateTime.Now;
                    invite.LastModifiedBy = user.UserID;
                    invite.CurrRedemptions = invite.CurrRedemptions + 1;
                }
                else if (invite.InvitationAudience == "group")
                {
                    invite.UserID = user.UserID;
                    invite.LastModified = DateTime.Now;
                    invite.LastModifiedBy = user.UserID;
                    invite.CurrRedemptions = invite.CurrRedemptions + 1;

                    if (invite.MaxRedemptions > 0 && invite.CurrRedemptions >= invite.MaxRedemptions)
                        invite.InvitationStatus = "Redeemed";
                }
                else if (invite.InvitationAudience == "moderated group")
                {
                    invite.UserID = user.UserID;
                    invite.LastModified = DateTime.Now;
                    invite.LastModifiedBy = user.UserID;
                    invite.CurrRedemptions = invite.CurrRedemptions + 1;

                    if (invite.MaxRedemptions > 0 && invite.CurrRedemptions >= invite.MaxRedemptions)
                        invite.InvitationStatus = "Redeemed";
                }
                invite.Update();

                // add possible space associated with invitation & space-specific elements

                if (invite.SpaceID > 0)
                {
                    qSoc_Space space = new qSoc_Space(invite.SpaceID);
                    if (space != null)
                    {
                        if (space.SpaceID > 0)
                        {
                            qSoc_UserSpace u_space = new qSoc_UserSpace();
                            u_space.ScopeID = scope_id;
                            u_space.Available = "Yes";
                            u_space.Created = DateTime.Now;
                            u_space.CreatedBy = user.UserID;
                            u_space.LastModified = DateTime.Now;
                            u_space.LastModifiedBy = user.UserID;
                            u_space.MarkAsDelete = 0;
                            u_space.UserID = user.UserID;
                            u_space.SpaceID = space.SpaceID;
                            u_space.PrimarySpace = true;
                            if (role_id == moderator_role_id)
                                u_space.SpaceRole = "Moderator";
                            u_space.Insert();
                        }

                        if (space.SchoolID > 0)
                        {
                            qOrg_UserSchool school = new qOrg_UserSchool();
                            school.UserID = user.UserID;
                            school.SchoolID = space.SchoolID;
                            school.Insert();
                        }

                        // set space to visibile in directory it not already visible
                        if (space.VisibleInDirectory == "No")
                        {
                            space.VisibleInDirectory = "Yes";
                            space.Update();
                        }

                        // add campaign -- includes check to insure that campaigns aren't added twice
                        AddSpaceCampaigns(space, user, scope_id);
                    }
                }

                // add possible campaign associated with invitation -- includes check to insure that campaigns aren't added twice
                if (invite.CampaignID > 0)
                {
                    qSoc_UserCampaign checkc = new qSoc_UserCampaign(user.UserID, invite.CampaignID);
                    if (checkc.UserCampaignID == 0)
                    {
                        AddUserCampaign(invite.CampaignID, scope_id, user);
                    }
                }

                if (invite.FunctionalRoleID > 0)
                {
                    sqlCode = "INSERT INTO qLrn_UserFunctionalRoles ([UserID],[FunctionalRoleID]) VALUES(" + user.UserID + "," + invite.FunctionalRoleID + ")";
                    sql.ExecuteSQL(sqlCode);

                    UserFunctions.AddUserTrainingsByFunctionalRole(user.UserID, invite.FunctionalRoleID);
                }
            }
            else
            {
                // else use default role types
                int teen_max_age = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Register_TeenMaxAge"]);

                qPtl_UserProfile profile = new qPtl_UserProfile(user.UserID);
                if (profile.Age <= teen_max_age)
                    role_id = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Register_TeenRoleID"]);
                else
                    role_id = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Register_ParentRoleID"]);
            }

            // OPTION #2 -- User might have entered a registration code; this will assign them to a space which might have one or more associated campaigns
            if (!String.IsNullOrEmpty(code) && process_code_mode == "space")
            {
                if (!string.IsNullOrEmpty(code))
                {
                    qSoc_Space space = new qSoc_Space(code);

                    if (space != null)
                    {
                        if (space.SpaceID > 0)
                        {
                            qSoc_UserSpace u_space = new qSoc_UserSpace();
                            u_space.ScopeID = scope_id;
                            u_space.Available = "Yes";
                            u_space.Created = DateTime.Now;
                            u_space.CreatedBy = user.UserID;
                            u_space.LastModified = DateTime.Now;
                            u_space.LastModifiedBy = user.UserID;
                            u_space.MarkAsDelete = 0;
                            u_space.UserID = user.UserID;
                            u_space.SpaceID = space.SpaceID;
                            u_space.PrimarySpace = true;
                            if (role_id == moderator_role_id)
                                u_space.SpaceRole = "Moderator";
                            u_space.Insert();
                        }

                        space_redirect = true;
                        new_space_id = space.SpaceID;

                        AddSpaceCampaigns(space, user, scope_id);
                    }
                }
            }
            else if (!String.IsNullOrEmpty(code) && process_code_mode == "campaign")
            {
                qSoc_Campaign campaign = new qSoc_Campaign(code);

                AddUserCampaign(campaign.CampaignID, scope_id, user);
            }

            // ****************************************************
            // STEP 4: Add School Information
            if (plhSchool.Visible == true)
            {
                string school_name = string.Empty;
                string school_other_name = string.Empty;

                if (radCBSearch.Visible == true)
                    school_name = radCBSearch.SelectedValue;
                else
                {
                    school_other_name = txtSchoolOther.Text;
                    school_name = "Other";
                }

                var school = qOrg_School.GetSchoolFromAutoPopulateDropdown(school_name);

                if (school != null)
                {
                    if (school.SchoolID > 0)
                    {
                        qOrg_UserSchool user_school = new qOrg_UserSchool();
                        user_school.Available = "Yes";
                        user_school.ScopeID = scope_id;
                        user_school.Created = DateTime.Now;
                        user_school.CreatedBy = user.UserID;
                        user_school.LastModified = DateTime.Now;
                        user_school.LastModifiedBy = user.UserID;
                        user_school.MarkAsDelete = 0;
                        user_school.UserID = user.UserID;
                        user_school.SchoolID = school.SchoolID;
                        user_school.OtherName = school_other_name;
                        user_school.Insert();

                        // see if this school is already a space
                        var school_space = qSoc_Space.GetSpacesBySchool(school.SchoolID);

                        qSoc_Space curr_space = new qSoc_Space();
                        if (school_space == null)
                        {
                            qSoc_Space new_space = new qSoc_Space();
                            new_space.ScopeID = scope_id;
                            new_space.Available = "Yes";
                            new_space.Created = DateTime.Now;
                            new_space.CreatedBy = 0;
                            new_space.LastModified = DateTime.Now;
                            new_space.LastModifiedBy = 0;
                            new_space.MarkAsDelete = 0;
                            new_space.SpaceName = school.School;
                            new_space.SpaceShortName = school.School;
                            new_space.SpaceType = "school";
                            new_space.AccessMode = "open";
                            new_space.VisibleInDirectory = "Yes";
                            new_space.SpaceCategoryID = 1;
                            new_space.SchoolID = school.SchoolID;
                            new_space.Insert();

                            school_space = new_space;
                        }

                        if (school_space != null)
                        {
                            qSoc_UserSpace s_space = new qSoc_UserSpace();
                            s_space.ScopeID = scope_id;
                            s_space.Available = "Yes";
                            s_space.Created = DateTime.Now;
                            s_space.CreatedBy = user.UserID;
                            s_space.LastModified = DateTime.Now;
                            s_space.LastModifiedBy = user.UserID;
                            s_space.MarkAsDelete = 0;
                            s_space.UserID = user.UserID;
                            s_space.SpaceID = school_space.SpaceID;
                            s_space.PrimarySpace = true;
                            if (role_id == moderator_role_id)
                                s_space.SpaceRole = "Moderator";
                            s_space.Insert();
                        }
                    }
                }
            }

            // ****************************************************
            // STEP 5: Add User Role & Supporting Role Structures
            // Add role
            /*
            qPtl_UserRole role = new qPtl_UserRole();
            role.UserID = user.UserID;
            role.RoleID = role_id;
            role.Insert();
             */
            sqlCode = "INSERT INTO qPtl_UserRoles ([UserID],[RoleID]) VALUES(" + user.UserID + "," + role_id + ")";
            sql.ExecuteSQL(sqlCode);

            // Add possible role actions for the new user role
            AddRoleAction(role_id, scope_id, user);

            // Add possible role campaigns
            AddRoleCampaigns(role_id, scope_id, user);

            // Redundancy check -- write Highest Level into qPtl_User table in case DB trigger not working
            qPtl_Role role = new qPtl_Role(role_id);
            user.HighestRank = role.RoleRank;
            user.HighestRole = role.RoleName;
            user.Update();

            // ****************************************************
            // STEP 6: User Utilties to finalize/prep account
            // Add username folder for images
            string rootLocation = Server.MapPath("~/") + "user_data\\";

            if (!Directory.Exists(rootLocation + user.UserName))
                Directory.CreateDirectory(rootLocation + user.UserName);

            // Create default album
            qSoc_Album album = new qSoc_Album();
            album.ScopeID = scope_id;
            album.Available = "Yes";
            album.Created = DateTime.Now;
            album.CreatedBy = user.UserID;
            album.LastModified = DateTime.Now;
            album.LastModifiedBy = user.UserID;
            album.MarkAsDelete = 0;
            album.UserID = user.UserID;
            album.Name = "My Pics";
            album.Insert();

            // Add communications preferences
            if (register_mode == "new")
            {
                qCom_UserPreference connect = new qCom_UserPreference();
                connect.UserID = user.UserID;
                connect.Created = DateTime.Now;
                connect.CreatedBy = user.UserID;
                connect.LastModified = DateTime.Now;
                connect.LastModifiedBy = user.UserID;
                connect.Available = "Yes";
                connect.ScopeID = 1;
                connect.MarkAsDelete = 0;
                connect.OkBulkEmail = "Yes";
                connect.OkEmail = "Yes";
                connect.OkSms = "Yes";
                connect.LanguageID = 1;
                connect.Insert();
            }

            qCom_UserPreference user_connect = qCom_UserPreference.GetUserPreference(user.UserID);
            user_connect.OkBulkEmail = "Yes";
            user_connect.OkEmail = "Yes";
            user_connect.Update();

            // ****************************************************
            // STEP 7: Log user in and redirect to account setup page/
            // initial session created -- will last for 24 hours before timing out
            qPtl_Sessions session = new qPtl_Sessions();
            session.Created = DateTime.Now;
            session.StartTime = DateTime.Now;
            session.LastTimeSeen = DateTime.Now;
            session.ScopeID = user.ScopeID;
            session.UserID = user.UserID;
            session.BrowserType = Request.Browser.Browser;
            session.ComputerType = Request.Browser.Platform;
            session.Insert();
            int sessionID = session.SessionID;
            int scopeID = user.ScopeID;

            var u_roles = qPtl_UserRole_View.GetUserRoles(user.UserID);
            string role_list = string.Empty;

            if (u_roles != null)
            {
                foreach (var u in u_roles)
                {
                    role_list += string.Format("{0},", u.RoleName, ",");
                }
            }

            role_list.TrimEnd(',');

            string userData = string.Format("{0};{1};{2}", sessionID, role_list, scopeID);

            FormsAuthenticationTicket tkt;
            string cookiestr;
            HttpCookie ck;
            tkt = new FormsAuthenticationTicket(1, user.UserID.ToString(), DateTime.Now, DateTime.Now.AddMinutes(3600), false, userData);
            cookiestr = FormsAuthentication.Encrypt(tkt);
            ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
            ck.Path = FormsAuthentication.FormsCookiePath;
            Response.Cookies.Add(ck);

            HttpCookie cookie2 = new HttpCookie("UserID", Convert.ToString(user.UserID));
            if (tkt.IsPersistent) { cookie2.Expires = tkt.Expiration.AddMinutes(3605); }
            Response.Cookies.Add(cookie2);

            if (space_redirect == true && new_space_id > 0)
                Response.Redirect("~/utilities/manage-user-access.aspx?mode=registration&spaceID=" + new_space_id);
            else
                Response.Redirect("~/utilities/manage-user-access.aspx?mode=registration");
        }
    }
        protected static bool CheckAge(RegistrationData data)
        {
            bool valid_age = false;
            int  regMinAge = 0;
            int  regMaxAge = 0;

            // if invitation is being used then get associated role; then check age range based on role
            if (!String.IsNullOrEmpty(data.invite_code))
            {
                qPtl_Invitation invite = new qPtl_Invitation(data.invite_code);
                if (invite != null)
                {
                    if (invite.RoleID > 0)
                    {
                        qPtl_Role role = new qPtl_Role(invite.RoleID);

                        if (role != null)
                        {
                            if (role.RoleName.Contains("Teen"))  // use teen age ELSE assume adult user
                            {
                                regMinAge = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Register_MinAge"]);
                                regMaxAge = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Register_TeenMaxAge"]);
                            }
                            else
                            {
                                regMinAge = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Register_TeenMaxAge"]) + 1;
                                regMaxAge = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Register_MaxAge"]);
                            }
                        }
                    }
                }
            }
            else
            {
                regMinAge = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Register_MinAge"]);
                regMaxAge = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Register_MaxAge"]);
            }

            try
            {
                DateTime DOB      = Convert.ToDateTime(data.dob);
                DateTime currDate = DateTime.Now;
                int      numYears = 0;
                try
                {
                    TimeSpan age = currDate.Subtract(DOB);
                    numYears = (age.Days / 365);
                }
                catch
                {
                    valid_age = false;
                }

                if (numYears >= regMinAge && numYears <= regMaxAge)
                {
                    valid_age = true;
                }
                else
                {
                    valid_age = false;
                }
            }
            catch
            {
                valid_age = false;
            }

            return(valid_age);
        }
        protected static bool CheckAge(RegistrationData data)
        {
            bool valid_age = false;
            int regMinAge = 0;
            int regMaxAge = 0;

            // if invitation is being used then get associated role; then check age range based on role
            if (!String.IsNullOrEmpty(data.invite_code))
            {
                qPtl_Invitation invite = new qPtl_Invitation(data.invite_code);
                if (invite != null)
                {
                    if (invite.RoleID > 0)
                    {
                        qPtl_Role role = new qPtl_Role(invite.RoleID);

                        if (role != null)
                        {
                            if (role.RoleName.Contains("Teen"))  // use teen age ELSE assume adult user
                            {
                                regMinAge = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Register_MinAge"]);
                                regMaxAge = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Register_TeenMaxAge"]);
                            }
                            else
                            {
                                regMinAge = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Register_TeenMaxAge"]) + 1;
                                regMaxAge = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Register_MaxAge"]);
                            }
                        }
                    }
                }
            }
            else
            {
                regMinAge = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Register_MinAge"]);
                regMaxAge = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Register_MaxAge"]);
            }

            try
            {
                DateTime DOB = Convert.ToDateTime(data.dob);
                DateTime currDate = DateTime.Now;
                int numYears = 0;
                try
                {
                    TimeSpan age = currDate.Subtract(DOB);
                    numYears = (age.Days / 365);
                }
                catch
                {
                    valid_age = false;
                }

                if (numYears >= regMinAge && numYears <= regMaxAge)
                {
                    valid_age = true;
                }
                else
                {
                    valid_age = false;
                }
            }
            catch
            {
                valid_age = false;
            }

            return valid_age;
        }
    protected void btnSave_OnClick(object sender, System.EventArgs e)
    {
        Page.Validate("form");

        if (Page.IsValid)
        {
            int user_id = Convert.ToInt32(Context.Items["UserID"]);

            if (!String.IsNullOrEmpty(Request.QueryString["invitationID"]))
            {
                invitation_id = Convert.ToInt32(Request.QueryString["invitationID"]);

                qPtl_Invitation invite = new qPtl_Invitation(invitation_id);
                invite.InvitationAudience = ddlInvitationAudience.SelectedValue;
                invite.InvitationAudienceName = txtAudienceName.Text;
                invite.Available = rblAvailable.SelectedValue;
                invite.LastModifiedBy = Convert.ToInt32(Context.Items["UserID"]);
                invite.LastModified = DateTime.Now;
                if (!String.IsNullOrEmpty(Convert.ToString(rdtStartTime.SelectedDate)))
                    invite.StartDate = rdtStartTime.SelectedDate;
                if (!String.IsNullOrEmpty(Convert.ToString(rdtEndTime.SelectedDate)))
                    invite.EndDate = rdtEndTime.SelectedDate;

                invite.Update();
            }
            else
            {
                int functional_role_id = Convert.ToInt32(ConfigurationManager.AppSettings["register_InvitationFunctionalRoleID"]);
                int member_role_id = Convert.ToInt32(ConfigurationManager.AppSettings["register_DefaultRoleID"]);
                int parent_role_id = Convert.ToInt32(ConfigurationManager.AppSettings["register_ParentRoleID"]);
                int moderator_role_id = Convert.ToInt32(ConfigurationManager.AppSettings["register_ModeratorRoleID"]);
                string invitation_type = Convert.ToString(ConfigurationManager.AppSettings["register_InvitationType"]);
                int invite_length = Convert.ToInt32(ConfigurationManager.AppSettings["register_InvitationLength"]);

                DateTime start_time = new DateTime();
                DateTime end_time = new DateTime();

                start_time = Convert.ToDateTime(rdtStartTime.SelectedDate);
                end_time = Convert.ToDateTime(rdtEndTime.SelectedDate);

                int family_id = 0;
                string audience_name = string.Empty;

                if (ddlInvitationAudience.SelectedValue == "new family")
                {
                    // create family and add information
                    qPtl_Family family = new qPtl_Family();

                    family.ScopeID = Convert.ToInt32(Context.Items["ScopeID"]);
                    family.Available = rblAvailable.SelectedValue;
                    family.Created = DateTime.Now;
                    family.CreatedBy = Convert.ToInt32(Context.Items["UserID"]);
                    family.LastModified = DateTime.Now;
                    family.LastModifiedBy = Convert.ToInt32(Context.Items["UserID"]);
                    family.MarkAsDelete = 0;
                    family.FamilyName = txtAudienceName.Text;
                    family.ContactFirstName = txtFirstName.Text;
                    family.ContactLastName = txtLastName.Text;
                    family.ContactAddress1 = txtAddress1.Text;
                    family.ContactAddress2 = txtAddress2.Text;
                    family.ContactCity = txtCity.Text;
                    family.ContactStateProvince = txtStateProvince.Text;
                    family.ContactPostalCode = txtPostalCode.Text;
                    family.ContactCountry = txtCountry.Text;
                    family.ContactPhone1 = txtPhone1.Text;
                    if (!String.IsNullOrEmpty(ddlPhone1Type.SelectedValue))
                        family.ContactPhone1Type = ddlPhone1Type.SelectedValue;
                    family.ContactPhone2 = txtPhone2.Text;
                    if (!String.IsNullOrEmpty(ddlPhone2Type.SelectedValue))
                        family.ContactPhone2Type = ddlPhone2Type.SelectedValue;
                    family.ContactEmail = txtEmail.Text;
                    family.ContactRelationship = txtRelationship.Text;

                    family.Insert();

                    family_id = family.FamilyID;
                    audience_name = txtAudienceName.Text;
                }
            }

            if (!String.IsNullOrEmpty(Request.QueryString["invitationID"]))
            {
                lblMessage.Text = "*** Record Successfully Updated ***";
                lblMessageBottom.Text = "*** Record Successfully Updated ***";
                plhInvitationCode.Visible = true;
            }
            else
            {
                Response.Redirect(Request.Url.ToString() + "&mode=add-successful&invitationID=" + invitation_id);
            }
        }
    }
    protected void ProcessContacts(string[] to_pass)
    {
        string mode = to_pass[0];
        string f_name = to_pass[1];
        lblFileName.Text = fileFullName;
        string fileName = string.Format("{0}{1}", Server.MapPath(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["Resources_PDFFolder"])), f_name);
        string message = string.Empty;

        if (File.Exists(fileName))
        {
            List<string[]> contacts = parseCSV(fileName);

            message = "RESULTS<br>";

            //try
            //{
            int i = 0;
            foreach (string[] c in contacts)
            {

                string invite_code = string.Empty;
                string first_name = string.Empty;
                string last_name = string.Empty;
                string email = string.Empty;
                string mobile = string.Empty;
                string postal_code = string.Empty;
                string gender = string.Empty;
                string reference_value = string.Empty;

                invite_code = c[0];
                first_name = c[1];
                last_name = c[2];
                email = c[3];
                mobile = c[4];
                postal_code = c[5];
                gender = c[6];
                reference_value = c[7];

                bool success = false;
                string reason = string.Empty;

                if (i > 0)
                {
                    if (mode == "process")
                    {
                        // get existing invite
                        qPtl_Invitation invite = new qPtl_Invitation(invite_code);

                        if (invite.InvitationID > 0)
                        {
                            invite.InitFirstName = first_name;
                            invite.InitLastName = last_name;
                            invite.InitEmail = email;
                            invite.InitMobile = mobile;
                            invite.InitPostal = postal_code;
                            invite.InitGender = gender;
                            invite.ReferenceValue = reference_value;

                            invite.Update();
                            success = true;
                        }
                    }
                    else if (mode == "test")
                    {
                        success = true;
                    }
                }

                i++;

                if (mode == "process" && success == true)
                {
                    message += "Line " + i + " SUCCESS - Invite Code: " + invite_code + " successfully update<br>";
                }
                else if (mode == "test" && success == true)
                {
                    message += "Line " + i + " SUCCESS - Invite Code: " + invite_code + " will be processed<br>";
                }
                else if (i > 1)
                {
                    message += "Line " + i + " SUCCESS - Invite Code: " + invite_code + " could not be updated<br>";
                }
                else
                    message += "Line " + i + " LINE NOT PROCESSED - header line in the file<br>";
            }

            if (mode == "process")
            {
                lblMessage.Text = message;
                plhStep3.Visible = false;
                plhStep3Completed.Visible = true;
            }
            else if (mode == "test")
            {
                lblTestOutput.Text = message;
                plhStep3.Visible = true;
                plhStep2Completed.Visible = true;
                lblUploadFail.Text = "";
            }
            //}
            //catch
            //{
            //lblTestOutput.Text = "WARNING: File processing failed. Make sure to use a properly formatted .csv file. You can download an example from the top of the page.";
            //}
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            // configure type pull down menu based on site preferences
            ddlInvitationAudience.Items.FindByValue("family").Enabled = false;
            ddlInvitationAudience.Items.FindByValue("new family").Enabled = false;
            ddlInvitationAudience.Items.FindByValue("group").Enabled = false;
            ddlInvitationAudience.Items.FindByValue("new group").Enabled = false;
            ddlInvitationAudience.Items.FindByValue("moderated group").Enabled = false;
            ddlInvitationAudience.Items.FindByValue("new moderated group").Enabled = false;
            ddlInvitationAudience.Items.FindByValue("individual").Enabled = false;
            string invitation_types = Convert.ToString(ConfigurationManager.AppSettings["Members_InvitationTypes"]);
            if (invitation_types.ToLower().Contains("family"))
            {
                ddlInvitationAudience.Items.FindByValue("family").Enabled = true;
                ddlInvitationAudience.Items.FindByValue("new family").Enabled = true;
            }
            if (invitation_types.ToLower().Contains("simple group"))
            {
                ddlInvitationAudience.Items.FindByValue("group").Enabled = true;
                ddlInvitationAudience.Items.FindByValue("new group").Enabled = true;
            }
            if (invitation_types.ToLower().Contains("moderated group"))
            {
                ddlInvitationAudience.Items.FindByValue("moderatedGroup").Enabled = true;
                plhSchools.Visible = true;
            }

            if (invitation_types.ToLower().Contains("individual"))
            {
                ddlInvitationAudience.Items.FindByValue("individual").Enabled = true;
            }

            if (!String.IsNullOrEmpty(Request.QueryString["invitationID"]))
            {
                ddlInvitationAudience.Items.FindByValue("individual").Enabled = true;
            }

            invitation_id = Convert.ToInt32(Request.QueryString["invitationID"]);
            string invite_audience = Convert.ToString(Request.QueryString["audience"]);

            qPtl_Invitation invite = new qPtl_Invitation(invitation_id);

            txtAudienceName.Text = invite.InvitationAudienceName;
            lblAudienceName.Text = invite.InvitationAudienceName;
            lblAudienceName.Visible = false;
            txtModeratedGroupNameShort.Text = invite.InvitationAudienceName;
            txtInvitationCode.Text = invite.InviteCode;
            rblAvailable.SelectedValue = invite.Available;
            ddlInvitationAudience.SelectedValue = invite.InvitationAudience;
            if (invite.MaxRedemptions > 0)
                txtMaxRedemptions.Text = Convert.ToString(invite.MaxRedemptions);
            else
                txtMaxRedemptions.Text = "";
            lblCurrRedemptions.Text = Convert.ToString(invite.CurrRedemptions);
            rdtStartTime.SelectedDate = invite.StartDate;
            rdtEndTime.SelectedDate = invite.EndDate;

            if (Convert.ToString(Request.QueryString["mode"]) == "add-successful")
            {
                lblMessage.Text = "*** Record Successfully Added ***";
            }

            // configure print link
            string baseURL = ConfigurationManager.AppSettings["returnURL"];
            string invitation_audience = Request.QueryString["audience"];
            string rawURL = string.Empty;

            plhNumRedemptions.Visible = true;
            plhCurrRedemptions.Visible = true;

            if (invitation_audience == "individual")
            {
                rawURL = baseURL + "/qDbs/print/print-individual-invitations.aspx?invitationID=" + Request.QueryString["invitationID"];
                lblTitle.Text = "Edit Individual Invitation (ID: " + invite.InvitationID + ")";
                ddlInvitationAudience.Items.FindByValue("family").Enabled = false;
                ddlInvitationAudience.Items.FindByValue("new family").Enabled = false;
                ddlInvitationAudience.Items.FindByValue("group").Enabled = false;
                ddlInvitationAudience.Items.FindByValue("moderated group").Enabled = false;
                ddlInvitationAudience.Items.FindByValue("").Enabled = false;
                lblAudience.Text = "Individual Name *";
                hplBackTop.NavigateUrl = "invitations-list-individuals.aspx";
                hplBackBottom.NavigateUrl = "invitations-list-individuals.aspx";
                plhExistingFamily.Visible = false;
                plhFamilyContactInfo.Visible = false;
                plhEditAudienceName.Visible = true;
            }
            else if (invitation_audience == "family")
            {
                plhSchools.Visible = false;
                populateFamilies();
                populateGroups();
                rawURL = baseURL + "/qDbs/print/print-family-invitations.aspx?invitationID=" + Request.QueryString["invitationID"];
                lblTitle.Text = "Edit Family Invitation (ID: " + invite.InvitationID + ")";
                // load family information
                qPtl_Family family = new qPtl_Family(invite.FamilyID);
                txtFirstName.Text = family.ContactFirstName;
                txtLastName.Text = family.ContactLastName;
                txtAddress1.Text = family.ContactAddress1;
                txtAddress2.Text = family.ContactAddress2;
                txtCity.Text = family.ContactCity;
                txtStateProvince.Text = family.ContactStateProvince;
                txtPostalCode.Text = family.ContactPostalCode;
                txtCountry.Text = family.ContactCountry;
                txtPhone1.Text = family.ContactPhone1;
                if (!String.IsNullOrEmpty(family.ContactPhone1Type))
                    ddlPhone1Type.SelectedValue = family.ContactPhone1Type;
                txtPhone2.Text = family.ContactPhone2;
                if (!String.IsNullOrEmpty(family.ContactPhone2Type))
                    ddlPhone2Type.SelectedValue = family.ContactPhone2Type;
                txtEmail.Text = family.ContactEmail;
                txtRelationship.Text = family.ContactRelationship;
                ddlInvitationAudience.Items.FindByValue("individual").Enabled = false;
                ddlInvitationAudience.Items.FindByValue("group").Enabled = false;
                //ddlInvitationAudience.Items.FindByValue("new family").Enabled = false;
                ddlInvitationAudience.Items.FindByValue("moderated group").Enabled = false;
                ddlInvitationAudience.Items.FindByValue("").Enabled = false;
                plhExistingFamily.Visible = false;
                lblAudience.Text = "Family Name *";
                hplBackTop.NavigateUrl = "invitations-list-families.aspx";
                hplBackBottom.NavigateUrl = "invitations-list-families.aspx";
                hplBackTop.Text = "<i class=\"icon-circle-arrow-left\"></i>&nbsp;&nbsp;Back to Family Invitations";
                hplBackBottom.Text = "<i class=\"icon-circle-arrow-left\"></i>&nbsp;&nbsp;Back to Family Invitations";
            }
            else if (invitation_audience == "moderatedGroup")
            {
                populateSchools();
                rawURL = baseURL + "/qDbs/print/print-moderated-group-invitations.aspx?invitationID=" + Request.QueryString["invitationID"];
                lblTitle.Text = "Edit Moderated Group Invitation (ID: " + invite.InvitationID + ")";
                plhExistingFamily.Visible = false;
                plhFamilyContactInfo.Visible = false;
                plhModeratedGroupInfo.Visible = true;
                qPtl_Role invite_role = new qPtl_Role(invite.RoleID);
                lblInvitationForUserRole.Text = invite_role.RoleName;
                txtAudienceName.Visible = false;
                lblAudienceName.Visible = true;
                plhExistingGroup.Visible = false;
                plhEditAudienceName.Visible = false;
                plhCreateNewModeratedGroup.Visible = true;

                if (invite.SpaceID > 0)
                {
                    qSoc_Space space = new qSoc_Space(invite.SpaceID);
                    if (space.SchoolID > 0)
                    {
                        ddlSchools.SelectedValue = Convert.ToString(space.SchoolID);
                    }
                    txtModeratedGroupNameShort.Text = space.SpaceShortName;
                    txtModeratedGroupName.Text = space.SpaceName;
                    ddlGroupType.SelectedValue = space.SpaceType;
                }
                /*
                // load group information
                qPtl_Family family = new qPtl_Family(invite.FamilyID);
                txtFirstName.Text = family.ContactFirstName;
                txtLastName.Text = family.ContactLastName;
                txtAddress1.Text = family.ContactAddress1;
                txtAddress2.Text = family.ContactAddress2;
                txtCity.Text = family.ContactCity;
                txtStateProvince.Text = family.ContactStateProvince;
                txtPostalCode.Text = family.ContactPostalCode;
                txtCountry.Text = family.ContactCountry;
                txtPhone1.Text = family.ContactPhone1;
                if (!String.IsNullOrEmpty(family.ContactPhone1Type))
                    ddlPhone1Type.SelectedValue = family.ContactPhone1Type;
                txtPhone2.Text = family.ContactPhone2;
                if (!String.IsNullOrEmpty(family.ContactPhone2Type))
                    ddlPhone2Type.SelectedValue = family.ContactPhone2Type;
                txtEmail.Text = family.ContactEmail;
                txtRelationship.Text = family.ContactRelationship;
                    */
                ddlInvitationAudience.Items.FindByValue("individual").Enabled = false;
                ddlInvitationAudience.Items.FindByValue("group").Enabled = false;
                ddlInvitationAudience.Items.FindByValue("new family").Enabled = false;
                ddlInvitationAudience.Items.FindByValue("family").Enabled = false;
                ddlInvitationAudience.Items.FindByValue("new group").Enabled = false;
                ddlInvitationAudience.Items.FindByValue("new moderated group").Enabled = false;
                ddlInvitationAudience.Items.FindByValue("").Enabled = false;
                plhExistingFamily.Visible = false;
                lblAudience.Text = "Group Name *";
                hplBackTop.NavigateUrl = "invitations-list-moderated-groups.aspx";
                hplBackBottom.NavigateUrl = "invitations-list-moderated-groups.aspx";
            }
            else if (invitation_audience == "group")
            {
                rawURL = baseURL + "/qDbs/print/print-group-invitations.aspx?invitationID=" + Request.QueryString["invitationID"];
                lblTitle.Text = "Edit Group Invitation (ID: " + invite.InvitationID + ")";
                ddlInvitationAudience.Items.FindByValue("family").Enabled = false;
                ddlInvitationAudience.Items.FindByValue("new family").Enabled = false;
                ddlInvitationAudience.Items.FindByValue("individual").Enabled = false;
                ddlInvitationAudience.Items.FindByValue("moderated group").Enabled = false;
                ddlInvitationAudience.Items.FindByValue("").Enabled = false;
                lblAudience.Text = "Group Name *";
                hplBackTop.NavigateUrl = "invitations-list-groups.aspx";
                hplBackBottom.NavigateUrl = "invitations-list-groups.aspx";
                plhExistingFamily.Visible = false;
                plhFamilyContactInfo.Visible = false;
                plhEditAudienceName.Visible = true;
            }

            //hplRefreshBottom.NavigateUrl = Request.Url.ToString();
            //hplRefreshTop.NavigateUrl = Request.Url.ToString();

            string passURL = Server.UrlEncode(rawURL);
            string timeStamp = Convert.ToString(DateTime.Now.Month) + "-" + Convert.ToString(DateTime.Now.Day) + "-" + Convert.ToString(DateTime.Now.Year);

            hplPrint.NavigateUrl = "~/qDbs/GeneratePDF.aspx?PageOrientation=landscape&htmlSource=" + passURL + "&mode=read&pdfOutput=" + invitation_audience + " invitation_id_" + invitation_id + "_" + timeStamp + ".pdf";
            hplPrint.Target = "_blank";

            plhInvitationCode.Visible = true;
            plhTools.Visible = true;
        }
        else
        {
            rblAvailable.SelectedValue = "Yes";
            if (!String.IsNullOrEmpty(Request.QueryString["audience"]))
                ddlInvitationAudience.SelectedValue = Convert.ToString(Request.QueryString["audience"]);
            plhInvitationCode.Visible = false;
            plhTools.Visible = false;
            plhCurrRedemptions.Visible = false;

            string invitation_audience = Request.QueryString["audience"];

            //hplRefreshBottom.NavigateUrl = Request.Url.ToString();
            //hplRefreshTop.NavigateUrl = Request.Url.ToString();
            if (invitation_audience == "individual")
            {
                lblTitle.Text = "New Invitation";
                hplBackTop.NavigateUrl = "invitations-list-individuals.aspx";
                hplBackBottom.NavigateUrl = "invitations-list-individuals.aspx";
                lblAudience.Text = "Individual Name *";
                plhCreateFamilyInvitationSettings.Visible = false;
                plhNumRedemptions.Visible = true;
                txtMaxRedemptions.Text = Convert.ToString(1);
                txtMaxRedemptions.Enabled = false;
                plhExistingFamily.Visible = false;
                plhFamilyContactInfo.Visible = false;
                plhEditAudienceName.Visible = true;
                ddlExistingGroups.Visible = false;
            }
            else if (invitation_audience == "family")
            {
                lblTitle.Text = "New Invitation";
                hplBackTop.NavigateUrl = "invitations-list-families.aspx";
                hplBackBottom.NavigateUrl = "invitations-list-families.aspx";
                lblAudience.Text = "Family Name *";
                plhCreateFamilyInvitationSettings.Visible = true;
                txtNumParents.Text = Convert.ToString(2);
                txtNumTeens.Text = Convert.ToString(1);
                plhNumRedemptions.Visible = false;
                populateFamilies();
                plhFamilyContactInfo.Visible = true;
                plhExistingFamily.Visible = false;
                ddlInvitationAudience.SelectedValue = "new family";
                ddlExistingGroups.Visible = false;
            }
            else if (invitation_audience == "group")
            {
                lblTitle.Text = "New Invitation";
                hplBackTop.NavigateUrl = "invitations-list-groups.aspx";
                hplBackBottom.NavigateUrl = "invitations-list-groups.aspx";
                lblAudience.Text = "Group Name *";
                plhCreateFamilyInvitationSettings.Visible = false;
                plhNumRedemptions.Visible = true;
                plhExistingFamily.Visible = false;
                plhFamilyContactInfo.Visible = false;
                plhEditAudienceName.Visible = true;
                ddlExistingGroups.Visible = false;
            }
            else if (invitation_audience == "moderatedGroup")
            {
                lblTitle.Text = "New Invitation";
                hplBackTop.NavigateUrl = "invitations-list-moderated-groups.aspx";
                hplBackBottom.NavigateUrl = "invitations-list-moderated-groups.aspx";
                lblAudience.Text = "Group Name *";
                plhCreateFamilyInvitationSettings.Visible = false;
                plhNumRedemptions.Visible = true;
                plhExistingFamily.Visible = false;
                plhFamilyContactInfo.Visible = false;
                plhEditAudienceName.Visible = true;
                ddlInvitationAudience.SelectedValue = "new moderated group";
                plhExistingGroup.Visible = false;
                plhCreateModeratedGroupInvitationSettings.Visible = true;
                lblMaxRedemptions.Text = "Max Number of Member Redemptions";
                plhCreateNewModeratedGroup.Visible = true;
                plhEditAudienceName.Visible = false;
            }
        }
    }
    protected void btnSave_OnClick(object sender, System.EventArgs e)
    {
        Page.Validate("form");

        if (Page.IsValid)
        {
            int user_id = Convert.ToInt32(Context.Items["UserID"]);

            if (!String.IsNullOrEmpty(Request.QueryString["invitationID"]))
            {
                invitation_id = Convert.ToInt32(Request.QueryString["invitationID"]);

                qPtl_Invitation invite = new qPtl_Invitation(invitation_id);
                invite.InvitationAudience = ddlInvitationAudience.SelectedValue;
                invite.InvitationAudienceName = txtAudienceName.Text;
                invite.Available = rblAvailable.SelectedValue;
                invite.LastModifiedBy = Convert.ToInt32(Context.Items["UserID"]);
                invite.LastModified = DateTime.Now;
                if (!String.IsNullOrEmpty(Convert.ToString(rdtStartTime.SelectedDate)))
                    invite.StartDate = rdtStartTime.SelectedDate;
                if (!String.IsNullOrEmpty(Convert.ToString(rdtEndTime.SelectedDate)))
                    invite.EndDate = rdtEndTime.SelectedDate;

                if (!String.IsNullOrEmpty(ddlSchools.SelectedValue))
                {
                    if (invite.SpaceID > 0)
                    {
                        qSoc_Space space = new qSoc_Space(invite.SpaceID);
                        space.SchoolID = Convert.ToInt32(ddlSchools.SelectedValue);
                        space.Update();
                    }
                }

                invite.Update();
            }
            else
            {
                int functional_role_id = Convert.ToInt32(ConfigurationManager.AppSettings["register_InvitationFunctionalRoleID"]);
                int member_role_id = Convert.ToInt32(ConfigurationManager.AppSettings["register_DefaultRoleID"]);
                int parent_role_id = Convert.ToInt32(ConfigurationManager.AppSettings["register_ParentRoleID"]);
                int moderator_role_id = Convert.ToInt32(ConfigurationManager.AppSettings["register_ModeratorRoleID"]);
                string invitation_type = Convert.ToString(ConfigurationManager.AppSettings["register_InvitationType"]);
                int invite_length = Convert.ToInt32(ConfigurationManager.AppSettings["register_InvitationLength"]);

                DateTime start_time = new DateTime();
                DateTime end_time = new DateTime();

                start_time = Convert.ToDateTime(rdtStartTime.SelectedDate);
                end_time = Convert.ToDateTime(rdtEndTime.SelectedDate);

                if (ddlInvitationAudience.SelectedValue == "individual")
                {
                    var invite = qPtl_Invitation.GenerateInvite(0, start_time, end_time, Convert.ToInt32(Context.Items["UserID"]), 0, invite_length, invitation_type, member_role_id, functional_role_id);

                    invite.ScopeID = Convert.ToInt32(Context.Items["ScopeID"]);
                    invite.LastModifiedBy = Convert.ToInt32(Context.Items["UserID"]);
                    invite.LastModified = DateTime.Now;
                    invite.MarkAsDelete = 0;
                    invite.InvitationAudience = ddlInvitationAudience.SelectedValue;
                    invite.InvitationAudienceName = txtAudienceName.Text;
                    invite.Available = rblAvailable.SelectedValue;
                    invite.InvitationStatus = "Redeemable";
                    invite.CurrRedemptions = 0;
                    invite.MaxRedemptions = 1;

                    invite.Update();
                    invitation_id = invite.InvitationID;
                }
                else if (ddlInvitationAudience.SelectedValue == "group")
                {
                    var invite = qPtl_Invitation.GenerateInvite(0, start_time, end_time, Convert.ToInt32(Context.Items["UserID"]), 0, invite_length, invitation_type, member_role_id, functional_role_id);

                    invite.ScopeID = Convert.ToInt32(Context.Items["ScopeID"]);
                    invite.LastModifiedBy = Convert.ToInt32(Context.Items["UserID"]);
                    invite.LastModified = DateTime.Now;
                    invite.MarkAsDelete = 0;
                    invite.InvitationAudience = ddlInvitationAudience.SelectedValue;
                    invite.InvitationAudienceName = txtAudienceName.Text;
                    invite.Available = rblAvailable.SelectedValue;
                    invite.InvitationStatus = "Redeemable";
                    invite.CurrRedemptions = 0;
                    if (!String.IsNullOrEmpty(txtMaxRedemptions.Text))
                        invite.MaxRedemptions = Convert.ToInt32(txtMaxRedemptions.Text);

                    invite.Update();
                    invitation_id = invite.InvitationID;
                }
                else if (ddlInvitationAudience.SelectedValue == "family" || ddlInvitationAudience.SelectedValue == "new family")
                {
                    int family_id = 0;
                    string audience_name = string.Empty;

                    if (ddlInvitationAudience.SelectedValue == "new family")
                    {
                        // create family and add information
                        qPtl_Family family = new qPtl_Family();

                        family.ScopeID = Convert.ToInt32(Context.Items["ScopeID"]);
                        family.Available = rblAvailable.SelectedValue;
                        family.Created = DateTime.Now;
                        family.CreatedBy = Convert.ToInt32(Context.Items["UserID"]);
                        family.LastModified = DateTime.Now;
                        family.LastModifiedBy = Convert.ToInt32(Context.Items["UserID"]);
                        family.MarkAsDelete = 0;
                        family.FamilyName = txtAudienceName.Text;
                        family.ContactFirstName = txtFirstName.Text;
                        family.ContactLastName = txtLastName.Text;
                        family.ContactAddress1 = txtAddress1.Text;
                        family.ContactAddress2 = txtAddress2.Text;
                        family.ContactCity = txtCity.Text;
                        family.ContactStateProvince = txtStateProvince.Text;
                        family.ContactPostalCode = txtPostalCode.Text;
                        family.ContactCountry = txtCountry.Text;
                        family.ContactPhone1 = txtPhone1.Text;
                        if (!String.IsNullOrEmpty(ddlPhone1Type.SelectedValue))
                            family.ContactPhone1Type = ddlPhone1Type.SelectedValue;
                        family.ContactPhone2 = txtPhone2.Text;
                        if (!String.IsNullOrEmpty(ddlPhone2Type.SelectedValue))
                            family.ContactPhone2Type = ddlPhone2Type.SelectedValue;
                        family.ContactEmail = txtEmail.Text;
                        family.ContactRelationship = txtRelationship.Text;

                        family.Insert();

                        family_id = family.FamilyID;
                        audience_name = txtAudienceName.Text;
                    }
                }
                else if (ddlInvitationAudience.SelectedValue == "moderated group" || ddlInvitationAudience.SelectedValue == "new moderated group")
                {
                    int space_id = 0;
                    string group_audience_name = string.Empty;

                    if (ddlInvitationAudience.SelectedValue == "new moderated group" || ddlInvitationAudience.SelectedValue == "moderatedGroup")
                    {
                        // create space
                        qSoc_Space space = new qSoc_Space();
                        space.ScopeID = Convert.ToInt32(Context.Items["ScopeID"]);
                        space.Available = rblAvailable.SelectedValue;
                        space.Created = DateTime.Now;
                        space.CreatedBy = Convert.ToInt32(Context.Items["UserID"]);
                        space.LastModified = DateTime.Now;
                        space.LastModifiedBy = Convert.ToInt32(Context.Items["UserID"]);
                        space.MarkAsDelete = 0;
                        space.SpaceShortName = txtModeratedGroupNameShort.Text;
                        space.SpaceName = txtModeratedGroupName.Text;
                        space.AccessMode = "invitation";
                        space.VisibleInDirectory = "No";
                        space.SpaceType = ddlGroupType.SelectedValue;
                        if (!String.IsNullOrEmpty(ddlSchools.SelectedValue))
                        {
                            space.SchoolID = Convert.ToInt32(ddlSchools.SelectedValue);
                        }
                        space.Insert();

                        space_id = space.SpaceID;
                        group_audience_name = txtModeratedGroupName.Text;
                    }
                    else
                    {
                        space_id = Convert.ToInt32(ddlExistingGroups.SelectedValue);
                        qSoc_Space space = new qSoc_Space(space_id);
                        group_audience_name = space.SpaceShortName;
                    }

                    // create necessary invitations -- moderators
                    int num_moderators = Convert.ToInt32(txtNumGroupModerators.Text);
                    for (int i = 0; i < num_moderators; i++)
                    {
                        var invite = qPtl_Invitation.GenerateInvite(0, start_time, end_time, Convert.ToInt32(Context.Items["UserID"]), 0, invite_length, invitation_type, moderator_role_id, functional_role_id);
                        invite.ScopeID = Convert.ToInt32(Context.Items["ScopeID"]);
                        invite.LastModifiedBy = Convert.ToInt32(Context.Items["UserID"]);
                        invite.LastModified = DateTime.Now;
                        invite.MarkAsDelete = 0;
                        invite.InvitationAudience = "moderated group";
                        invite.InvitationAudienceName = group_audience_name;
                        invite.Available = rblAvailable.SelectedValue;
                        invite.InvitationStatus = "Redeemable";
                        invite.CurrRedemptions = 0;
                        invite.MaxRedemptions = 1;
                        invite.SpaceID = space_id;
                        invite.Update();
                    }

                    // create single teen invitation
                    var invite_t = qPtl_Invitation.GenerateInvite(0, start_time, end_time, Convert.ToInt32(Context.Items["UserID"]), 0, invite_length, invitation_type, member_role_id, functional_role_id);
                    invite_t.ScopeID = Convert.ToInt32(Context.Items["ScopeID"]);
                    invite_t.LastModifiedBy = Convert.ToInt32(Context.Items["UserID"]);
                    invite_t.LastModified = DateTime.Now;
                    invite_t.MarkAsDelete = 0;
                    invite_t.InvitationAudience = "moderated group";
                    invite_t.InvitationAudienceName = group_audience_name;
                    invite_t.Available = rblAvailable.SelectedValue;
                    invite_t.InvitationStatus = "Redeemable";
                    invite_t.CurrRedemptions = 0;
                    if (!String.IsNullOrEmpty(txtNumTeens.Text))
                        invite_t.MaxRedemptions = Convert.ToInt32(txtNumTeens.Text);
                    else
                        invite_t.MaxRedemptions = -1;
                    invite_t.SpaceID = space_id;
                    invite_t.Update();
                    invitation_id = invite_t.InvitationID;

                    qSoc_Space existing_space = new qSoc_Space(space_id);
                    existing_space.SpaceCode = invite_t.InviteCode;
                    existing_space.Update();
                }
            }

            if (!String.IsNullOrEmpty(Request.QueryString["invitationID"]))
            {
                lblMessage.Text = "*** Record Successfully Updated ***";
                lblMessageBottom.Text = "*** Record Successfully Updated ***";
                plhInvitationCode.Visible = true;
            }
            else
            {
                Response.Redirect(Request.Url.ToString() + "&mode=add-successful&invitationID=" + invitation_id);
            }
        }
    }