protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            int emailID = Convert.ToInt32(Request.QueryString["emailID"]);

            // create object
            qCom_EmailTool email = new qCom_EmailTool(emailID);

            qPtl_User user = new qPtl_User(Convert.ToInt32(Context.Items["UserID"]));
            txtEmail.Text = user.Email;

            lblSubject.Text = email.emailSubject;

            // get headers and footers
            string query = "SELECT TOP(1) * FROM qCom_EmailPreferences WHERE Available = 'Yes'";
            qDbs_SQLcode sql = new qDbs_SQLcode();
            SqlDataReader eReader = sql.GetDataReader(query);

            eReader.Read();
            string header = Convert.ToString(eReader["Header"]);
            string footer = Convert.ToString(eReader["Footer"]);
            string unsubscribe = Convert.ToString(eReader["Unsubscribe"]);
            eReader.Close();

            // if email type is bulk, then add footer
            string completeMessage = header + email.emailDraft + footer;
            if (email.emailType == "bulk")
            {
                completeMessage += unsubscribe;
            }

            lblBody.Text = completeMessage;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            string sqlCode = string.Empty;
            qDbs_SQLcode sql = new qDbs_SQLcode();

            // get emails
            sqlCode = "SELECT EmailID, URI FROM qCom_EmailItem WHERE Type <> 'Individual Email' AND ScopeID = " + Context.Items["ScopeID"] + " ORDER BY Subject ASC";

            DataTable dtEmails;
            dtEmails = sql.GetDataTable(sqlCode);

            ddlEmails.DataSource = dtEmails;
            ddlEmails.DataValueField = "EmailID";
            ddlEmails.DataTextField = "URI";
            ddlEmails.DataBind();

            // get searches
            sqlCode = "SELECT SearchID, SavedName FROM qDbs_Searches WHERE Saved = 'Yes' AND YesEmail = 'Yes' ORDER BY SavedName ASC";

            DataTable dtSearches;
            dtSearches = sql.GetDataTable(sqlCode);

            ddlSearches.DataSource = dtSearches;
            ddlSearches.DataValueField = "SearchID";
            ddlSearches.DataTextField = "SavedName";
            ddlSearches.DataBind();

            // get prior data if edit mode
            if (Request.QueryString["sendEventID"] != null && Request.QueryString["sendEventID"] != "")
            {
                sqlCode = "SELECT * FROM qCom_SendEvents WHERE SendEventID = " + Request.QueryString["sendEventID"];

                using (SqlDataReader eReader = sql.GetDataReader(sqlCode))
                {
                    eReader.Read();
                    ddlEmails.SelectedValue = Convert.ToString(eReader["EmailID"]);
                    ddlSearches.SelectedValue = Convert.ToString(eReader["SearchID"]);
                    DateTime startDate = new DateTime();
                    startDate = Convert.ToDateTime(eReader["StartDate"]);
                    datStart.SelectedDate = startDate;
                    rblRecurring.SelectedValue = Convert.ToString(eReader["Recurring"]);
                    rblRunning.SelectedValue = Convert.ToString(eReader["Running"]);
                    rblHeader.SelectedValue = Convert.ToString(eReader["IncludeHeader"]);
                    rblFooter.SelectedValue = Convert.ToString(eReader["IncludeFooter"]);
                    rblUnsubscribe.SelectedValue = Convert.ToString(eReader["IncludeUnsubscribe"]);
                    eReader.Close();
                }
            }

        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        Response.Write("just clicked");

        string sqlQuery = string.Empty;

        if (Request.QueryString["sendEventID"] != null && Request.QueryString["sendEventID"] != "")
        {
            sqlQuery = "UPDATE qCom_SendEvents SET [SearchID] = " + ddlSearches.SelectedValue + ", [EmailID] = " + ddlEmails.SelectedValue + ", [StartDate] = '" + datStart.SelectedDate + "',[Recurring] = '" + rblRecurring.SelectedItem + "',[Running] = '" + rblRunning.SelectedItem + "',[IncludeHeader] = '" + rblHeader.SelectedItem + "',[IncludeFooter] = '" + rblFooter.SelectedItem + "',[IncludeUnsubscribe] = '" + rblUnsubscribe.SelectedItem + "' WHERE SendEventID = " + Request.QueryString["sendEventID"];
        } else
        {
            sqlQuery = "INSERT qCom_SendEvents ([ScopeID],[SearchID],[EmailID],[StartDate],[Recurring],[Running],[IncludeHeader],[IncludeFooter],[IncludeUnsubscribe]) VALUES (" + Context.Items["ScopeID"] + "," + ddlSearches.SelectedValue + " , " + ddlEmails.SelectedValue + " ,'" + datStart.SelectedDate + "','" + rblRecurring.SelectedItem + "','" + rblRunning.SelectedItem + "','" + rblHeader.SelectedItem + "','" + rblFooter.SelectedItem + "','" + rblUnsubscribe.SelectedItem + "')";
        }

        //Response.Write("sql code = " + sqlQuery);

        qDbs_SQLcode sql = new qDbs_SQLcode();
        sql.ExecuteSQL(sqlQuery);

        Response.Redirect("send-event-list.aspx");
    }
    protected void populateTrainings()
    {
        int userID = Convert.ToInt32(Request.QueryString["userID"]);
        string sqlCode = string.Empty;
        qDbs_SQLcode sql = new qDbs_SQLcode();
        q_Helper helper = new q_Helper();

        // get roles
        sqlCode = "SELECT TrainingID, Title FROM qLrn_UserTrainings_View WHERE Available = 'Yes' AND UserID = " + userID + " ORDER BY Title ASC";

        DataTable dtRoles;

        using (dtRoles = sql.GetDataTable(sqlCode))
        {
            cblUserTrainings.DataSource = dtRoles;
            cblUserTrainings.DataValueField = "TrainingID";
            cblUserTrainings.DataTextField = "Title";
            cblUserTrainings.DataBind();
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            profile_id = Convert.ToInt32(Request.QueryString["userID"]);

            qPtl_User profile = new qPtl_User(profile_id);
            username = profile.UserName;

            string curr_tab = string.Empty;
            curr_tab = Request.QueryString["currTab"];
            lit1Class.Text = "";
            lit2Class.Text = "";
            lit3Class.Text = "";
            lit4Class.Text = "";
            lit5Class.Text = "";
            litTab1Class.Text = "class=\"tab-pane\"";
            litTab2Class.Text = "class=\"tab-pane\"";
            litTab3Class.Text = "class=\"tab-pane\"";
            litTab4Class.Text = "class=\"tab-pane\"";
            litTab5Class.Text = "class=\"tab-pane\"";
            if (curr_tab == "overview")
            {
                lit1Class.Text = "class='active'";
                litTab1Class.Text = "class=\"tab-pane active\"";
                if (!String.IsNullOrEmpty(Request.QueryString["message"]))
                    lblTab1Message.Text = " *** " + Request.QueryString["message"] + "***";
            }
            else if (curr_tab == "trainings")
            {
                lit2Class.Text = "class='active'";
                litTab2Class.Text = "class=\"tab-pane active\"";
                if (!String.IsNullOrEmpty(Request.QueryString["message"]))
                    lblTab2Message.Text = " *** " + Request.QueryString["message"] + "***";
            }
            else if (curr_tab == "assessments")
            {
                lit3Class.Text = "class='active'";
                litTab3Class.Text = "class=\"tab-pane active\"";
                if (!String.IsNullOrEmpty(Request.QueryString["message"]))
                    lblTab3Message.Text = " *** " + Request.QueryString["message"] + "***";
            }
            else if (curr_tab == "certificates")
            {
                lit4Class.Text = "class='active'";
                litTab4Class.Text = "class=\"tab-pane active\"";
                if (!String.IsNullOrEmpty(Request.QueryString["message"]))
                    lblTab4Message.Text = " *** " + Request.QueryString["message"] + "***";
            }
            else if (curr_tab == "tools")
            {
                lit5Class.Text = "class='active'";
                litTab5Class.Text = "class=\"tab-pane active\"";
                if (!String.IsNullOrEmpty(Request.QueryString["message"]))
                    lblTab5Message.Text = " *** " + Request.QueryString["message"] + "***";
            }
            else
            {
                lit1Class.Text = "class='active'";
                litTab1Class.Text = "class=\"tab-pane active\"";
            }

            // tab 2 - assigned trainings
            var u_trainings = qLrn_UserTraining_View.GetUserTrainings(profile_id);
            string u_training_html = string.Empty;

            if (u_trainings != null)
            {
                foreach (var t in u_trainings)
                {
                    u_training_html += "<strong>" + t.Title + "</strong><br>Status: " + t.Status + "<br><br>";
                }
                litUserTrainingList.Text = u_training_html;
            }
            else
                litUserTrainingList.Text = "No trainings assigned";

            // tab 3 - assessments
            userAssessments.SelectCommand = "SELECT * FROM qLrn_UserAssessments_View WHERE UserID = " + profile_id + " AND Available = 'Yes' AND MarkAsDelete = 0 AND Created > '" + System.Configuration.ConfigurationManager.AppSettings["Solution_StartDate"] + "' ORDER BY Created DESC";

            startDate = null;
            endDate = null;

            // tab 4 - certificates
            var certificates = qLrn_UserTrainingCertificates.GetUserTrainingCertificates(profile_id);

            if (certificates != null)
            {
                string cert_html = string.Empty;

                foreach (var c in certificates)
                {
                    if (c.UserTrainingCertificateID > 0)
                    {
                        qLrn_UserTraining_View training = new qLrn_UserTraining_View(c.UserTrainingID);

                        cert_html += "<li><i class=\"icon-download-alt\"></i>  <a href=\"/user_data/" + profile.UserName + "/" + c.FileName + "\"><strong>" + training.Title + "</strong></a> uploaded at: " + c.Created + "</li>";
                    }
                }

                if (!String.IsNullOrEmpty(cert_html))
                    litCertificates.Text = cert_html;
                else
                    litCertificates.Text = "No Certificates.";
            }
            else
            {
                litCertificates.Text = "No Certificates.";
            }

            // tab 5 - tools
            // TOOL: Add Trainings
            string sqlCode = string.Empty;
            qDbs_SQLcode sql = new qDbs_SQLcode();
            q_Helper helper = new q_Helper();

            // get roles
            sqlCode = "SELECT TrainingID, Title FROM qLrn_Trainings WHERE Available = 'Yes' ORDER BY TrainingID";

            DataTable dtTrainings;

            using (dtTrainings = sql.GetDataTable(sqlCode))
            {

                cblTrainings.DataSource = dtTrainings;
                cblTrainings.DataValueField = "TrainingID";
                cblTrainings.DataTextField = "Title";
                cblTrainings.DataBind();
            }

            // mark current trainings
            sqlCode = "SELECT TrainingID FROM qLrn_UserTrainings WHERE UserID = " + Request.QueryString["userID"];

            SqlDataReader rReader;

            int i = 0;
            using (rReader = sql.GetDataReader(sqlCode))
            {
                while (rReader.Read())
                {
                    ListItem currentCheckBox = cblTrainings.Items.FindByValue(rReader["TrainingID"].ToString());
                    if (currentCheckBox != null)
                    {
                        currentCheckBox.Selected = true;
                    }
                    i++;
                }
            }
            litNumTrainings.Text = "Member is enrolled in <strong>" + i + " trainings</strong>";

            // TOOL: Reset/Delete Trainings
            plhTrainings.Visible = false;
            plhResetOptions.Visible = false;
            btnProcessTrainings.Visible = false;
            dpkStartDate.SelectedDate = DateTime.Now.AddDays(-1);
            txtDaysAvailable.Text = "4000";

            var u_assessments = qLrn_UserAssessment.GetUserAssessments(profile_id, "");
            int num_assessments = 0;
            if (u_assessments != null)
                num_assessments = u_assessments.Count;
            litNumAssessments.Text = "Member has taken <strong>" + num_assessments + " assessments</strong>";
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            // get all send events
            string sqlCode = string.Empty;

            sqlCode = "SELECT * FROM qCom_SendEvents_View WHERE (Available = 'Yes' AND Running = 'Yes' AND Recurring = 'Yes' AND GetDate() > StartDate) OR (Available = 'Yes' AND Running = 'Yes' AND Recurring = 'No' AND (GetDate() Between StartDate AND StartDate+1)) ORDER BY Priority ASC";
            qDbs_SQLcode sql = new qDbs_SQLcode();
            SqlDataReader eReader = sql.GetDataReader(sqlCode);

            if (eReader.HasRows)
            {
                while (eReader.Read())
                {
                    // see if there are custom email preferences if this send event is associated with a campaign
                    int campaign_id = 0;
                    string custom_email = string.Empty;
                    string custom_email_from = string.Empty;
                    bool get_custom_did = false;

                    if (!String.IsNullOrEmpty(Convert.ToString(eReader["CampaignID"])))
                        campaign_id = Convert.ToInt32(eReader["CampaignID"]);

                    if (campaign_id > 0)
                    {
                        var pref = qCom_CampaignPreference.GetCampaignPreferences(campaign_id);
                        if (pref != null)
                        {
                            if (pref.CampaignPreferenceID > 0)
                            {
                                if (!String.IsNullOrEmpty(pref.CampaignEmail))
                                    custom_email = pref.CampaignEmail;
                                if (!String.IsNullOrEmpty(pref.CampaignEmailFrom))
                                    custom_email_from = pref.CampaignEmailFrom;

                                // see if we need to get / integrated a custom DID
                                if (pref.IncludeCustomDID == true)
                                    get_custom_did = true;
                            }
                        }
                    }

                    // get email preferences
                    string sqlCode2 = "SELECT TOP(1) * FROM qCom_EmailPreferences WHERE Available = 'Yes'";
                    SqlDataReader pReader = sql.GetDataReader(sqlCode2);

                    pReader.Read();
                    string header = Convert.ToString(pReader["Header"]);
                    string footer = Convert.ToString(pReader["Footer"]);
                    string unsubscribe = Convert.ToString(pReader["Unsubscribe"]);
                    string fromEmailAddress = string.Empty;
                    string fromName = string.Empty;
                    if (!String.IsNullOrEmpty(custom_email))
                        fromEmailAddress = custom_email;
                    else
                        fromEmailAddress = Convert.ToString(pReader["FromEmailAddress"]);
                    if (!String.IsNullOrEmpty(custom_email_from))
                        fromName = custom_email_from;
                    else
                        fromName = Convert.ToString(pReader["fromName"]);
                    pReader.Close();

                    //try
                    //{
                        lblMessage.Text += "<br>Sending...";
                        // create object
                        int emailID = Convert.ToInt32(eReader["emailID"]);
                        string contactQuery = "SELECT " + Convert.ToString(eReader["sqlSELECT"]) + " FROM " + Convert.ToString(eReader["sqlFROM"]) + " WHERE " + Convert.ToString(eReader["sqlWHERE"]);
                        bool is_contact_list = false;
                        if (Convert.ToString(eReader["sqlFROM"]).Contains("qCom_Contacts"))
                            is_contact_list = true;

                        qCom_EmailTool email = new qCom_EmailTool(emailID);

                        // get addresses
                        string[][] contacts = email.GetSendEventContacts(contactQuery, get_custom_did, campaign_id, Convert.ToInt32(Context.Items["ScopeID"]), is_contact_list);

                        string messageBody = string.Empty;
                        string includeHeader = Convert.ToString(eReader["IncludeHeader"]);
                        string includeFooter = Convert.ToString(eReader["IncludeFooter"]);
                        string includeUnsubscribe = Convert.ToString(eReader["IncludeUnsubscribe"]);

                        if (includeHeader == "Yes")
                        {
                            messageBody += header;
                        }

                        messageBody += email.emailDraft;

                        if (includeFooter == "Yes")
                        {
                            messageBody += footer;
                        }
                        if (includeUnsubscribe == "Yes")
                        {
                            messageBody += unsubscribe;
                        }

                        //(string[][] addresses, string strFrom, string strFromEmail, string requestURL, string strSubject, string rawEmailContent, string userID, string value1, string value2, bool sendCopyToAdmins, bool noDuplicatesToday, bool noDontSend, int emailID)
                        ArrayList[] output = email.SendMail(contacts, fromName, fromEmailAddress, "bulkemail", email.emailSubject, messageBody, "", "", "", "", "", false, true, true, emailID, get_custom_did, campaign_id);

                        lblMessage.Text += "finished sending email: " + email.emailSubject + "; send event id = " + Convert.ToString(eReader["SendEventID"]) + "; number of recipients=" + contacts.Length;
                    //}
                    //catch
                    //{
                    //    lblMessage.Text += "A problem has occurred<br>";
                    //}
                }

                eReader.Close();

            }
            else
            {
                lblMessage.Text += "There are no scheduled send events.<br>";
            }

        }
        else
        {
            lblMessage.Text += "Problem with key or page incorrectly loaded.<br>";
        }
    }
    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["pollID"]))
            {
                poll_id = Convert.ToInt32(Request.QueryString["pollID"]);
                qSoc_Poll2 poll = new qSoc_Poll2(poll_id);

                poll.Question = txtQuestion.Text;
                poll.LastModified = DateTime.Now;
                poll.LastModifiedBy = user_id;
                if (!String.IsNullOrEmpty(ddlTheme.SelectedValue))
                    poll.ThemeID = Convert.ToInt32(ddlTheme.SelectedValue);
                else
                    poll.ThemeID = 0;

                DateTime start_time = new DateTime();
                DateTime end_time = new DateTime();
                if (rblAvailable.SelectedValue == "Yes")
                {
                    poll.Available = "Yes";
                    start_time = DateTime.Now;
                    end_time = DateTime.Now.AddYears(10);
                    poll.StartDate = start_time;
                    poll.EndDate = end_time;

                    /*
                    // code no longer used since use defaults for setting these values
                    if (!String.IsNullOrEmpty(Convert.ToString(rdtStartTime.SelectedDate)))
                        poll.StartDate = Convert.ToDateTime(rdtStartTime.SelectedDate);
                    if (!String.IsNullOrEmpty(Convert.ToString(rdtEndTime.SelectedDate)))
                        poll.EndDate = Convert.ToDateTime(rdtEndTime.SelectedDate);
                     */
                }
                else
                {
                    poll.Available = "No";
                    start_time = DateTime.Now.AddDays(-2);
                    end_time = DateTime.Now.AddDays(-1);
                    poll.StartDate = start_time;
                    poll.EndDate = end_time;

                    /*
                    // code no longer used since use defaults for setting these values
                    if (!String.IsNullOrEmpty(Convert.ToString(rdtStartTime.SelectedDate)))
                        poll.StartDate = null;
                    if (!String.IsNullOrEmpty(Convert.ToString(rdtEndTime.SelectedDate)))
                        poll.EndDate = null;
                    */
                }

                poll.Update();
            }
            else
            {
                qSoc_Poll2 poll = new qSoc_Poll2();
                poll.ScopeID = 1;
                poll.Created = DateTime.Now;
                poll.CreatedBy = user_id;
                poll.LastModified = DateTime.Now;
                poll.LastModifiedBy = user_id;
                poll.Available = "Yes";
                poll.MarkAsDelete = 0;
                poll.Question = txtQuestion.Text;
                if (ddlPollType.SelectedValue == "Think")
                {
                    poll.PollType = "Opinion";
                    poll.ExperienceType = "Think";
                }
                else if (ddlPollType.SelectedValue == "Fact")
                {
                    poll.PollType = "Fact";
                    poll.ExperienceType = "Poll";
                }
                else if (ddlPollType.SelectedValue == "Opinion")
                {
                    poll.PollType = "Opinion";
                    poll.ExperienceType = "Poll";
                }
                poll.Available = "No";

                if (!String.IsNullOrEmpty(ddlTheme.SelectedValue))
                    poll.ThemeID = Convert.ToInt32(ddlTheme.SelectedValue);

                // default to start time is today and end time is 20 years from now
                poll.StartDate = DateTime.Now;
                poll.EndDate = DateTime.Now.AddYears(20);

                poll.Insert();
                /*
                if (!String.IsNullOrEmpty(Convert.ToString(rdtStartTime.SelectedDate)))
                    poll.StartDate = Convert.ToDateTime(rdtStartTime.SelectedDate);
                if (!String.IsNullOrEmpty(Convert.ToString(rdtEndTime.SelectedDate)))
                    poll.EndDate = Convert.ToDateTime(rdtEndTime.SelectedDate);
                 */

                poll_id = poll.PollID;

                if (ddlPollType.SelectedValue == "Think")
                {
                    int curr_choice_id = createNewChoice(poll_id, "Agree", false);
                    curr_choice_id = createNewChoice(poll_id, "Disagree", false);
                }
            }

            // process if highlighted poll
            qDbs_SQLcode sql = new qDbs_SQLcode();
            string sqlCode = string.Empty;
            sqlCode = "UPDATE qSoc_Polls SET Highlighted = null";

            if (lblHighlightedMessage.Text.Contains("current") && chkHighlightedPoll.Checked == false)
            {
                sql.ExecuteSQL(sqlCode);        // // clear all highlighted options
            }
            else if (chkHighlightedPoll.Checked && lblHighlightedMessage.Text.Contains("current"))
            {
                sql.ExecuteSQL(sqlCode);        // clear all highlighted options
                qSoc_Poll2 poll = new qSoc_Poll2(poll_id);
                poll.Highlighted = true;
                poll.Update();
            }
            else if (chkHighlightedPoll.Checked && lblHighlightedMessage.Text.Contains("Check"))
            {
                sql.ExecuteSQL(sqlCode);        // clear all highlighted options
                qSoc_Poll2 poll = new qSoc_Poll2(poll_id);
                poll.Highlighted = true;
                poll.Update();
            }

            // add keywords
            string owner_keywords = string.Empty;
            qPtl_KeywordReference.DeleteKeywordReferencesByContent((int)qSoc_ContentType.Types.Poll, poll_id);
            foreach (ListItem item in cblKeywords.Items)
            {
                if (item.Selected)
                {
                    if (!String.IsNullOrEmpty(owner_keywords))
                        owner_keywords += "," + item.Text;
                    else
                        owner_keywords += item.Text;
                    qPtl_KeywordReference keyword = new qPtl_KeywordReference();
                    keyword.Available = "Yes";
                    keyword.ScopeID = Convert.ToInt32(Context.Items["ScopeID"]);
                    keyword.KeywordID = Convert.ToInt32(item.Value);
                    keyword.ContentTypeID = (int)qSoc_ContentType.Types.Poll;
                    keyword.ReferenceID = poll_id;
                    keyword.Created = DateTime.Now;
                    keyword.LastModified = DateTime.Now;
                    keyword.CreatedBy = Convert.ToInt32(Context.Items["UserID"]);
                    keyword.LastModifiedBy = Convert.ToInt32(Context.Items["UserID"]);
                    keyword.MarkAsDelete = 0;
                    keyword.Insert();
                }
            }

            string reserved_keywords = string.Empty;
            foreach (ListItem item in chkTopics.Items)
            {
                if (item.Selected)
                {
                    if (!String.IsNullOrEmpty(reserved_keywords))
                        reserved_keywords += "," + item.Text;
                    else
                        reserved_keywords += item.Text;
                }
            }

            qSoc_Feed feed = new qSoc_Feed((int)qSoc_ContentType.Types.Poll, poll_id);

            if (!chkDisplayInFeed.Checked && !chkDisplayInExplore.Checked)
            {
                if (feed != null)
                {
                    if (feed.FeedID > 0)
                    {
                        feed.MarkAsDelete = 1;
                        feed.Available = "No";
                        feed.ReservedKeywords = reserved_keywords;
                        if (!chkDisplayInFeed.Checked)
                            feed.VisibleFeed = false;
                        if (!chkDisplayInExplore.Checked)
                            feed.VisibleExplore = false;
                        feed.Update();
                    }
                }
            }
            else if (chkDisplayInFeed.Checked || chkDisplayInExplore.Checked || !string.IsNullOrEmpty(reserved_keywords))
            {
                qSoc_Poll2 poll = new qSoc_Poll2(poll_id);

                int p_user_id = user_id;
                if (post_as_user_id > 0)
                    p_user_id = post_as_user_id;

                qPtl_User user = new qPtl_User(p_user_id);
                var u_space = qSoc_UserSpace_View.GetUserSpaces(poll.CreatedBy);

                // evaluate title and description
                string p_title = q_Helper.replaceSpecialCharacters(poll.Question);
                string p_description = string.Empty;
                // add choices to description field
                var choices = qSoc_PollChoice2.GetAvailablePollChoices(poll_id);

                string choices_html = string.Empty;
                int i = 1;
                if (choices != null)
                {
                    foreach (var c in choices)
                    {
                        if (!String.IsNullOrEmpty(choices_html))
                            choices_html += "<br>";
                        choices_html += i + ") " + c.Choice;
                        i++;
                    }
                }

                if (!String.IsNullOrEmpty(choices_html))
                {
                    p_description = choices_html;
                }

                if (feed != null)
                {
                    if (feed.FeedID > 0)
                    {
                        feed.CreatedBy = user.UserID;
                        feed.Available = poll.Available;
                        if (chkMoveToTop.Checked)
                            feed.LastModified = DateTime.Now;
                        feed.LastModifiedBy = user.UserID;
                        feed.MarkAsDelete = poll.MarkAsDelete;
                        feed.OwnerMarkAsDelete = poll.MarkAsDelete;
                        feed.ContentTypeID = (int)qSoc_ContentType.Types.Poll;
                        feed.ReferenceID = poll_id;
                        feed.OwnerID = user.UserID;
                        feed.OwnerName = user.UserName;
                        feed.OwnerProfilePic = user.ProfilePict;
                        feed.Type = "poll";
                        feed.Title = p_title;
                        feed.Description = p_description;
                        feed.Body = p_description;
                        feed.OwnerRole = user.HighestRole;
                        feed.OwnerRoleID = user.HighestRank;
                        feed.OwnerKeywords = owner_keywords;
                        feed.ReservedKeywords = reserved_keywords;
                        feed.UploadedFrom = "manager";
                        if (!String.IsNullOrEmpty(ddlTheme.SelectedValue))
                        {
                            feed.ThemeID = Convert.ToInt32(ddlTheme.SelectedValue);
                            feed.ThemeName = Convert.ToString(ddlTheme.SelectedItem);
                        }
                        if (chkDisplayInFeed.Checked)
                            feed.VisibleFeed = true;
                        else
                            feed.VisibleFeed = false;
                        if (chkDisplayInExplore.Checked)
                            feed.VisibleExplore = true;
                        else
                            feed.VisibleExplore = false;
                        feed.Update();
                    }
                    else
                    {
                        // create new feed item
                        if (u_space != null)
                        {
                            foreach (var s in u_space)
                            {
                                feed.SpaceID = s.SpaceID;
                                feed.SpaceName = s.SpaceShortName;
                            }
                        }
                        feed.ScopeID = Convert.ToInt32(Context.Items["ScopeID"]);
                        feed.Available = poll.Available;
                        feed.Created = DateTime.Now;
                        feed.CreatedBy = user.UserID;
                        feed.LastModified = DateTime.Now;
                        feed.LastModifiedBy = user.UserID;
                        feed.MarkAsDelete = poll.MarkAsDelete;
                        feed.OwnerMarkAsDelete = poll.MarkAsDelete;
                        feed.ContentTypeID = (int)qSoc_ContentType.Types.Poll;
                        feed.ReferenceID = poll_id;
                        feed.OwnerID = user.UserID;
                        feed.OwnerName = user.UserName;
                        feed.OwnerProfilePic = user.ProfilePict;
                        feed.Type = "poll";
                        feed.Title = p_title;
                        feed.Description = p_description;
                        feed.Body = p_description;
                        feed.OwnerRole = user.HighestRole;
                        feed.OwnerRoleID = user.HighestRank;

                        feed.VisibleAll = true;
                        feed.VisibleFriends = true;
                        feed.VisibleFollowers = true;
                        feed.VisibleSpace = true;
                        feed.VisiblePrivate = true;
                        feed.VisibleFeed = true;
                        feed.VisibleOwnerFeed = true;
                        feed.VisibleOwnerProfile = true;
                        if (!String.IsNullOrEmpty(ddlTheme.SelectedValue))
                        {
                            feed.ThemeID = Convert.ToInt32(ddlTheme.SelectedValue);
                            feed.ThemeName = Convert.ToString(ddlTheme.SelectedItem);
                        }
                        feed.ReservedKeywords = reserved_keywords;
                        if (!String.IsNullOrEmpty(owner_keywords))
                        {
                            feed.OwnerKeywords = owner_keywords;
                        }
                        feed.UploadedFrom = "manager";
                        if (chkDisplayInFeed.Checked)
                            feed.VisibleFeed = true;
                        else
                            feed.VisibleFeed = false;
                        if (chkDisplayInExplore.Checked)
                            feed.VisibleExplore = true;
                        else
                            feed.VisibleExplore = false;
                        feed.Insert();
                    }
                }
            }

            // redirect to page to add poll + keywords
            if (!String.IsNullOrEmpty(Request.QueryString["pollID"]))
            {
                Response.Redirect("poll-edit.aspx?pollID=" + poll_id);
            }
            else
            {
                Response.Redirect(Request.Url.ToString() + "?mode=add-successful&pollID=" + poll_id);
            }
        }
        else
        {
            lblMessage.Text = "*** A problem has occurred -- make sure all the required information has been entered ***";
            lblMessageBottom.Text = "*** A problem has occurred -- make sure all the required information has been entered ***";
        }
    }
    protected void btnSave_OnClick(object sender, System.EventArgs e)
    {
        int user_id = Convert.ToInt32(Context.Items["UserID"]);

        if (!String.IsNullOrEmpty(Request.QueryString["BlogID"]))
        {
            blog_id = Convert.ToInt32(Request.QueryString["BlogID"]);
            qSoc_Blog2 blog = new qSoc_Blog2(blog_id);
            blog.Title = txtTitle.Text;
            blog.Summary = txtSummary.Text;
            blog.Text = reContent.Content;
            blog.LastModified = DateTime.Now;
            blog.LastModifiedBy = user_id;
            if (!String.IsNullOrEmpty(ddlAuthor.SelectedValue))
                blog.AuthorID = Convert.ToInt32(ddlAuthor.SelectedValue);
            if (!String.IsNullOrEmpty(ddlTheme.SelectedValue))
                blog.ThemeID = Convert.ToInt32(ddlTheme.SelectedValue);
            blog.Available = rblAvailable.SelectedValue;
            blog.Type = rblType.SelectedValue;
            blog.ApprovedStatus = ddlStatus.SelectedValue;
            if (ddlStatus.SelectedValue == "Approved")
            {
                blog.ApprovedBy = user_id;
                blog.Approved = DateTime.Now;
            }
            blog.Update();
        }
        else
        {
            qSoc_Blog2 blog = new qSoc_Blog2();
            blog.ScopeID = 1;
            blog.Created = DateTime.Now;
            blog.CreatedBy = user_id;
            blog.LastModified = DateTime.Now;
            blog.LastModifiedBy = user_id;
            blog.Available = "Yes";
            blog.MarkAsDelete = 0;
            blog.UserID = user_id;
            blog.Title = txtTitle.Text;
            blog.Summary = txtSummary.Text;
            blog.Text = reContent.Content;
            blog.LastModified = DateTime.Now;
            blog.LastModifiedBy = user_id;
            if (!String.IsNullOrEmpty(ddlAuthor.SelectedValue))
                blog.AuthorID = Convert.ToInt32(ddlAuthor.SelectedValue);
            if (!String.IsNullOrEmpty(ddlTheme.SelectedValue))
                blog.ThemeID = Convert.ToInt32(ddlTheme.SelectedValue);
            blog.Available = rblAvailable.SelectedValue;
            blog.Type = rblType.SelectedValue;
            blog.ApprovedStatus = ddlStatus.SelectedValue;
            if (ddlStatus.SelectedValue == "Approved")
            {
                blog.ApprovedBy = user_id;
                blog.Approved = DateTime.Now;
            }
            blog.UploadedFrom = "manager";
            blog.Insert();

            blog_id = blog.BlogID;
        }

        string user_name = (new qPtl_User(user_id)).UserName;

        // add keywords
        string owner_keywords = string.Empty;
        qPtl_KeywordReference.DeleteKeywordReferencesByContent((int)qSoc_ContentType.Types.Story, blog_id);
        foreach (ListItem item in cblKeywords.Items)
        {
            if (item.Selected)
            {
                if (!String.IsNullOrEmpty(owner_keywords))
                    owner_keywords += "," + item.Text;
                else
                    owner_keywords += item.Text;
                qPtl_KeywordReference keyword = new qPtl_KeywordReference();
                keyword.Available = "Yes";
                keyword.ScopeID = Convert.ToInt32(Context.Items["ScopeID"]);
                keyword.KeywordID = Convert.ToInt32(item.Value);
                keyword.ContentTypeID = (int)qSoc_ContentType.Types.Story;
                keyword.ReferenceID = blog_id;
                keyword.Created = DateTime.Now;
                keyword.LastModified = DateTime.Now;
                keyword.CreatedBy = Convert.ToInt32(Context.Items["UserID"]);
                keyword.LastModifiedBy = Convert.ToInt32(Context.Items["UserID"]);
                keyword.MarkAsDelete = 0;
                keyword.Insert();
            }
        }

        string reserved_keywords = string.Empty;
        foreach (ListItem item in chkTopics.Items)
        {
            if (item.Selected)
            {
                if (!String.IsNullOrEmpty(reserved_keywords))
                    reserved_keywords += "," + item.Text;
                else
                    reserved_keywords += item.Text;
            }
        }

        // process if highlighted blog
        qDbs_SQLcode sql = new qDbs_SQLcode();
        string sqlCode = string.Empty;
        sqlCode = "UPDATE qSoc_Blogs SET Highlighted = null";

        if (lblHighlightedMessage.Text.Contains("current") && chkHighlightedItem.Checked == false)
        {
            sql.ExecuteSQL(sqlCode);        // clear all highlighted options
        }
        else if (chkHighlightedItem.Checked && lblHighlightedMessage.Text.Contains("current"))
        {
            sql.ExecuteSQL(sqlCode);        // clear all highlighted options
            qSoc_Blog2 curr_item = new qSoc_Blog2(blog_id);
            curr_item.Highlighted = true;
            curr_item.Update();
        }
        else if (chkHighlightedItem.Checked && lblHighlightedMessage.Text.Contains("Check"))
        {
            sql.ExecuteSQL(sqlCode);        // clear all highlighted options
            qSoc_Blog2 blog = new qSoc_Blog2(blog_id);
            blog.Highlighted = true;
            blog.Update();
        }

        qSoc_Feed feed = new qSoc_Feed((int)qSoc_ContentType.Types.Story, blog_id);

        if (!chkDisplayInFeed.Checked && !chkDisplayInExplore.Checked)
        {
            if (feed != null)
            {
                if (feed.FeedID > 0)
                {
                    feed.MarkAsDelete = 1;
                    feed.Available = "No";
                    feed.ReservedKeywords = reserved_keywords;
                    if (!chkDisplayInFeed.Checked)
                        feed.VisibleFeed = false;
                    if (!chkDisplayInExplore.Checked)
                        feed.VisibleExplore = false;
                    feed.Update();
                }
            }
        }
        else if (chkDisplayInFeed.Checked || chkDisplayInExplore.Checked || !string.IsNullOrEmpty(reserved_keywords))
        {
            qSoc_Blog2 blog = new qSoc_Blog2(blog_id);

            int p_user_id = user_id;
            if (post_as_user_id > 0)
                p_user_id = post_as_user_id;

            qPtl_User user = new qPtl_User(p_user_id);
            var u_space = qSoc_UserSpace_View.GetUserSpaces(blog.CreatedBy);

            // evaluate title and description
            string p_title = blog.Title.Replace("'", "\"");
            p_title = q_Helper.replaceSpecialCharacters(p_title);
            string p_description = q_Helper.replaceSpecialCharacters(blog.Summary);

            if (feed != null)
            {
                if (feed.FeedID > 0)
                {
                    feed.CreatedBy = user.UserID;
                    feed.Available = blog.Available;
                    if (chkMoveToTop.Checked)
                        feed.LastModified = DateTime.Now;
                    feed.LastModifiedBy = user.UserID;
                    feed.MarkAsDelete = blog.MarkAsDelete;
                    feed.OwnerMarkAsDelete = blog.MarkAsDelete;
                    feed.ContentTypeID = (int)qSoc_ContentType.Types.Story;
                    feed.ReferenceID = blog_id;
                    feed.OwnerID = user.UserID;
                    feed.OwnerName = user.UserName;
                    feed.OwnerProfilePic = user.ProfilePict;
                    feed.Type = "blog";
                    feed.Title = p_title;
                    feed.Description = p_description;
                    feed.Body = p_description;
                    feed.OwnerRole = user.HighestRole;
                    feed.OwnerRoleID = user.HighestRank;
                    feed.OwnerKeywords = owner_keywords;
                    feed.ReservedKeywords = reserved_keywords;
                    feed.UploadedFrom = "manager";
                    if (!String.IsNullOrEmpty(ddlTheme.SelectedValue))
                    {
                        feed.ThemeID = Convert.ToInt32(ddlTheme.SelectedValue);
                        feed.ThemeName = Convert.ToString(ddlTheme.SelectedItem);
                    }
                    if (chkDisplayInFeed.Checked)
                        feed.VisibleFeed = true;
                    else
                        feed.VisibleFeed = false;
                    if (chkDisplayInExplore.Checked)
                        feed.VisibleExplore = true;
                    else
                        feed.VisibleExplore = false;
                    feed.Update();
                }
                else
                {
                    // create new feed item
                    if (u_space != null)
                    {
                        foreach (var s in u_space)
                        {
                            feed.SpaceID = s.SpaceID;
                            feed.SpaceName = s.SpaceShortName;
                        }
                    }
                    feed.ScopeID = Convert.ToInt32(Context.Items["ScopeID"]);
                    feed.Available = blog.Available;
                    feed.Created = DateTime.Now;
                    feed.CreatedBy = user.UserID;
                    feed.LastModified = DateTime.Now;
                    feed.LastModifiedBy = user.UserID;
                    feed.MarkAsDelete = blog.MarkAsDelete;
                    feed.OwnerMarkAsDelete = blog.MarkAsDelete;
                    feed.ContentTypeID = (int)qSoc_ContentType.Types.Story;
                    feed.ReferenceID = blog_id;
                    feed.OwnerID = user.UserID;
                    feed.OwnerName = user.UserName;
                    feed.OwnerProfilePic = user.ProfilePict;
                    feed.Type = "blog";
                    feed.Title = p_title;
                    feed.Description = p_description;
                    feed.Body = p_description;
                    feed.OwnerRole = user.HighestRole;
                    feed.OwnerRoleID = user.HighestRank;

                    feed.VisibleAll = true;
                    feed.VisibleFriends = true;
                    feed.VisibleFollowers = true;
                    feed.VisibleSpace = true;
                    feed.VisiblePrivate = true;
                    feed.VisibleFeed = true;
                    feed.VisibleOwnerFeed = true;
                    feed.VisibleOwnerProfile = true;
                    if (!String.IsNullOrEmpty(ddlTheme.SelectedValue))
                    {
                        feed.ThemeID = Convert.ToInt32(ddlTheme.SelectedValue);
                        feed.ThemeName = Convert.ToString(ddlTheme.SelectedItem);
                    }
                    feed.ReservedKeywords = reserved_keywords;
                    if (!String.IsNullOrEmpty(owner_keywords))
                    {
                        feed.OwnerKeywords = owner_keywords;
                    }
                    feed.UploadedFrom = "manager";
                    if (chkDisplayInFeed.Checked)
                        feed.VisibleFeed = true;
                    else
                        feed.VisibleFeed = false;
                    if (chkDisplayInExplore.Checked)
                        feed.VisibleExplore = true;
                    else
                        feed.VisibleExplore = false;
                    feed.Insert();
                }
            }
        }

        //Response.Redirect("~/qSoc/blogs-list.aspx");
        if (!String.IsNullOrEmpty(Request.QueryString["BlogID"]))
        {
            lblMessage.Text = "*** Record Successfully Updated ***";
            lblMessageBottom.Text = "*** Record Successfully Updated ***";
        }
        else
        {
            if (!String.IsNullOrEmpty(Request.QueryString["type"]))
                Response.Redirect(Request.Url.ToString() + "&mode=add-successful&BlogID=" + blog_id);
            else
                Response.Redirect(Request.Url.ToString() + "?mode=add-successful&BlogID=" + blog_id);
        }
    }
    protected void AddRoleCampaigns(int role_id, int scope_id, qPtl_User user)
    {
        //Add role campaigns
        string sqlCode = string.Empty;
        string returnMessage = string.Empty;
        qDbs_SQLcode sql = new qDbs_SQLcode();

        sqlCode = string.Format("SELECT * FROM qSoc_RoleCampaigns WHERE RoleID = " + role_id + " AND Available = 'Yes' AND ScopeID = " + scope_id);

        int campaignID = 0;
        string progressMode = string.Empty;

        using (SqlDataReader sReader = sql.GetDataReader(sqlCode))
        {
            if (sReader.HasRows)
            {
                while (sReader.Read())
                {
                    campaignID = Convert.ToInt32(sReader["CampaignID"]);

                    qSoc_UserCampaign checkc = new qSoc_UserCampaign(user.UserID, campaignID);
                    if (checkc.UserCampaignID == 0)
                    {
                        //create campaign for user
                        qSoc_UserCampaign campaign = new qSoc_UserCampaign();
                        qSoc_Campaign cam = new qSoc_Campaign(campaign.CampaignID);

                        campaign.ScopeID = 1;
                        campaign.CampaignID = campaignID;
                        campaign.Available = "Yes";
                        campaign.Created = DateTime.Now;
                        campaign.CreatedBy = user.UserID;
                        campaign.UserID = user.UserID;
                        campaign.CampaignStatus = "In Progress";
                        // following parameters are defaults based on these campaigns being created associated to user roles and not spaces
                        campaign.SpaceID = 0;
                        campaign.EnrollmentType = "role";
                        campaign.Enrolled = DateTime.Now;
                        if (cam.SetupRequired != true)
                        {
                            campaign.CampaignStart = DateTime.Now;
                        }

                        //add campaign actions
                        int j = 0;
                        var cActions = qSoc_CampaignAction.GetCampaignActions(campaignID);
                        foreach (var i in cActions)
                        {
                            // get values
                            qSoc_UserCampaignAction cUserAction = new qSoc_UserCampaignAction();

                            cUserAction.UserID = user.UserID;
                            cUserAction.ScopeID = 1;
                            cUserAction.Available = "Yes";
                            cUserAction.Created = DateTime.Now;
                            cUserAction.CreatedBy = 0;
                            cUserAction.CampaignActionID = i.CampaignActionID;
                            if (j == 0)
                            {
                                cUserAction.Status = "In Progress";
                                campaign.CurrentCampaignActionID = i.CampaignActionID;
                            }
                            else
                            {
                                cUserAction.Status = "Not Started";
                            }

                            cUserAction.Insert();

                            j++;
                        }

                        // create campaign record now that have current campaign actionID
                        campaign.Insert();
                    }
                }
            }
        }
    }
    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 void AddSpaceCampaigns(qSoc_Space space, qPtl_User user, int scope_id)
    {
        //Add space campaigns
        string sqlCode = string.Empty;
        string returnMessage = string.Empty;
        qDbs_SQLcode sql = new qDbs_SQLcode();

        sqlCode = string.Format("SELECT * FROM qSoc_SpaceCampaigns WHERE SpaceID = " + space.SpaceID + " AND Available = 'Yes' AND ScopeID = " + scope_id);

        int campaignID = 0;
        string progressMode = string.Empty;

        using (SqlDataReader sReader = sql.GetDataReader(sqlCode))
        {
            if (sReader.HasRows)
            {
                while (sReader.Read())
                {
                    campaignID = Convert.ToInt32(sReader["CampaignID"]);

                    qSoc_UserCampaign checkc = new qSoc_UserCampaign(user.UserID, campaignID);
                    if (checkc.UserCampaignID == 0)
                    {
                        //create campaign for user
                        qSoc_Campaign campaign = new qSoc_Campaign(campaignID);

                        AddUserCampaign(campaign.CampaignID, scope_id, user);
                    }
                }
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            profile_id = Convert.ToInt32(Request.QueryString["userID"]);

            qPtl_User profile = new qPtl_User(profile_id);

            hplManageTrainings.NavigateUrl = "member-learning.aspx?userID=" + profile_id;
            string nav_mode = System.Configuration.ConfigurationManager.AppSettings["Site_NavMode"];
            if (nav_mode == "lms")
                plhSchoolDisplay.Visible = false;

            string img_url = string.Empty;
            string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/";

            if (!String.IsNullOrEmpty(profile.ProfilePict))
                img_url = baseUrl + "user_data/" + profile.UserName + "/" + profile.ProfilePict + ".ashx?width=84&height=84&mode=crop";
            else
                img_url = baseUrl + "images/mylife_portrait_default.jpg.ashx?width=84&height=84&mode=crop";

            litProfilePict.Text = "<img src=\"" + img_url + "\" />";

            lblUsername.Text = profile.UserName;
            lblFullName.Text = profile.FirstName + " " + profile.LastName;
            lblEmail.Text = profile.Email;
            lblUserID.Text = Convert.ToString(profile.UserID);
            lblCreated.Text = Convert.ToString(profile.Created);
            lblMostRecentLogin.Text = Convert.ToString(profile.LastTimeSeen);
            lblMostRecentIPAddress.Text = profile.LastIPAddress;
            lblRoleName.Text = profile.HighestRole;

            txtFirstName.Text = profile.FirstName;
            txtLastName.Text = profile.LastName;
            txtEmail.Text = profile.Email;
            lblUsernameProfile.Text = profile.UserName;
            if (profile.HighestRole == "Mobile")
            {
                lblMemberTypeProfile.Text = "Mobile Only";
            }
            else
            {
                lblMemberTypeProfile.Text = "Social";
                required_indicator = " *";
                if (race_required == true)
                    race_required_indicator = " *";
            }

            qPtl_UserProfile full_profile = new qPtl_UserProfile(profile_id);
            DateTime check = new DateTime();
            check = Convert.ToDateTime("1/1/1900");
            if (full_profile.DOB != check)
            {
                try
                {
                    rdtDOB.SelectedDate = Convert.ToDateTime(full_profile.DOB).Date;
                }
                catch
                {
                    // do nothing
                }
            }

            var user_space = qSoc_UserSpace_View.GetMostRecentUserspace(profile_id);

            if (user_space != null)
            {
                if (user_space.UserSpaceID > 0)
                {
                    lblSchool.Text = user_space.School;
                    string full_info = string.Empty;
                    full_info = user_space.SpaceShortName;
                    if (!String.IsNullOrEmpty(user_space.CategoryName))
                        full_info += " [" + user_space.CategoryName + "]";
                    if (!String.IsNullOrEmpty(user_space.School))
                        full_info += " at " + user_space.School;
                    lblGroupTabGroupName.Text = "<a href=\"/manage/members/space-edit.aspx?spaceID=" + user_space.SpaceID + "\">" + full_info + " <i class=\"icon-circle-arrow-right\"></i></a>";
                    string full_group_name = user_space.SpaceShortName;
                    if (!String.IsNullOrEmpty(user_space.CategoryName))
                        full_group_name += " [" + user_space.CategoryName + "]";
                    lblGroupName.Text = "<a href=\"/manage/members/space-edit.aspx?spaceID=" + user_space.SpaceID + "\">" + full_group_name + " <i class=\"icon-circle-arrow-right\"></i></a>";
                }
                else
                {
                    btnChangeGroup.Text = "Add To Group";
                }
            }

            // profile gender
            string gender_options = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["Register_SupportedGenderValues"]);
            ddlGender.Items.FindByValue("Intersex").Enabled = false;
            ddlGender.Items.FindByValue("Transgender").Enabled = false;
            if (gender_options.Contains("Intersex"))
                ddlGender.Items.FindByValue("Intersex").Enabled = true;
            if (gender_options.Contains("Transgender"))
                ddlGender.Items.FindByValue("Transgender").Enabled = true;
            ddlGender.SelectedValue = full_profile.Gender;

            // evaluate race
            if (!String.IsNullOrEmpty(full_profile.Race))
            {
                if (full_profile.Race.Contains("Asian/SouthAsian"))
                    cblRace.Items.FindByValue("Asian/SouthAsian").Selected = true;
                if (full_profile.Race.Contains("Biracial"))
                    cblRace.Items.FindByValue("Biracial").Selected = true;
                if (full_profile.Race.Contains("Black/African American"))
                    cblRace.Items.FindByValue("Black/African American").Selected = true;
                if (full_profile.Race.Contains("Latino/a"))
                    cblRace.Items.FindByValue("Latino/a").Selected = true;
                if (full_profile.Race.Contains("Middle Eastern"))
                    cblRace.Items.FindByValue("Middle Eastern").Selected = true;
                if (full_profile.Race.Contains("Multiracial"))
                    cblRace.Items.FindByValue("Multiracial").Selected = true;
                if (full_profile.Race.Contains("Pacific Islander"))
                    cblRace.Items.FindByValue("Pacific Islander").Selected = true;
                if (full_profile.Race.Contains("White/European-American"))
                    cblRace.Items.FindByValue("White/European-American").Selected = true;
            }

            // **** PERMISSIONS ****
            string sqlCode = string.Empty;
            qDbs_SQLcode sql = new qDbs_SQLcode();
            q_Helper helper = new q_Helper();

            // get roles
            sqlCode = "SELECT RoleID, RoleName FROM qPtl_Roles WHERE Available = 'Yes' ORDER BY RoleRank";

            DataTable dtRoles;

            using (dtRoles = sql.GetDataTable(sqlCode))
            {

                cblRoles.DataSource = dtRoles;
                cblRoles.DataValueField = "RoleID";
                cblRoles.DataTextField = "RoleName";
                cblRoles.DataBind();
            }

            // mark current permissions
            sqlCode = "SELECT RoleID FROM qPtl_UserRoles WHERE UserID = " + Request.QueryString["userID"];

            SqlDataReader rReader;

            using (rReader = sql.GetDataReader(sqlCode))
            {
                while (rReader.Read())
                {
                    ListItem currentCheckBox = cblRoles.Items.FindByValue(rReader["RoleID"].ToString());
                    if (currentCheckBox != null)
                    {
                        currentCheckBox.Selected = true;
                    }
                }
            }

            // *** GROUP ***
            // load group information and all other available groups
            ddlSpaces.DataSource = qSoc_Space.GetSpaces();
            ddlSpaces.DataTextField = "SpaceShortName";
            ddlSpaces.DataValueField = "SpaceID";
            ddlSpaces.DataBind();
            ddlSpaces.Items.Insert(0, new ListItem("", "0"));

            /* // no longer used since we now want to automatically remove any existing user spaces from the list of options for adding
            if (user_space != null)
            {
                if (user_space.UserSpaceID > 0)
                {
                    ddlSpaces.SelectedValue = Convert.ToString(user_space.SpaceID);
                }
            }
            */

            // get other groups enrolled
            var u_groups = qSoc_UserSpace_View.GetAllAvailableUserSpacesOrderMostRecent(profile_id);
            if (u_groups != null)
            {
                int j = 0;
                string group_list = string.Empty;
                foreach (var g in u_groups)
                {
                    Quartz.Controls.MemberEnrolledGroup curr_group = (Quartz.Controls.MemberEnrolledGroup)LoadControl("~/manage/members/controls/MemberEnrolledGroup.ascx");
                    curr_group.UserSpaceID = g.UserSpaceID;
                    curr_group.UserID = g.UserID;
                    curr_group.SpaceID = g.SpaceID;
                    if (g.PrimarySpace == true)
                        curr_group.IsPrimary = true;
                    pnlUserGroups.Controls.Add(curr_group);

                    // remove each of these spaces from the spaces pull down
                    if (ddlSpaces.Items.Count > 0)
                    {
                        try
                        {
                            ddlSpaces.Items.FindByValue(Convert.ToString(g.SpaceID)).Enabled = false;
                        }
                        catch
                        {
                            // do nothing
                        }
                    }
                    j++;
                }
            }

            // *** TAB MANAGEMENT ***
            string curr_tab = string.Empty;
            curr_tab = Request.QueryString["currTab"];
            litOverviewClass.Text = "";
            litProfileClass.Text = "";
            litPermissionClass.Text = "";
            litGroupClass.Text = "";
            litWarningsClass.Text = "";
            litTabOverviewClass.Text = "class=\"tab-pane\"";
            litTabProfileClass.Text = "class=\"tab-pane\"";
            litTabPermissionsClass.Text = "class=\"tab-pane\"";
            litTabWarningsClass.Text = "class=\"tab-pane\"";
            litTabGroupClass.Text = "class=\"tab-pane\"";
            if (curr_tab == "profile")
            {
                litProfileClass.Text = "class='active'";
                litTabProfileClass.Text = "class=\"tab-pane active\"";
                if (!String.IsNullOrEmpty(Request.QueryString["message"]))
                    lblProfileMessage.Text = " *** " + Request.QueryString["message"] + "***";
            }
            else if (curr_tab == "permissions")
            {
                litPermissionClass.Text = "class='active'";
                litTabPermissionsClass.Text = "class=\"tab-pane active\"";
                if (!String.IsNullOrEmpty(Request.QueryString["message"]))
                    lblPermissionsMessage.Text = " *** " + Request.QueryString["message"] + "***";
            }
            else if (curr_tab == "group")
            {
                litGroupClass.Text = "class='active'";
                litTabGroupClass.Text = "class=\"tab-pane active\"";
                if (!String.IsNullOrEmpty(Request.QueryString["message"]))
                    lblGroupMessage.Text = " *** " + Request.QueryString["message"] + "***<br><br>";
            }
            else if (curr_tab == "warnings")
            {
                litWarningsClass.Text = "class='active'";
                litTabWarningsClass.Text = "class=\"tab-pane active\"";
            }
            else
            {
                litOverviewClass.Text = "class='active'";
                litTabOverviewClass.Text = "class=\"tab-pane active\"";
            }
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        // first delete all existing roles
        int user_id = Convert.ToInt32(Request.QueryString["userID"]);
        string sqlCode = "DELETE FROM qPtl_UserRoles WHERE UserID = " + user_id;
        qDbs_SQLcode sql = new qDbs_SQLcode();
        sql.ExecuteSQL(sqlCode);

        // delete from usermember group -- > cms permissions
        //qPtl_UserGroupMembers.DeleteUserGroupMember(user_id);

        // create records for all new roles
        int n;
        string selectedItems = string.Empty;

        n = 0;
        foreach (ListItem item in cblRoles.Items)
        {
            if (item.Selected)
            {
                sqlCode = "INSERT INTO qPtl_UserRoles (UserID, RoleID)";
                sqlCode += " VALUES (" + Request.QueryString["userID"] + "," + item.Value + ")";
                sql.ExecuteSQL(sqlCode);

                if (n > 0)
                {
                    selectedItems += "," + item.Value;
                }
                else
                {
                    selectedItems += item.Value;
                }
                n++;
            }
        }

        Response.Redirect("/manage/members/member-profile.aspx?userID=" + user_id + "&currTab=permissions&message=successfully updated");
    }
    protected void btnSave_OnClick(object sender, System.EventArgs e)
    {
        Page.Validate("form");

        if (Page.IsValid)
        {

            int user_id = Convert.ToInt32(Context.Items["UserID"]);
            video_id = Convert.ToInt32(Request.QueryString["videoID"]);

            string user_name = (new qPtl_User(user_id)).UserName;

            qSoc_Video video = new qSoc_Video(video_id);
            video.Title = txtTitle.Text;
            video.Description = txtDescription.Text;
            if (!String.IsNullOrEmpty(ddlTheme.SelectedValue))
                video.ThemeID = Convert.ToInt32(ddlTheme.SelectedValue);
            video.Status = "Approved";
            video.Created = video.Created;
            video.CreatedBy = video.CreatedBy;
            video.Approved = DateTime.Now;
            video.Source = lblVideoType.Text;
            video.LastModified = DateTime.Now;
            video.LastModifiedBy = user_id;
            video.Length = video.Length;
            video.EmbedCode = txtEmbed.Text;
            if (txtPreviewImage.Visible == true)
                video.ThumbnailURL = txtPreviewImage.Text;
            video.SourceVideoID = txtSourceVideoID.Text;
            if (!String.IsNullOrEmpty(ddlExternalSource.SelectedValue))
                video.ExternalSourceName = ddlExternalSource.SelectedValue;
            string author = string.Empty;
            author = ddlAuthor.SelectedValue;
            if (!String.IsNullOrEmpty(author))
                video.AuthorID = Convert.ToInt32(ddlAuthor.SelectedValue);
            video.Available = rblAvailable.SelectedValue;

            // process if highlighted video
            qDbs_SQLcode sql = new qDbs_SQLcode();
            string sqlCode = string.Empty;
            sqlCode = "UPDATE qSoc_Videos SET HighlightedWF = null";

            qSoc_HighlightedVideo.Delete(video_id);

            if (lblHighlightedMessage.Text.Contains("current") && chkHighlightedVideo.Checked == false)
            {
                sql.ExecuteSQL(sqlCode);
                video.HighlightedWF = null;
            }
            else if (chkHighlightedVideo.Checked && lblHighlightedMessage.Text.Contains("current"))
            {
                sql.ExecuteSQL(sqlCode);
                qSoc_HighlightedVideo high_video = new qSoc_HighlightedVideo();
                high_video = qSoc_HighlightedVideo.GetLatest();
                high_video.Available = "No";
                high_video.Created = DateTime.Now;
                high_video.CreatedBy = user_id;
                high_video.LastModified = DateTime.Now;
                high_video.LastModifiedBy = user_id;
                high_video.MarkAsDelete = 1;
                high_video.Status = "Hidden";
                high_video.Update();
            }
            else if (chkHighlightedVideo.Checked && lblHighlightedMessage.Text.Contains("Check"))
            {
                sql.ExecuteSQL(sqlCode);
                qSoc_HighlightedVideo new_highlighted = new qSoc_HighlightedVideo();
                new_highlighted.VideoID = video_id;
                new_highlighted.ScopeID = Convert.ToInt32(Context.Items["ScopeID"]);
                new_highlighted.Available = "Yes";
                new_highlighted.Created = DateTime.Now;
                new_highlighted.CreatedBy = user_id;
                new_highlighted.LastModified = DateTime.Now;
                new_highlighted.LastModifiedBy = user_id;
                new_highlighted.MarkAsDelete = 0;
                new_highlighted.Status = "Visible";
                new_highlighted.Insert();
                video.HighlightedWF = "Yes";
            }
            video.Update();

            // add keywords
            string owner_keywords = string.Empty;
            qPtl_KeywordReference.DeleteKeywordReferencesByContent((int)qSoc_ContentType.Types.Video, video_id);
            foreach (ListItem item in cblKeywords.Items)
            {
                if (item.Selected)
                {
                    if (!String.IsNullOrEmpty(owner_keywords))
                        owner_keywords += "," + item.Text;
                    else
                        owner_keywords += item.Text;
                    qPtl_KeywordReference keyword = new qPtl_KeywordReference();
                    keyword.Available = "Yes";
                    keyword.ScopeID = Convert.ToInt32(Context.Items["ScopeID"]);
                    keyword.KeywordID = Convert.ToInt32(item.Value);
                    keyword.ContentTypeID = (int)qSoc_ContentType.Types.Video;
                    keyword.ReferenceID = video_id;
                    keyword.Created = DateTime.Now;
                    keyword.LastModified = DateTime.Now;
                    keyword.CreatedBy = Convert.ToInt32(Context.Items["UserID"]);
                    keyword.LastModifiedBy = Convert.ToInt32(Context.Items["UserID"]);
                    keyword.MarkAsDelete = 0;
                    keyword.Insert();
                }
            }

            string reserved_keywords = string.Empty;
            foreach (ListItem item in chkTopics.Items)
            {
                if (item.Selected)
                {
                    if (!String.IsNullOrEmpty(reserved_keywords))
                        reserved_keywords += "," + item.Text;
                    else
                        reserved_keywords += item.Text;
                }
            }

            qSoc_Feed feed = new qSoc_Feed((int)qSoc_ContentType.Types.Video, video.VideoID);

            if (!chkDisplayInFeed.Checked && !chkDisplayInExplore.Checked)
            {
                if (feed != null)
                {
                    if (feed.FeedID > 0)
                    {
                        feed.MarkAsDelete = 1;
                        feed.Available = "No";
                        feed.ReservedKeywords = reserved_keywords;
                        if (!chkDisplayInFeed.Checked)
                            feed.VisibleFeed = false;
                        if (!chkDisplayInExplore.Checked)
                            feed.VisibleExplore = false;
                        feed.Update();
                    }
                }
            }
            else if (chkDisplayInFeed.Checked || chkDisplayInExplore.Checked || !string.IsNullOrEmpty(reserved_keywords))
            {
                int p_user_id = user_id;
                if (post_as_user_id > 0)
                    p_user_id = post_as_user_id;

                qPtl_User user = new qPtl_User(p_user_id);
                var u_space = qSoc_UserSpace_View.GetUserSpaces(video.CreatedBy);

                if (feed != null)
                {
                    if (feed.FeedID > 0)
                    {
                        feed.Available = video.Available;
                        feed.ScopeID = Convert.ToInt32(Context.Items["ScopeID"]);
                        feed.CreatedBy = user.UserID;
                        if (chkMoveToTop.Checked)
                            feed.LastModified = DateTime.Now;
                        feed.LastModified = video.LastModified;
                        feed.LastModifiedBy = user.UserID;
                        feed.MarkAsDelete = video.MarkAsDelete;
                        feed.OwnerMarkAsDelete = video.MarkAsDelete;
                        feed.ContentTypeID = (int)qSoc_ContentType.Types.Video;
                        feed.ReferenceID = video.VideoID;
                        feed.OwnerID = user.UserID;
                        feed.OwnerName = user.UserName;
                        feed.OwnerProfilePic = user.ProfilePict;
                        feed.Type = "video";
                        feed.Title = video.Title;
                        feed.Description = video.Description;
                        feed.OwnerRole = user.HighestRole;
                        feed.OwnerRoleID = user.HighestRank;
                        feed.OwnerKeywords = owner_keywords;
                        feed.UploadedFrom = "manager";
                        feed.ReservedKeywords = reserved_keywords;
                        feed.Thumbnail = video.ThumbnailURL;
                        if (!String.IsNullOrEmpty(ddlTheme.SelectedValue))
                        {
                            feed.ThemeID = Convert.ToInt32(ddlTheme.SelectedValue);
                            feed.ThemeName = Convert.ToString(ddlTheme.SelectedItem);
                        }
                        if (video.Source == "internal")
                        {
                            feed.VideoKey = video.ViddlerID;
                        }
                        else
                        {
                            string embed_code = Convert.ToString(video.EmbedCode);
                            feed.Embed = embed_code;
                            feed.VideoKey = null;
                        }
                        if (chkDisplayInFeed.Checked)
                            feed.VisibleFeed = true;
                        else
                            feed.VisibleFeed = false;
                        if (chkDisplayInExplore.Checked)
                            feed.VisibleExplore = true;
                        else
                            feed.VisibleExplore = false;
                        feed.Update();
                    }
                    else
                    {
                        // create new feed item
                        if (u_space != null)
                        {
                            foreach (var s in u_space)
                            {
                                feed.SpaceID = s.SpaceID;
                                feed.SpaceName = s.SpaceShortName;
                            }
                        }
                        feed.Available = video.Available;
                        feed.ScopeID = Convert.ToInt32(Context.Items["ScopeID"]);
                        feed.Created = DateTime.Now;    //video.Created;
                        feed.CreatedBy = user.UserID;
                        feed.LastModified = DateTime.Now;
                        feed.LastModifiedBy = user.UserID;
                        feed.MarkAsDelete = video.MarkAsDelete;
                        feed.OwnerMarkAsDelete = video.MarkAsDelete;
                        feed.ContentTypeID = (int)qSoc_ContentType.Types.Video;
                        feed.ReferenceID = video.VideoID;
                        feed.OwnerID = user.UserID;
                        feed.OwnerName = user.UserName;
                        feed.OwnerProfilePic = user.ProfilePict;
                        feed.Type = "video";
                        feed.Title = video.Title;
                        feed.Description = video.Description;
                        feed.OwnerRole = user.HighestRole;
                        feed.OwnerRoleID = user.HighestRank;
                        feed.OwnerKeywords = owner_keywords;
                        feed.UploadedFrom = "manager";
                        feed.ReservedKeywords = reserved_keywords;
                        feed.Thumbnail = video.ThumbnailURL;
                        if (!String.IsNullOrEmpty(ddlTheme.SelectedValue))
                        {
                            feed.ThemeID = Convert.ToInt32(ddlTheme.SelectedValue);
                            feed.ThemeName = Convert.ToString(ddlTheme.SelectedItem);
                        }
                        if (video.Source == "internal")
                        {
                            feed.VideoKey = video.ViddlerID;
                        }
                        else
                        {
                            string embed_code = Convert.ToString(video.EmbedCode);
                            feed.Embed = embed_code;
                        }

                        feed.VisibleAll = true;
                        feed.VisibleFriends = true;
                        feed.VisibleFollowers = true;
                        feed.VisibleSpace = true;
                        feed.VisiblePrivate = true;
                        feed.VisibleFeed = true;
                        feed.VisibleOwnerFeed = true;
                        feed.VisibleOwnerProfile = true;
                        if (!String.IsNullOrEmpty(owner_keywords))
                        {
                            feed.OwnerKeywords = owner_keywords;
                        }
                        if (chkDisplayInFeed.Checked)
                            feed.VisibleFeed = true;
                        else
                            feed.VisibleFeed = false;
                        if (chkDisplayInExplore.Checked)
                            feed.VisibleExplore = true;
                        else
                            feed.VisibleExplore = false;
                        feed.Insert();

                    }
                }
            }

            // see if there is a pending task for this video
            if (video.Status == "Approved")
            {
                qPtl_Task task = new qPtl_Task((int)qSoc_ContentType.Types.Video, video_id);

                if (task != null)
                {
                    if (task.TaskID > 0)
                    {
                        task.PercentCompleted = 100;
                        task.Status = "Completed";
                        task.Update();
                    }
                }
            }

            // redirect to page to add theme + keywords
            //  Response.Redirect("~/qSoc/videos-list.aspx");
            lblMessage.Text = "*** Record Successfully Updated ***";
            lblMessageBottom.Text = "*** Record Successfully Updated ***";
        }
    }
        public static DataSet GetNearestHealthProvidersByPostalCode(string postal_code)
        {
            string sqlGIS = String.Empty;
            string distance = "3500";
            string sqlWHERE = String.Empty;
            string criteria = String.Empty;

            sqlGIS = "DECLARE @Zip nvarchar(5); ";
            sqlGIS += "DECLARE @Distance int; ";
            sqlGIS += "SET @Zip = '" + postal_code + "'; ";
            sqlGIS += "SET @Distance = " + distance + "; ";
            sqlGIS += "DECLARE @GeomZip geography ";
            sqlGIS += "SET @GeomZip = (SELECT TOP(1) g.geom FROM qGis_ReferenceObjects g WHERE g.Name = @Zip ORDER BY AREA DESC) ";
            sqlGIS += "SELECT h.*, (SELECT h.Geography.STDistance(@GeomZip)/1609.344) AS Distance ";
            sqlGIS += "FROM qHtl_HealthProviders_Spatial_View h ";
            sqlGIS += "WHERE (h.Geography.STIntersects(@GeomZip.STBuffer(@Distance * 1609.344))=1) ";
            sqlGIS += "ORDER BY Distance ASC ";
            criteria += " " + distance + " miles of " + postal_code;

            qDbs_SQLcode sql = new qDbs_SQLcode();

            DataSet dsHealthProviders = new DataSet();
            dsHealthProviders = sql.GetDataSet(sqlGIS);
            return dsHealthProviders;
        }
        public static string ProcessWorkflow(Int32 workflow_id, Int32 userID)
        {
            qDbs_SQLcode sql = new qDbs_SQLcode();
            qPtl_Workflow c_workflow = new qPtl_Workflow(workflow_id);
            string returnMessage = string.Empty;

            if (c_workflow.WorkflowActionType == "sql")
            {
                // get sql and then replace the parameters
                string finalSql = c_workflow.SQL;

                // replace values
                finalSql = finalSql.Replace("{UserID}", Convert.ToString(userID));

                if (c_workflow.ReferenceID > 0)
                    finalSql = finalSql.Replace("{ReferenceID}", Convert.ToString(c_workflow.ReferenceID));

                if (c_workflow.WorkflowActionReferenceID > 0)
                    finalSql = finalSql.Replace("{WorkflowActionReferenceID}", Convert.ToString(c_workflow.WorkflowActionReferenceID));

                returnMessage = sql.ExecuteSQL(finalSql);
            }

            return returnMessage;
        }
    protected void btnSave_OnClick(object sender, EventArgs e)
    {
        Page.Validate();

        if (Page.IsValid)
        {
            // step 1: create account using registration model (single user role)
            int curr_default_role_id = Convert.ToInt32(ddlUserRoles.SelectedValue);

            RegistrationData data = new RegistrationData();
            data.scope_id = 1;
            data.invite_code = "";
            data.space_code = "";
            data.campaign_code = "";
            data.mobile_number = "";
            data.email = txtEmail.Text;
            data.username = txtUserName.Text;
            data.password = "";
            data.firstname = txtFirstName.Text;
            data.lastname = txtLastName.Text;
            data.degrees = "";
            data.position = "";
            data.agency = "";
            data.division = "";
            data.address = "";
            data.address2 = "";
            data.city = "";
            data.state = "";
            data.postal_code = "";
            data.work_phone = "";
            data.first_event = "";
            data.dob = "";
            data.gender = "";
            data.ethnicity = "";
            data.race = "";
            data.profession = "";
            data.employment_setting = "";
            data.employment_location = "";
            data.employment_sites = "";
            data.registration_type = "manager";
            data.registration_notes = "";
            data.default_role_id = curr_default_role_id;
            data.browser = "";
            data.platform = "";

            qPtl_User user = new qPtl_User();
            user = UserFunctions.RegisterNewUser(data);

            user.RegistrationNotes = txtRegistrationNotes.Text;
            user.RegistrationType = ddlRegistrationTypes.SelectedValue;
            user.Update();

            // process functional roles
            if (plhFunctionalRoles.Visible == true)
            {
                string sqlCode = string.Empty;
                string returnMessage = string.Empty;
                qDbs_SQLcode sql = new qDbs_SQLcode();

                // first delete all existing roles
                sqlCode = "DELETE FROM qLrn_UserFunctionalRoles WHERE UserID = " + user.UserID;
                sql.ExecuteSQL(sqlCode);

                // create records for all new roles
                int n;
                string selectedItems = string.Empty;

                n = 0;
                foreach (ListItem item in cblFunctionalRoles.Items)
                {
                    if (item.Selected)
                    {
                        sqlCode = "INSERT INTO qLrn_UserFunctionalRoles (UserID, FunctionalRoleID)";
                        sqlCode += " VALUES (" + user.UserID + "," + item.Value + ")";
                        sql.ExecuteSQL(sqlCode);

                        if (n > 0)
                        {
                            selectedItems += "," + item.Value;
                        }
                        else
                        {
                            selectedItems += item.Value;
                        }
                        n++;
                    }
                }

                int daysBetweenTrainings = 0;
                if (!String.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["Learning_DaysBetweenTrainings"]))
                    daysBetweenTrainings = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Learning_DaysBetweenTrainings"]);
                int daysTillUnavailable = 5000;
                DateTime seedDate = DateTime.Now;
                string trainingMode = "open";
                string surveyRequired = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["Learning_SurveyRequired"]);

                qLrn_UserTraining.manageUserTrainings(user.UserID, daysBetweenTrainings, daysTillUnavailable, trainingMode, "add", 0, seedDate, surveyRequired);

                // redirect to new user tools page
                Response.Redirect("member-profile.aspx?userID=" + user.UserID);
            }
        }
    }
        public static qPtl_User RegisterNewUser(RegistrationData data)
        {
            int existing_user_id = 0;
            int new_space_id = 0;
            string sqlCode = string.Empty;

            // Redundancy check -- write Highest Level into qPtl_User table in case DB trigger not working
            qPtl_Role role = new qPtl_Role(data.default_role_id);

            // add user
            qPtl_User new_user = new qPtl_User();
            new_user.Available = "Yes";
            new_user.OrgUnitID = data.scope_id;
            new_user.ScopeID = data.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 = data.firstname;
            new_user.LastName = data.lastname;
            new_user.Email = data.email;
            new_user.UserName = data.username;
            string password_for_storing = FormsAuthentication.HashPasswordForStoringInConfigFile(data.password, "sha1");
            new_user.Password = password_for_storing;
            new_user.AccountStatus = "Active";
            new_user.HighestRank = role.RoleRank;
            new_user.HighestRole = role.RoleName;
            new_user.Insert();
            existing_user_id = new_user.UserID;

            DateTime DOB;
            try
            {
                DOB = Convert.ToDateTime(data.dob);
            }
            catch
            {
                // no valid date so use default value
                DOB = Convert.ToDateTime("1/1/1900");
            }

            // add user profile
            qPtl_UserProfile new_profile = new qPtl_UserProfile();
            new_profile.UserID = existing_user_id;
            new_profile.ScopeID = data.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.Division = data.division;
            new_profile.Agency = data.agency;
            new_profile.Position = data.position;
            new_profile.Degrees = data.degrees;
            new_profile.Address1 = data.address;
            new_profile.Address2 = data.address2;
            new_profile.City = data.city;
            new_profile.StateProvince = data.state;
            new_profile.PostalCode = data.postal_code;
            new_profile.Country = data.country;
            new_profile.Gender = data.gender;
            new_profile.DOB = DOB;
            new_profile.Race = data.race;
            new_profile.EmploymentLocation = data.employment_location;
            new_profile.EmploymentSetting = data.employment_setting;
            new_profile.WorkSites = data.employment_sites;
            new_profile.Profession = data.profession;
            new_profile.Phone1 = data.work_phone;
            new_profile.Phone1Type = "work";
            new_profile.Insert();

            qPtl_User user = new qPtl_User(existing_user_id);

            // add user communication preference
            if (!String.IsNullOrEmpty(user.Email))
            {
                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();
            }

            // ****************************************************
            // 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();
             */
            qDbs_SQLcode sql = new qDbs_SQLcode();
            sqlCode = "INSERT INTO qPtl_UserRoles ([UserID],[RoleID]) VALUES(" + user.UserID + "," + data.default_role_id + ")";
            sql.ExecuteSQL(sqlCode);

            // Add possible role actions for the new user role
            AddRoleAction(data.default_role_id, data.scope_id, user);

            // add folder for user_data
            string rootLocation = HttpContext.Current.Server.MapPath("~/") + "user_data\\";

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

            if (new_user.UserID > 0) return new_user;
            else return null;
        }