using System;
using System.Data;
using System.Text;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using digioz;

public partial class ChatRoom : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {

        Response.AddHeader("Refresh", Convert.ToString((Session.Timeout * 60) - 10));

        if ((Session["username"] != null))
        {
            txtChat.Enabled = true;
            btnMoreSmiles.Attributes.Add("onclick", "OpenSmiles()");

            StringBuilder lsbBuff = new StringBuilder();
            string lsError = String.Empty;
            SmileyList loSmileyList;

            if (Session["smileylisttop38"] == null)
            {
                loSmileyList = SmileyManagement.GetSmileyListTop38(out lsError);
                Session["smileylisttop38"] = loSmileyList;
            }
            else
            {
                loSmileyList = (SmileyList)Session["smileylisttop38"];
            }

            foreach (Smiley loSmiley in loSmileyList)
            {
                lsbBuff.Append("<img src=\"" + loSmiley.Image + "\" onclick=\"SetSmiley('" + loSmiley.Abbr + "')\" alt=\"\" />");
            }
            lblSmileyList.Text = lsbBuff.ToString();
        }
        else
        {
            txtChat.Enabled = false;
            btnChat.Enabled = false;
            Response.Redirect("Login.aspx");
        }
    }

    protected void btnChat_Click(object sender, EventArgs e)
    {
        string lsChatText = string.Empty;
        ChatMessage loChatMessage = new ChatMessage();

        lsChatText = txtChat.Text;
        lsChatText = Utility.ConvertHtmlToPlainText(lsChatText);
        UBBCode loUBBCode = new UBBCode(lsChatText);
        lsChatText = loUBBCode.HTMLCode;
        lsChatText = SubstituteEmoticons(lsChatText);


        if (!(lsChatText == string.Empty))
        {
            loChatMessage.Username = Session["username"].ToString();
            loChatMessage.Message = lsChatText;
            ChatMessageManagement.SaveChatMessages(loChatMessage);

            txtChat.Text = string.Empty;
            txtChat.Focus();
        }
    }

    private string SubstituteEmoticons(string pMessage)
    {
        StringBuilder psbBuff = new StringBuilder(pMessage);
        string lsError = String.Empty;
        SmileyList loSmileyList;

        if (Session["smileylist"] == null)
        {
            loSmileyList = SmileyManagement.GetSmileyList(out lsError);
            Session["smileylist"] = loSmileyList;
        }
        else
        {
            loSmileyList = (SmileyList)Session["smileylist"];
        }

        foreach (Smiley loSmiley in loSmileyList)
        {
            psbBuff = psbBuff.Replace(loSmiley.Abbr, "<img src=\"" + loSmiley.Image + "\" alt=\"\" />");
        }

        return psbBuff.ToString();
    }
}
