protected void btn_play_for_real_Click(object sender, EventArgs e)
    {
        HedgeEmLogEvent my_log_event = new HedgeEmLogEvent();
        my_log_event.p_method_name = "btn_play_for_real_Click";
        log.Info("[" + Session["username"].ToString() + "] cliked on Play for Real button.");
        try
        {
            // This will get the current value of count that how many times user have clicked on the button, from the database.       
            int play_for_real_count = Convert.ToInt32(f_get_object_from_json_call_to_server("f_get_play_for_real_count/" + f_get_player_id().ToString(), null));

            // This will increment the value of count.
            play_for_real _play_for_real = new play_for_real
            {
                p_playerid = f_get_player_id(),
                p_play_for_real_count = play_for_real_count
            };

            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(play_for_real));
            MemoryStream mem = new MemoryStream();
            ser.WriteObject(mem, _play_for_real);
            string data =
                Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
            WebClient webClient = new WebClient();
            webClient.Headers["Content-type"] = "application/json";
            webClient.Encoding = Encoding.UTF8;
            webClient.UploadString("http://devserver.hedgeem.com/Service1.svc/f_set_play_for_real_count", data);
            webClient.UploadString("http://localhost:59225/Service1.svc/f_set_play_for_real_count", data);

            _global_game_state_object = (DC_hedgeem_game_state)f_get_object_from_json_call_to_server("get_game_state_object/" + _table_id, typeof(DC_hedgeem_game_state));
            game_id = _global_game_state_object.p_game_id;
            int my_number_of_hands = _global_game_state_object.p_number_of_hands_int;
            enum_betting_stage my_betting_stage = f_get_current_betting_stage();
            _game_state = _global_game_state_object.p_current_state_enum;
            _hedgeem_hand_panels = new hedgeem_hand_panel[my_number_of_hands];
            _int_number_of_betting_stages = _global_game_state_object.p_number_of_betting_stages_int;
            _hedgeem_betting_panels = new BETTING_PANEL[_int_number_of_betting_stages, my_number_of_hands];
            lbl_game_id.Text = String.Format("Table/Game: {0}/{1} ", _global_game_state_object.p_table_id, game_id);
            // Method which calls the functions to render the screen.
            f_call_functions_to_render_screen();
        }
        catch (Exception ex)
        {
            string my_error_popup = "alert('Error in btn_play_for_real_Click - " + ex.Message.ToString() + "');";
            ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
            HedgeEmLogEvent my_log = new HedgeEmLogEvent();
            my_log.p_message = "Exception caught in btn_play_for_real_Click function " + ex.Message;
            my_log.p_method_name = "btn_play_for_real_Click";
            my_log.p_player_id = f_get_player_id();
            my_log.p_game_id = game_id;
            my_log.p_table_id = _table_id;
            log.Error(my_log.ToString());
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        HedgeEmLogEvent my_log_event = new HedgeEmLogEvent();
        my_log_event.p_method_name = System.Reflection.MethodBase.GetCurrentMethod().ToString();
        my_log_event.p_message = "Method called.";
        log.Debug(my_log_event.ToString());

        p_session_current_table_id = 1000;
        p_session_server_id = 10;

        try
        {

            string strUserAgent = Request.UserAgent.ToString().ToLower();
            bool MobileDevice = Request.Browser.IsMobileDevice;
            if (Request.Cookies["MobileDevice"] != null)
            {
                if (Request.Cookies["MobileDevice"].Value == "IgnoreMobile") { MobileDevice = false; }
            }
            else
            {
                if (strUserAgent != null)
                {
                    //if (MobileDevice == true || strUserAgent.Contains("iphone") || strUserAgent.Contains("blackberry") || strUserAgent.Contains("mobile") ||
                    //strUserAgent.Contains("android") || strUserAgent.Contains("windows ce") || strUserAgent.Contains("opera mini") || strUserAgent.Contains("palm"))
                    if (strUserAgent.Contains("iphone"))
                    {
                        Response.Redirect("https://itunes.apple.com/gb/app/texas-hedgeem/id1018941577?mt=8");
                    }
                }
            }


            //Read more: http://www.thecodingguys.net/blog/asp-net-mobile-detection#ixzz3qoYVKpHs

            if (Request.QueryString["un"] != null && Request.QueryString["p"] != null)
            {
                string retrieved_username = Decryptdata(Request.QueryString["un"].ToString());
                string retrieved_password = Decryptdata(Request.QueryString["p"].ToString());
                string retrieved_displayname = Decryptdata(Request.QueryString["dn"].ToString());
                Session["p_session_username"] = retrieved_username;
                Session["password"] = retrieved_password;
                Session["display_name"] = retrieved_displayname;
                //  service.f_activate_user(retrieved_username);
                //    my_log_event.p_message = String.Format("Username [{0}] activated. ", retrieved_username);
                my_log_event.p_message = String.Format("User [{0}] clicked on link activation. ", retrieved_username);
                ScriptManager.RegisterStartupScript(Page, GetType(), "OnLoad", "alert('Thanks for verifying your account. You can now play the game.'); if(alert){ window.location='frm_facebook_canvas.aspx';}", true);
                log.Debug(my_log_event.ToString());

            }
            if (Page.IsPostBack == false)
            {
                if (Request.QueryString["signout"] != "true")
                {
                    Page.RegisterStartupScript("OnLoad", "<script>document.getElementById('element').style.display='block';</script>");
                    Page.RegisterStartupScript("OnLoad2", "<script> $('#element').introLoader({animation: { name: 'counterLoader', options: { exitFx: 'slideRight',ease: 'easeOutSine',style: 'fluoYellow', delayBefore: 1000, exitTime: 500, animationTime: 1000} } });</script>");

                    //#region load_all_images_at_once
                    ////Get Path of Images
                    //var path = Server.MapPath("~/resources/cards/");
                    //string[] images = Directory.GetFiles(path, "*.png");
                    //List<string> get_list_of_images = new List<string>();
                    //foreach (string image in images)
                    //{
                    //    string name = Path.GetFileName(image);
                    //    // Add image names in list
                    //    get_list_of_images.Add("'resources/cards/" + name + "'");
                    //}
                    //// convert list to array
                    //string[] array_of_images = get_list_of_images.ToArray();
                    //// convert array to string along with joining with ','
                    //string images_ = ConvertStringArrayToStringJoin(array_of_images);

                    //// script to call the Progress Bar while images are loading
                    //Page.RegisterStartupScript("Loading", "<script type='text/javascript'> var myImages = [" + images_ + "]; progressBar(myImages.length); </script>");

                    //// script to load all images
                    //Page.RegisterStartupScript("Prefetch Images", "<script type='text/javascript'> var myImages = [" + images_ + "]; for (var i = 0; i <= myImages.length; i++) { var img = new Image();  img.src = myImages[i];}</script>");
                    //#endregion load_all_images_at_once

                }
            }
            else
            {
                //Page.RegisterStartupScript("OnLoad", "<script>document.getElementById('progressbar').style.display='none';</script>");
            }

            if (Request.QueryString["r"] != null)
            {
                my_log_event.p_message = String.Format("Session Timedout message shown to user.");
                log.Debug(my_log_event.ToString());
                Page.RegisterStartupScript("Alert Message", "<script type='text/javascript'>show_session_timeout_message();</script>");


            }
            else
            {
                
                if (Request.QueryString["action"] != null)
                {
                    Response.Clear();
                    Session.Abandon();
                    Response.Redirect("frm_facebook_canvas.aspx");
                }
                
                if (Session["p_session_username"] != null)
                {

                    //Page.RegisterStartupScript("OnLoading", "<script>load_edit_profile();</script>");
                    if (Session["display_name"] != null)
                    {
                    }
                    
                    
                    HedgeEmPlayer my_player = get_player_details(Session["p_session_username"].ToString());

                   
                    string role = "";
                    if (my_player != null)
                    {
                        role = my_player.p_role;

                        //my_log_event.p_message = String.Format("User/player role hardcoded to BASIC_USER");
                        //log.Debug(my_log_event.ToString());
                        my_log_event.p_message = String.Format("User/player role determined to be [{0}].", role.ToString());
                        log.Debug(my_log_event.ToString());
                    }

                    
                    Session["user_role"] = role;
                    //// - xxx- Hardcoding value of role to BASIC_USER as need to discuss this with Simon.
                    //Session["user_role"] = "BASIC_USER";
                    Page.RegisterStartupScript("OnLoad", "<script>document.getElementById('progressbar').style.display='none';</script>");
                }
            }
        }
        catch (Exception ex)
        {
            HedgeemerrorPopup my_popup_message = new HedgeemerrorPopup();
            my_popup_message.p_detailed_message_str = "";
            my_popup_message.p_is_visible = false;
            string my_error_popup = "Error in Page Load of frm_facebook_canvas - " + ex.Message.ToString();
            //ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
            my_popup_message.p_detailed_message_str = my_error_popup.ToString();
            my_popup_message.p_is_visible = true;
            Place_Holder_Popup_Message.Controls.Add(my_popup_message);
            my_log_event.p_message = "Exception caught in Page Load of frm_facebook_canvas- " + ex.Message;
            log.Error(my_log_event.ToString(), new Exception(ex.Message));
        }
    }
    protected void f_play_anon(enum_theme a_enum_theme)
    {

        // Log that the user has clicked the 'Play now' button.
        HedgeEmLogEvent my_log_event = new HedgeEmLogEvent();
        my_log_event.p_method_name = System.Reflection.MethodBase.GetCurrentMethod().ToString();
        my_log_event.p_table_id = p_session_personal_table_id;
        my_log_event.p_server_id = p_session_server_id;
        my_log_event.p_message = String.Format("User [{0}] click 'Play Now", p_session_username);
        log.Info(my_log_event.ToString());

        // This fucntion should not be able to be played if the player as not logged in, so test if they have 
        // a 'HedgeEm Session' has been established,  If not exit this fucntion. 
        /*if (!p_valid_session_exists)
        {
            my_log_event.p_message = String.Format("User informed the session is invalide.");
            log.Debug(my_log_event.ToString());

            //ScriptManager.RegisterStartupScript(Page, GetType(), "Alert Message", "alert('You must be logged in to Play this game.');", true);
            ScriptManager.RegisterStartupScript(Page, GetType(), "Alert Message", "document.getElementById('alertmessage').style.display = 'block';", true);
            return;
        }*/


        // xxx Consider uncommenting the following after aslo considering consequence (if you do this when user clicks leave table 
        // they will leave there personal table which you may not want currently as the code currently (Dec 2014) assumes you are sitting at
        // personal table all the time.
        HedgeEmPlayer my_hedgeem_player;
        //my_hedgeem_player = f_get_free_anonymous_player();
        DC_hedgeem_game_state my_game_state = f_sit_at_anonymous_table(a_enum_theme);
        //f_login_anonymously(1201);
        if (my_game_state.p_error_message != null)
        {
            if (my_game_state.p_error_message != "")
            {
                throw new Exception(my_game_state.p_error_message);
            }
        }


        Session["p_session_username"] = my_game_state._seats[0].p_player_name;
        Session["p_session_personal_table_id"] = my_game_state.p_table_id;
        Session["p_session_current_table_id"] = my_game_state.p_table_id;
        Session["p_session_player_id"] = my_game_state._seats[0].p_player_id;
        Session["theme"] = a_enum_theme.ToString();
        Session["role"] = "BASIC_USER";

            f_goto_table(my_game_state.p_table_id);

        // If code reaches here we asssume Table ID and PlayerID is known so sit the person at this table


    }
    private DC_hedgeem_game_state f_sit_at_anonymous_table(enum_theme a_enum_theme )
    {
        HedgeEmLogEvent my_log_event = new HedgeEmLogEvent();
        DC_hedgeem_game_state my_game_state = new DC_hedgeem_game_state();
        my_log_event.p_method_name = System.Reflection.MethodBase.GetCurrentMethod().ToString();
        my_log_event.p_message = "f_sit_at_anonymous_table";
        log.Debug(_xxx_log_event.ToString());
        string my_endpoint = "Not Set";
        try
        {
            try
            {
    
                // Creates (registers) a new user (HedgeEmPlayer) in the HedgeEm Server.
                // Note this also creates a Personal Table for them (which the HedgeEmTable is returned in the Player object 'p_personal_table_id
                enum_authentication_method my_authentication_method = enum_authentication_method.FACEBOOK;
            my_endpoint = String.Format("{0}/ws_sit_at_anonymous_table/{1},{2},{3},{4}/",
                                                p_current_json_webservice_url_base,
                                                "anon_session_id_123",
                                                83,
                                                a_enum_theme.ToString(),
                                                "FASTPLAY_FLOP");

            my_game_state = (DC_hedgeem_game_state)f_get_object_from_json_call_to_server(my_endpoint, typeof(DC_hedgeem_game_state));
                if (my_game_state.p_error_message != null)
                {
                    if (my_game_state.p_error_message != "")
                    {
                        string my_error_msg = string.Format("Failed trying call 'sit anonymously' to server, Error returned [{0}], Endpoint targeted [{1}]",my_game_state.p_error_message,my_endpoint);
                        throw new Exception(my_error_msg);
                    }
                }

                // If we got here we assume Player was created successfully so store Player ID and continue
                //p_session_player_id = my_game_state.p_player_id;


                // login to the game
                /*Session["p_session_username"] = txt_username.Text;
                Session["password"] = txt_password.Text;
                Session["display_name"] = txt_full_name.Text;
                Session["p_session_personal_table_id"] = my_game_state.p_personal_table_id;
                Session["p_session_username"] = my_game_state.p_username;
                Session["p_session_password"] = txt_password.Text;
                Session["p_session_display_name"] = my_game_state.p_display_name;


                ScriptManager.RegisterStartupScript(Page, GetType(), "OnLoad", "alert('Thank you for registering,your facebook account with HedgeEm. A confirmation mail is sent to your email Id '); if(alert){ window.location='frm_facebook_canvas.aspx';}", true);
                */
                //Page.RegisterStartupScript("OnLoad", "<script>alert('Thank you for registering, you are now logged in an can start to play HedgeEm'); if(alert){ window.location='frm_facebook_canvas.aspx';}</script>");
            }
            catch (Exception ex)
            {
                string my_error_msg_summary = String.Format("Fatal error trying to sit at table anonymously");
                string my_error_msg_detail = String.Format("Error in {0} Reason [{1}]", 
                    my_log_event.p_method_name, 
                    ex.Message.ToString());

                my_log_event.p_message = my_error_msg_detail;

                log.Error(my_log_event.ToString());

                HedgeemerrorPopup my_popup_messageError = new HedgeemerrorPopup();
                my_popup_messageError.p_user_message_str = my_error_msg_summary;
                my_popup_messageError.p_detailed_message_str = my_error_msg_detail;
                my_popup_messageError.p_is_visible = true;

                Place_Holder_Popup_Message.Controls.Add(my_popup_messageError);

                my_popup_messageError.Dispose();

                //newuser.Visible = false;



            }
        }
        catch (Exception ex)
        {
            string my_error_popup = "Error in f_get_free_anonymous_player suald - " + ex.Message.ToString();
       //     ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
            log.Error("Error in f_get_free_anonymous_player xxxaawe", new Exception(ex.Message));

            HedgeemerrorPopup my_popup_message = new HedgeemerrorPopup();
            my_popup_message.p_detailed_message_str = "";
            my_popup_message.p_detailed_message_str = my_error_popup;
            my_popup_message.p_is_visible = true;

            //newuser.Visible = false;

            Place_Holder_Popup_Message.Controls.Add(my_popup_message);

            my_popup_message.Dispose();

        }

        return my_game_state;
        
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="endpoint">Full path to JSON endpoint including base URL.  Example: http://devserver.hedgeem.com/Service1.svc/get_server_info/10/</param>
    /// <param name="typeIn"></param>
    /// <returns></returns>
    public static object f_get_object_from_json_call_to_server(string endpoint, Type typeIn)
    {
        HedgeEmLogEvent my_log_event = new HedgeEmLogEvent();
        my_log_event.p_message = String.Format("Method called with endpoint [{0}]", endpoint); ;
        my_log_event.p_method_name = System.Reflection.MethodBase.GetCurrentMethod().ToString();
        object obj = null;

        //my_log.p_player_id = playerid;
        try
        {
            log.Debug(my_log_event.ToString());
            HttpWebRequest request;
            String my_service_url = "not set";


            //my_service_url = WebConfigurationManager.AppSettings["hedgeem_server_default_webservice_url"];
            my_log_event.p_message = String.Format("Webservice configured for GoDaddy Deployment URI = [{0}]", endpoint); ;



            log.Debug(my_log_event.ToString());
            //request = WebRequest.Create(my_service_url + endpoint) as HttpWebRequest;
            request = WebRequest.Create(endpoint) as HttpWebRequest;


            // Get response
            if (request != null)
                using (var response = request.GetResponse() as HttpWebResponse)
                {
                    if (response != null)
                    {
                        Stream stream = response.GetResponseStream();

                        if (stream != null)
                        {

                            var reader = new StreamReader(stream);
                            try
                            {
                                string json = reader.ReadToEnd();
                                // Check if stream is empty, if it is throw and exception
                                if (json.Length == 0)
                                {
                                    String my_error_msg = String.Format("JSON string has been returned empty for URI endpoint [{0}]", request.Address);
                                    my_log_event.p_message = my_error_msg;
                                    log.Error(my_log_event.ToString());
                                    throw new Exception(my_error_msg);
                                }
                                var ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
                                if (typeIn != null)
                                {
                                    var ser = new DataContractJsonSerializer(typeIn);
                                    obj = ser.ReadObject(ms);
                                }
                                else
                                {
                                    obj = json;
                                }
                            }

                            finally
                            {
                                reader.Close();
                            }
                        }
                    }
                }
            return obj;
        }
        catch (System.Net.WebException webex)
        {
            HttpWebResponse my_error_response = webex.Response as HttpWebResponse;
            switch (my_error_response.StatusCode)
            {
                case HttpStatusCode.BadRequest:
                    my_log_event.p_message = String.Format(
                       "Error (Web Exception: BadRequest). Endpoint URI probably badly formed ...\nEndpoint [{0}], Status Code [{1}]",
                              endpoint,
                               my_error_response.StatusCode
                              );
                    break;

                case HttpStatusCode.NotFound:
                    my_log_event.p_message = String.Format(
                       "Error (Web Exception: NotFound). Endpoint URI not found; Endpoint [{0}], Status Code [{1}]",
                              endpoint,
                               my_error_response.StatusCode
                              );
                    break;

                default: my_log_event.p_message = String.Format(
                       "Error unexpected status code (Web Exception of type Status Code [{0}] for Endpoint [{1}], ",
                              my_error_response.StatusCode,
                              endpoint
                              );
                    break;
            }



            return new WebException(my_log_event.ToString(), webex);
        }
        catch (Exception ex)
        {
            // Log the error and raise a new exception
            if (ex.InnerException != null)
            {
                my_log_event.p_message = String.Format(
                    "Error. Details [{0}], Inner Exception [{1}]",
                            ex.Message, ex.InnerException.Message
                           );
            }
            else
            {
                my_log_event.p_message = String.Format(
               "Error. Details [{0}]", ex.Message);

            }
            log.Error(my_log_event.ToString());
            //throw new Exception(my_log_event.ToString());
            return new Exception(my_log_event.ToString());
        }
        
    }
    protected void btn_play_shared_table_Click(object sender, EventArgs e)
    {

        try
        {
            // Log that the user has clicked the 'Play now' button.
            HedgeEmLogEvent my_log_event = new HedgeEmLogEvent();
            my_log_event.p_method_name = System.Reflection.MethodBase.GetCurrentMethod().ToString();
            my_log_event.p_message = String.Format("User [{0}] click 'Play Shared Table", Session["p_session_username"]);
            log.Info(my_log_event.ToString());

            Session["p_session_player_id"] = xxxHC_ANON_PLAYER_ID;
            Session["theme"] = "CASINO_TABLE";
            Session["Facebook_User_Id"] = "not_set";
            Session["user_role"] = "BASIC_USER";
            Session["p_session_username"] = xxxHC_ANON_USERNAME;
            Session["p_session_personal_table_id"] = 1000;
            f_goto_table(1000);
        }
        catch (Exception ex)
        {
            string my_error_popup = "alert('Error in method [btn_play_shared_table_Click] - " + ex.Message.ToString() + "');";

            HedgeemerrorPopup my_popup_message = new HedgeemerrorPopup();
            my_popup_message.p_detailed_message_str = "";
            my_popup_message.p_detailed_message_str = my_error_popup;
            my_popup_message.p_is_visible = true;

            //newuser.Visible = false;

            Place_Holder_Popup_Message.Controls.Add(my_popup_message);

            my_popup_message.Dispose();

            log.Error("Error in btn_play_shared_table_Click", new Exception(ex.Message));
      //      throw new Exception(String.Format("fish cakes:", ex.Message));
        }


    }
    protected void btn_login_Click(object sender, EventArgs e)
    {

       
       

        HedgeEmLogEvent my_log_event = new HedgeEmLogEvent();
        my_log_event.p_method_name = System.Reflection.MethodBase.GetCurrentMethod().ToString();
        // Log the fact this method has been called
        my_log_event.p_message = String.Format("Method [btn_login_Click] called ");
        log.Debug(my_log_event.ToString());
        string my_endpoint = "Not Set";
        // Detemine if there is a session varible set for facebook. 
        // xxx Nov 2014 Note ... Not sure why - I assmume this is to check
        // if the user has already authenticated via facebook so we can make choices about what to display
        if (Session["chkfb"] != null)
        {
            //   chk_fb_visibility.Visible = true;
            log.Debug(String.Format("Session variable 'chkfb' is {0}", Session["chkfb"].ToString()));
        }
        else
        {
            //  chk_fb_visibility.Visible = false;
            //  chk_fb_visibility.Visible = false;
        }

        // Declare vairibles that will be required later
        string my_username = "";
        string my_password = "";
        DataTable my_user_details;

        // If the user has entered a email/userid into the text box use this to set 'my_username' varible (for later use)
        if (txt_get_fm_email_id.Text != "")
        {
            my_username = txt_get_fm_email_id.Text;
            my_password = Session["password"].ToString();
            Session["facebooklogin"] = "******";
        }
        else
        {
            my_username = txtUsername.Text;
            my_password = txtPassword.Text;
        }
        try
        {
            // Attempt to retrieve a Player object from the HedgeEm Webservice using the credentials supplied.
            my_endpoint = String.Format("{0}/ws_login/{1},{2},{3},{4}/", p_current_json_webservice_url_base, p_session_id, p_session_server_id, my_username, my_password);
            HedgeEmPlayer my_player = (HedgeEmPlayer)f_get_object_from_json_call_to_server(my_endpoint, typeof(HedgeEmPlayer));

            if (my_player == null)
            {
                string my_error_msg = String.Format("Player object is null after call to Webservice to retrieve details", my_username);
                my_log_event.p_message = my_error_msg;
                log.Error(my_log_event.ToString());
                throw new Exception(my_error_msg);
            }

            if (my_player.p_player_id <= 0)
            {
                my_log_event.p_message = my_player.p_error_message;
                log.Error(my_log_event.ToString());
                throw new Exception(my_log_event.ToString());

            }
            else
            {
                // If we have got here the user has logged into the server sucessfully so we should set some session variables for ease of use later
                int my_player_id = my_player.p_player_id;
                Session["p_session_player_id"] = my_player_id;
                Session["display_name"] = my_player.p_display_name;
                Session["p_session_username"] = my_username;
                Session["password"] = my_password;
                p_session_personal_table_id = my_player.p_personal_table_id;
                if (Session["p_session_username"] != null)
                {
                    if (File.Exists(Server.MapPath("resources/player_avatar_" + Session["p_session_username"].ToString() + ".jpg")))
                    {
                        usr_image.ImageUrl = "../resources/player_avatar_" + Session["p_session_username"].ToString() + ".jpg";
                    }

                    else
                    {
                        usr_image.ImageUrl = "../resources/avitars/user_square.png";
                    }
                }
                // As the user has now logged in by HedgeEm authentication hide the Facebook login DIV
                if (Session["facebooklogin"] != null)
                {
                    //LoginDiv.Attributes.Add("style", "display:none !Important;");
                }

                // As the user has now logged show the logout button and hide the login button
                // xxx Nov 2014.  Not sure why this is on condition of facebooklogin; I separated this out from if/else
                // of above to figure this out.  I assume is because you could be logged in by facebook so still want to
                // show / hide login/logout buttons appropriately
                if (Session["facebooklogin"] == null)
                {
                    lbl_user_name.Text = Session["display_name"].ToString();
                    Logout.Attributes.Add("style", "display:block !Important;");
                    //LoginDiv.Attributes.Add("style", "display:none !Important;");
                    divLogin.Attributes.Add("style", "display:none !Important;");
                    userdetails.Attributes.Add("style", "display:none !Important;");
                    btnLogout.Visible = true;
                    btnLogout.Enabled = true;
                    Page.RegisterStartupScript("OnLoad", "<script>document.getElementById('userdetails').style.display='none';</script>");
                }

                // As the user has now logged in Enable the 'Play Now' button
                btn_play_now.Enabled = true;

               // usr_image.ImageUrl = my_player.p_user_avitar_image_url;

                // If the 'fb_hide_logout' is set it implies xxxxxxxxxxxxxxxxxxxxx so enable the 'Play Now' button
                if (Session["fb_hide_logout"] != null)
                {
                    //    chk_fb_visibility_logout.Visible = false;
                    btn_play_now.Visible = true;

                }

                // If the 'chk_logout_hide' is set it implies xxxxxxxxxxxxxxxxxxxxx so enable the 'Play Now' button
                if (Session["chk_logout_hide"] != null)
                {

                    //   chk_fb_visibility.Visible = true;
                    btn_play_now.Visible = true;
                    btnLogout.Visible = false;
                }
                Page.RegisterStartupScript("OnLoading", "<script>load_edit_profile();</script>");
                // Response.Redirect("frm_facebook_canvas.aspx");
                Page.RegisterStartupScript("OnLoad", "<script>document.getElementById('progressbar').style.display='none';</script>");

                string role = "";
                if (my_player != null)
                {
                    role = my_player.p_role;
                    my_log_event.p_message = String.Format("User/player role determined to be [{0}].", role.ToString());
                    log.Debug(my_log_event.ToString());
                }

                if (role == enum_user_role.ADMIN.ToString())
                {
                    btnAdmin.Attributes.Add("style", "display:block");
                }
                else
                {
                    btnAdmin.Attributes.Add("style", "display:none");
                }
            }
        }
        catch (Exception ex)
        {
            string my_error_message = "Fatal Errorin method [btn_login_Click] - " + ex.Message.ToString() + "');";

            //  Log the error and raise a new exception
            my_log_event.p_message = String.Format(
                "Fatal error in method [btn_login_Click]. Reason [{0}]",
                        ex.Message);
            log.Error(my_log_event.ToString(), new Exception(ex.Message));
            HedgeemerrorPopup my_popup_message = new HedgeemerrorPopup();
            my_popup_message.p_detailed_message_str = "";
            my_popup_message.p_is_visible = false;
        
            //ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
            my_popup_message.p_detailed_message_str = my_error_message.ToString();
            my_popup_message.p_is_visible = true;
            Place_Holder_Popup_Message.Controls.Add(my_popup_message);
        }
       
    }
 public static string get_clicked_name(string name)
 {
     try
     {
         Page objp = new Page();
         // sets value of clicked link to session
         objp.Session["name"] = name;
     }
     catch (Exception ex)
     {
         HedgeEmLogEvent my_log = new HedgeEmLogEvent();
         my_log.p_message = "Exception caught in get_clicked_name function " + ex.Message;
         my_log.p_method_name = "get_clicked_name";
         log.Error(my_log.ToString());
     }
     return name;
 }
 // This function plays sound on the click of deal button
 private void PlaySound()
 {
     log.Debug("PlaySound method of Hedgeem Table is called");
     try
     {
         SoundPlayer sd = new SoundPlayer();
         sd.SoundLocation = Server.MapPath("~/resources/waves/Deal-4.wav");
         sd.Play();
         sd.Play();
         sd.Play();
         sd.Play();
         sd.Play();
     }
     catch (Exception ex)
     {
         string my_error_popup = "alert('Error in PlaySound method - " + ex.Message.ToString() + "');";
         ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
         HedgeEmLogEvent my_log = new HedgeEmLogEvent();
         my_log.p_message = ex.Message;
         my_log.p_method_name = "PlaySound";
         my_log.p_player_id = f_get_player_id();
         my_log.p_game_id = game_id;
         my_log.p_table_id = _table_id;
         log.Error(my_log.ToString());
     }
 }
    /// <summary>
    /// This is the primary co-ordinating function initiates the transistion of a Hedge'Em game from one
    /// state to the next.  This function is called when a player/user clicks on and of the 'Deal' buttons
    /// (e.g. 'Deal Hole', 'Deal Flop', 'Deal Next' etc).  
    /// 
    /// If you imagine the in the real physical world it would be like the player at a black-jack table
    /// telling the dealer to deal the next card. 
    /// 
    /// Upon calling of this function two things happen:
    /// 
    ///    1. An instruction is sent to the server to tell it to progress the game to the next stage.  (e.g. 
    ///       (if the game is currently in 'HOLE' state, then progress to 'FLOP' state.
    ///       
    ///    2. An internal call to is made to tell the webpage to update its display based on the change in state
    ///       as read from the server post change to new state.  Eg. If the Hedge'Em game now enters the 'TURN'
    ///       stage then show/enable the 'Deal River' button and update the Odd that each hand has of winning. 
    ///       
    /// xxx ... Note: in most games (and how this is currently (Dec 2013) coded there will only be 
    /// one player per table so the game will change to the next state each time this function is called.
    /// In future the game will not progress to the next state until all players at the same table have 
    /// issued the same instruction or the dealer/server decided to do on a time-delay basis after each stage.
    /// </summary>
    /// <returns></returns>
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// 

    public void btn_deal_next_stage_Click()
    {


        //   ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", "alert('called');", true);
        HedgeEmLogEvent my_log_event = new HedgeEmLogEvent();
        my_log_event.p_method_name = "frm_home_page.btn_deal_next_stage_Click";
        my_log_event.p_method_name = "btn_deal_next_stage_Click";
        if (Session["username"] == null)
        {
            my_log_event.p_message = "Hardcoded username to Simon";
            log.Warn(my_log_event.ToString());
            Session["username"] = "******";
        }
        string my_username = Session["username"].ToString();

        log.Info("[" + my_username + "] clicked Deal Next Stage button");
        try
        {
            if (Session.Count == 0)
            {
                log.Info("Session timed out for user with player id = " + f_get_player_id());
                ScriptManager.RegisterStartupScript(Page, GetType(), "SessionTimeOutMsg", "show_session_timeout_message();", true);
            }
            else
            {
                int xxxHC_my_player_ID = 10000;
                // call to webservice to get next state object
                _global_game_state_object = (DC_hedgeem_game_state)f_get_object_from_json_call_to_server("get_next_game_state_object/" + _table_id + "," + f_get_player_id(), typeof(DC_hedgeem_game_state));
                game_id = _global_game_state_object.p_game_id;
                int my_number_of_hands = _global_game_state_object.p_number_of_hands_int;
                enum_betting_stage my_betting_stage = f_get_current_betting_stage();
                Session["sess_betting_stage_enum"] = _global_game_state_object.p_current_betting_stage_enum;
                _game_state = _global_game_state_object.p_current_state_enum;
                _hedgeem_hand_panels = new hedgeem_hand_panel[my_number_of_hands];
                _int_number_of_betting_stages = _global_game_state_object.p_number_of_betting_stages_int;
                _hedgeem_betting_panels = new BETTING_PANEL[_int_number_of_betting_stages, my_number_of_hands];
                player_funds_at_seat = _global_game_state_object._seats[0].p_player_seat_balance;
                // call to the method to render the screen
                f_call_functions_to_render_screen();
            }
            ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", "alert ('hi');", true);
        }
        catch (Exception ex)
        {
            string my_error_popup = "alert('Error in btn_deal_next_stage_Click - " + ex.Message.ToString() + "');";
            ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", "alert ('" + ex.Message.ToString() + "')", true);
            HedgeEmLogEvent my_log = new HedgeEmLogEvent();
            my_log.p_message = String.Format("Exception caught in btn_deal_next_stage_Click function. Reason [{0}] ", ex.Message);
            my_log.p_method_name = "btn_deal_next_stage_Click";
            my_log.p_player_id = f_get_player_id();
            my_log.p_game_id = game_id;
            my_log.p_table_id = _table_id;
            log.Error(my_log.ToString());
            //throw new Exception("xxx This exception is not being caught");
        }
        //Response.Write("<META HTTP-EQUIV=Refresh CONTENT='30; URL='>");
    }
    // This method add 25 chips amount to user's seat balance if a user clicks on get chips button
    protected void btn_get_chips_add_Click(object sender, EventArgs e)
    {
        HedgeEmLogEvent my_log = new HedgeEmLogEvent();

        try
        {
            my_log.p_message = "Method called ";
            my_log.p_method_name = "btn_get_chips_add_Click";
            my_log.p_player_id = f_get_player_id();
            my_log.p_game_id = game_id;
            my_log.p_table_id = _table_id;
            log.Debug(my_log.ToString());
            log.Info("[" + Session["username"].ToString() + "] clicked btn_get_chips");
            int xxx_HC_seat_id = 0;
            double my_get_chips_top_up_amount = Convert.ToDouble(WebConfigurationManager.AppSettings["get_chips_default_amount"]);


            seat_balance_update my_seat_balance_update = new seat_balance_update
            {
                p_playerid = f_get_player_id(),
                p_tableid = _table_id,
                p_seatid = xxx_HC_seat_id,
                p_balance = my_get_chips_top_up_amount
            };


            int my_server_id = 10;
            // Call the Hedge'Em Webservices (via helper function) to place the bet.
            string get_chips_endpoint = String.Format("ws_top_up_chips_at_table/{0},{1},{2},{3},{4}",
                                                        my_server_id,
                                                        _table_id,
                                                        xxx_HC_seat_id,
                                                        my_get_chips_top_up_amount,
                                                        f_get_player_id());
            my_seat_balance_update = (seat_balance_update)f_get_object_from_json_call_to_server(get_chips_endpoint, typeof(seat_balance_update));


            // gets clicked link value from session
            string clicked_name = Session["name"].ToString();

            //logs the entry of clicked link
            log.Info("[" + Session["username"].ToString() + "] Selected [" + clicked_name + "] option to get chips.");
            /*_global_game_state_object = (DC_hedgeem_game_state)f_get_object_from_json_call_to_server("get_game_state_object/" + _table_id, typeof(DC_hedgeem_game_state));
            game_id = _global_game_state_object.p_game_id;
            int my_number_of_hands =_global_game_state_object.p_number_of_hands_int;
            
            enum_betting_stage my_betting_stage = f_get_current_betting_stage();
            _game_state = _global_game_state_object.p_current_state_enum;
            _hedgeem_hand_panels = new hedgeem_hand_panel[my_number_of_hands];
            _int_number_of_betting_stages = _global_game_state_object.p_number_of_betting_stages_int;
            _hedgeem_betting_panels = new BETTING_PANEL[_int_number_of_betting_stages, my_number_of_hands];
            lbl_game_id.Text = String.Format("Table/Game: {0}/{1} ", _global_game_state_object.p_table_id, game_id);
            */
            //f_call_functions_to_render_screen();
            ScriptManager.RegisterStartupScript(Page, GetType(), "", "alert('Congratulations £25 have been added to your seat amount........!');", true);
        }
        catch (Exception ex)
        {
            // xxxeh this exeception does not show to users
            string my_error_popup = "alert('Error in btn_get_chips_add_Click - " + ex.Message.ToString() + "');";
            ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
            my_log.p_message = String.Format("Exception caught in btn_get_chips_add_Click function. Reason [{0}] ", ex.Message);
            my_log.p_method_name = "btn_get_chips_add_Click";
            my_log.p_player_id = f_get_player_id();
            my_log.p_game_id = game_id;
            my_log.p_table_id = _table_id;
            log.Error(my_log.ToString());
        }
    }
    /// <summary>
    /// Get the current betting stage for the table.  Assume we already have this and it is 'cached' in session.
    /// If not get it from HedgeEmServer
    /// </summary>
    /// <returns></returns>
    enum_betting_stage f_get_current_betting_stage()
    {
        HedgeEmLogEvent my_log = new HedgeEmLogEvent();
        enum_betting_stage my_enum_betting_stage = enum_betting_stage.NON_BETTING_STAGE;

        // Test if the current betting stage is stored in session, if it is use this, if not try to retrieve from server.
        if (Session["sess_betting_stage_enum"] != null)
        {
            try
            {
                my_enum_betting_stage = (enum_betting_stage)Session["sess_betting_stage_enum"];
            }
            catch (Exception e)
            {
                throw new Exception("Fatal error trying to get current betting stage from session" + e.Message);
            }
        }
        else
        {
            try
            {
                _global_game_state_object = (DC_hedgeem_game_state)f_get_object_from_json_call_to_server("get_game_state_object/" + _table_id, typeof(DC_hedgeem_game_state));
                my_log.p_message = String.Format("Successfully retrieved gamestate from server. Table ID [{0}], State [{1}]", _global_game_state_object.p_table_id, _global_game_state_object.p_current_state_enum.ToString());
                log.Debug(my_log.ToString());
                my_enum_betting_stage = _global_game_state_object.p_current_betting_stage_enum;
            }
            catch (Exception ex)
            {
                my_log.p_message = String.Format("Error trying to get game state from server. Reason [{0}]", ex.Message);
                log.Error(my_log.ToString());
                return enum_betting_stage.NON_BETTING_STAGE;
            }

        }

        return my_enum_betting_stage;

    }
    // This cancels the bet placed by the user.
    public void btn_cancel_bets_for_this_hand_and_stage_Click(object sender, EventArgs e)
    {
        log.Info("[" + Session["username"].ToString() + "] cancelled the bet");
        try
        {
            // Get the hand_index from the hidden control
            int handindexbet = Convert.ToInt32(btn_hidden_control_temp_store_for_hand_index.Value);
            int xxx_HC_seat_index = 0;
            // Call webservice svc function to cancel the bet placed
            f_get_object_from_json_call_to_server("f_cancel_bets_for_this_hand_and_stage/" + _table_id.ToString() + "," + f_get_player_id().ToString() + "," + xxx_HC_seat_index.ToString() + "," + handindexbet.ToString(), null);

            _global_game_state_object = (DC_hedgeem_game_state)f_get_object_from_json_call_to_server("get_game_state_object/" + _table_id, typeof(DC_hedgeem_game_state));
            game_id = _global_game_state_object.p_game_id;
            int my_number_of_hands = _global_game_state_object.p_number_of_hands_int;
            enum_betting_stage my_betting_stage = f_get_current_betting_stage();
            _game_state = _global_game_state_object.p_current_state_enum;
            _hedgeem_hand_panels = new hedgeem_hand_panel[my_number_of_hands];
            _int_number_of_betting_stages = _global_game_state_object.p_number_of_betting_stages_int;
            _hedgeem_betting_panels = new BETTING_PANEL[_int_number_of_betting_stages, my_number_of_hands];
            lbl_game_id.Text = String.Format("Table/Game: {0}/{1} ", _global_game_state_object.p_table_id, game_id);
            // Method to render the screen
            f_call_functions_to_render_screen();
        }
        catch (Exception ex)
        {
            string my_error_popup = "alert('Error in f_cancel_bets_for_this_hand_and_stage" + ex.Message.ToString() + "');";
            ScriptManager.RegisterStartupScript(Page, GetType(), "OnLoad", "alert('" + ex.Message.ToString() + "');", true);
            ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
            HedgeEmLogEvent my_log = new HedgeEmLogEvent();
            my_log.p_message = "Exception caught in f_cancel_bets_for_this_hand_and_stage function " + ex.Message;
            my_log.p_method_name = "f_cancel_bets_for_this_hand_and_stage";
            my_log.p_player_id = f_get_player_id();
            my_log.p_game_id = game_id;
            my_log.p_table_id = _table_id;
            log.Error(my_log.ToString());
        }
    }
    //xxx commenting out the bet slider code and reverting back the old single bet place. NOw this function is not in use
    protected void btn_Bet_Click(object sender, EventArgs e)
    {
        HedgeEmBetAcknowledgement my_bet_ack = new HedgeEmBetAcknowledgement();
        log.Info("[" + Session["username"].ToString() + "] placed a bet");
        /* Get value of Selected_Hand_Panel for bet from textbox and save it in a variable */
        // xxx need to document this
        try
        {
            //  Get the hand_index from the hidden control
            int handindexbet = Convert.ToInt32(btn_hidden_control_temp_store_for_hand_index.Value);
            double bet_amount;
            if (handindexbet == 0)
            {
                bet_amount = double.Parse(amount1.Value);
            }
            else if (handindexbet == 1)
            {
                bet_amount = double.Parse(amount2.Value);
            }
            else if (handindexbet == 2)
            {
                bet_amount = double.Parse(amount3.Value);
            }
            else
            {
                bet_amount = double.Parse(amount4.Value);
            }

            double rounded_bet_amount = Math.Round(bet_amount, 2, MidpointRounding.AwayFromZero);
            DC_bet_acknowledgement enum_my_bet_ack;

            enum_betting_stage my_betting_stage = f_get_current_betting_stage();
            enum_my_bet_ack = f_place_bet(my_betting_stage,
               handindexbet, rounded_bet_amount);

            if (enum_my_bet_ack.p_ack_or_nak != enum_acknowledgement_type.ACK.ToString())
            {
                string short_desc = "Bet not accepted because.  Reason: ";
                string long_desc = my_bet_ack.p_ack_description;
                //To show error description that why bet is not accepted inside div
                short_description.InnerHtml = short_desc;
                long_description.InnerHtml = long_desc;
                ScriptManager.RegisterStartupScript(Page, GetType(), "JsStatus", "document.getElementById('error_message').style.display = 'block';document.getElementById('fade').style.display = 'block';", true);
            }
            f_place_bet();
            _global_game_state_object = (DC_hedgeem_game_state)f_get_object_from_json_call_to_server("get_game_state_object/" + _table_id, typeof(DC_hedgeem_game_state));
            game_id = _global_game_state_object.p_game_id;
            int my_number_of_hands = _global_game_state_object.p_number_of_hands_int;
            _game_state = _global_game_state_object.p_current_state_enum;
            _hedgeem_hand_panels = new hedgeem_hand_panel[my_number_of_hands];
            _int_number_of_betting_stages = _global_game_state_object.p_number_of_betting_stages_int;
            _hedgeem_betting_panels = new BETTING_PANEL[_int_number_of_betting_stages, my_number_of_hands];
            lbl_game_id.Text = String.Format("Table/Game: {0}/{1} ", _global_game_state_object.p_table_id, game_id);
            f_call_functions_to_render_screen();
        }
        catch (Exception ex)
        {
            string my_error_popup = "alert('Error in btn_Bet_Click" + ex.Message.ToString() + "');";
            ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
            HedgeEmLogEvent my_log = new HedgeEmLogEvent();
            my_log.p_message = "Exception caught in btn_Bet_Click function " + ex.Message;
            my_log.p_method_name = "btn_Bet_Click";
            my_log.p_player_id = f_get_player_id();
            my_log.p_game_id = game_id;
            my_log.p_table_id = _table_id;
            log.Error(my_log.ToString());
        }
    }
    /// <summary>
    /// This method is used to get the values of all Flop Cards when 
    /// someone click on Deal Buttons except Hole Button. Then save 
    /// that value of Flop Card to Session.
    /// Also get CSS value from session as described below. */
    /// </summary>
    private void f_update_hedgeem_control_board_cards_with_info_from_server()
    {
        try
        {
            log.Debug("f_update_hedgeem_control_board_cards_with_info_from_server called");

            // Create the FLOP card instances
            cc_flop_card1 = new hedgeem_control_card();
            cc_flop_card2 = new hedgeem_control_card();
            cc_flop_card3 = new hedgeem_control_card();
            // Get reference to the Application scoped Hedge'Em control that models the 'Turn' card
            // xxx NOTE the only reason the TURN card is coded diffently from other board cards was to prove that
            // it could be coded as an application scoped control.  I (Simon) do not know which method is best.
            // Logically there should only ever be one instance of a TURN card at any given table so I was thinking 
            // it would be best to instantiate only once.
            hedgeem_control_card my_turn_card = new hedgeem_control_card();
            hedgeem_control_card my_river_card = new hedgeem_control_card();
            hedgeem_control_jackpot my_control_jackpot = new hedgeem_control_jackpot();
            my_control_jackpot.p_jackpot_balance = my_jackpot_fund;

            // Note expect card as short string to be something like ac (ace of clubs), 6d (six of diamonds etc)
            // If ZZ us returned this implies the card is to be shown face down.
            p_flop_card1_as_short_string = _global_game_state_object.p_flop_card1_string;
            p_flop_card2_as_short_string = _global_game_state_object.p_flop_card2_string;
            p_flop_card3_as_short_string = _global_game_state_object.p_flop_card3_string;
            p_turn_as_short_string = _global_game_state_object.p_turn_card_string;
            p_river_as_short_string = _global_game_state_object.p_river_card_string;

            // Set the FLOP, TURN and RIVER card values using values specified by server
            // E.g. if the Server thinks the FLOP card in 'Six of clubs' (6c) set GUI control to 6c
            cc_flop_card1.p_card_as_short_string = p_flop_card1_as_short_string;
            cc_flop_card2.p_card_as_short_string = p_flop_card2_as_short_string;
            cc_flop_card3.p_card_as_short_string = p_flop_card3_as_short_string;

            my_turn_card.p_card_as_short_string = p_turn_as_short_string;
            my_river_card.p_card_as_short_string = p_river_as_short_string;

            // Set the style attribute for the Board card (e.g. whether they are position in left,right or middle position)
            cc_flop_card1.p_enum_card_position = enum_card_position.MIDDLE;
            cc_flop_card2.p_enum_card_position = enum_card_position.MIDDLE;
            cc_flop_card3.p_enum_card_position = enum_card_position.MIDDLE;
            my_turn_card.p_enum_card_position = enum_card_position.MIDDLE;
            my_river_card.p_enum_card_position = enum_card_position.MIDDLE;
            cc_flop_card1.p_cssclass = "card_left_flop";
            cc_flop_card2.p_cssclass = "card_middle_flop";
            cc_flop_card3.p_cssclass = "card_right_flop";
            my_turn_card.p_cssclass = "card_middle_turn";
            my_river_card.p_cssclass = "card_middle_river";

            Place_Holder_Flop_Cards.Controls.Add(cc_flop_card1);
            Place_Holder_Flop_Cards.Controls.Add(cc_flop_card2);
            Place_Holder_Flop_Cards.Controls.Add(cc_flop_card3);
            Place_Holder_Turn_Cards.Controls.Add(my_turn_card);
            Place_Holder_River_Cards.Controls.Add(my_river_card);
            Place_Holder_Table_Jackpot.Controls.Add(my_control_jackpot);


            lbl_game_id.Text = String.Format("Table/Game: {0}/{1} ", _global_game_state_object.p_table_id, game_id);

            // Control to show placed bets.  Only show during betting stages HOLE, FLOP and TURN and at RIVER/PAYOUT stage.

            if (_game_state >= enum_game_state.STATUS_HOLE && _game_state <= enum_game_state.STATUS_RIVER)
            {
                hedgeem_control_placed_bets my_control_placed_bets = new hedgeem_control_placed_bets();

                int count = _global_game_state_object._recorded_bets.Count;
                int bets = 0;
                foreach (HedgeEmBet hedgeem_bets in _global_game_state_object._recorded_bets)
                {
                    bets = (int)hedgeem_bets.p_bet_amount;
                }
                p_total_bets = bets * count;
                my_control_placed_bets.p_placed_bets = p_total_bets;
                Place_Holder_Placed_Bets.Controls.Add(my_control_placed_bets);
            }
        }
        catch (Exception ex)
        {
            string my_error_popup = "alert('" + ex.Message.ToString() + "');";
            ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
            HedgeEmLogEvent my_log = new HedgeEmLogEvent();
            my_log.p_message = "Exception caught in f_update_hedgeem_control_board_cards_with_info_from_server function " + ex.Message;
            my_log.p_method_name = "f_update_hedgeem_control_board_cards_with_info_from_server";
            my_log.p_player_id = f_get_player_id();
            my_log.p_game_id = game_id;
            my_log.p_table_id = _table_id;
            log.Error(my_log.ToString());
        }
    }
    //#region f_activate_deal_hole_button_and_hide_others
    //private void f_activate_deal_hole_button_and_hide_others()
    //{
    //    /*----- This function only shown Deal Display Random others are invisible------*/
    //    btnDealHole.Visible = true;
    //    btnDealFlop.Visible = false;
    //    btnDealTurn.Visible = false;
    //    btnDealRiver.Visible = false;
    //    btnNextGame.Visible = false;
    //}
    //#endregion

    //#region f_activate_deal_flop_button_and_hide_others
    //private void f_activate_deal_flop_button_and_hide_others()
    //{
    //    /*----- This function only shown Deal Flop others are invisible------*/
    //    btnDealHole.Visible = false;
    //    btnDealFlop.Visible = true;
    //    btnDealTurn.Visible = false;
    //    btnDealRiver.Visible = false;
    //    btnNextGame.Visible = false;
    //    btnLobby.Visible = true;
    //}
    //#endregion

    //#region f_activate_deal_turn_button_and_hide_others
    //private void f_activate_deal_turn_button_and_hide_others()
    //{
    //    /*----- This function only shown Deal Turn others are invisible------*/
    //    btnDealHole.Visible = false;
    //    btnDealFlop.Visible = false;
    //    btnDealTurn.Visible = true;
    //    btnDealRiver.Visible = false;
    //    btnNextGame.Visible = false;
    //    btnLobby.Visible = true;
    //}
    //#endregion Visible_Deal_Turn_Buttons

    //#region f_activate_deal_river_button_and_hide_others
    //private void f_activate_deal_river_button_and_hide_others()
    //{
    //    /*----- This function only shown Deal River others are invisible------*/
    //    btnDealHole.Visible = false;
    //    btnDealFlop.Visible = false;
    //    btnDealTurn.Visible = false;
    //    btnDealRiver.Visible = true;
    //    btnLobby.Visible = true;
    //}
    //#endregion Visible_Deal_River_Buttons

    //#region f_activate_deal_next_button_and_hide_others
    //private void f_activate_deal_next_button_and_hide_others()
    //{
    //    /*----- This function only shown Deal Next others are invisible------*/
    //    btnDealHole.Visible = false;
    //    btnDealFlop.Visible = false;
    //    btnDealTurn.Visible = false;
    //    btnDealRiver.Visible = false;
    //    btnNextGame.Visible = true;
    //}
    //#endregion Visible_Deal_Next_Buttons

    /// Context / Background reading
    /// ----------------------------
    /// You must understand the following before understanding this function
    /// + What the HedgeEmHandStageInfo class is and what its purpose is.
    /// 
    /// History
    /// -----------
    /// Original Author: Simon Hewins Jul 2014
    /// Last edit:       Simon Hewins Aug 2014
    /// 
    /// Description
    /// -----------
    /// 
    /// Gets a LIST of HedgeEmHandStageInfo objects for any given hand (index) at any given stage.
    /// </summary>
    /// <param name="a_enum_game_state"></param>
    /// <param name="a_hand_index"></param>
    /// <returns></returns>
    public List<HedgeEmBet> f_get_previous_bets_for_stage_and_hand_player_list(enum_betting_stage a_enum_betting_stage, int a_hand_index, int a_player_id)
    {
        /// xxx hack until Bet contains player id
        a_player_id = 0;

        List<HedgeEmBet> my_previous_bets_list = new List<HedgeEmBet>();
        try
        {
            my_previous_bets_list = (from handsstage_objects in _global_game_state_object.p_recorded_bets
                                     where handsstage_objects.p_enum_betting_stage == a_enum_betting_stage
                         && handsstage_objects.p_hand_index == a_hand_index
                         && handsstage_objects.p_seat_index == a_player_id
                                     select handsstage_objects).ToList();
        }
        catch (Exception ex)
        {
            string my_error_popup = "alert('Error in f_get_previous_bets_for_stage_and_hand" + ex.Message.ToString() + "');";
            ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
            HedgeEmLogEvent my_log = new HedgeEmLogEvent();
            my_log.p_message = "Exception caught in f_get_hand_stage_info_object_for_stage_and_hand function " + ex.Message;
            my_log.p_method_name = "f_get_hand_stage_info_object_for_stage_and_hand";
            my_log.p_player_id = f_get_player_id();
            my_log.p_game_id = game_id;
            my_log.p_table_id = _table_id;
            log.Error(my_log.ToString());
        }
        return my_previous_bets_list;
    }
    protected void btn_play_now_Click(object sender, EventArgs e)
    {

        // Log that the user has clicked the 'Play now' button.
        HedgeEmLogEvent my_log_event = new HedgeEmLogEvent();
        my_log_event.p_method_name = System.Reflection.MethodBase.GetCurrentMethod().ToString();
        my_log_event.p_table_id = p_session_personal_table_id;
        my_log_event.p_server_id = p_session_server_id;
        my_log_event.p_message = String.Format("User [{0}] click 'Play Now", p_session_username);
        log.Info(my_log_event.ToString());

        // This fucntion should not be able to be played if the player as not logged in, so test if they have 
        // a 'HedgeEm Session' has been established,  If not exit this fucntion. 
        if (!p_valid_session_exists)
        {
            my_log_event.p_message = String.Format("User informed the must be logged in to play.");
            log.Debug(my_log_event.ToString());

            //ScriptManager.RegisterStartupScript(Page, GetType(), "Alert Message", "alert('You must be logged in to Play this game.');", true);
            ScriptManager.RegisterStartupScript(Page, GetType(), "Alert Message", "document.getElementById('alertmessage').style.display = 'block';", true);
            return;
        }


        // xxx Consider uncommenting the following after aslo considering consequence (if you do this when user clicks leave table 
        // they will leave there personal table which you may not want currently as the code currently (Dec 2014) assumes you are sitting at
        // personal table all the time.
        p_session_current_table_id = p_session_personal_table_id;

        f_goto_table(p_session_personal_table_id);

        // If code reaches here we asssume Table ID and PlayerID is known so sit the person at this table


    }
    /// Context / Background reading
    /// ----------------------------
    /// You must understand the following before understanding this function
    /// + What the HedgeEmHandStageInfo class is and what its purpose is.
    /// 
    /// History
    /// -----------
    /// Original Author: Simon Hewins Jul 2014
    /// Last edit:       Simon Hewins Aug 2014
    /// 
    /// Description
    /// -----------
    /// 
    /// Gets a LIST of HedgeEmHandStageInfo objects for any given hand (index) at any given stage.
    /// </summary>
    /// <param name="a_enum_game_state"></param>
    /// <param name="a_hand_index"></param>
    /// <returns></returns>
    public double f_get_total_previous_bets_for_stage_and_hand_player(enum_betting_stage a_enum_betting_stage, int a_hand_index, int a_player_id)
    {
        /// xxx hack until Bet contains player id
        a_player_id = 0;

        List<HedgeEmBet> my_previous_bets_list = new List<HedgeEmBet>();

        HedgeEmBet myHedgeEmBet = null;
        double my_bet_total = -666;

        try
        {
            my_previous_bets_list = (from handsstage_objects in _global_game_state_object.p_recorded_bets
                                     where handsstage_objects.p_enum_betting_stage == a_enum_betting_stage
                         && handsstage_objects.p_hand_index == a_hand_index
                         && handsstage_objects.p_seat_index == a_player_id
                                     select handsstage_objects).ToList();

            my_bet_total = (from handsstage_objects in _global_game_state_object.p_recorded_bets
                            where handsstage_objects.p_enum_betting_stage == a_enum_betting_stage
                && handsstage_objects.p_hand_index == a_hand_index
                && handsstage_objects.p_seat_index == a_player_id
                            select handsstage_objects.p_bet_amount).Sum();

            /*if (my_previous_bets_list.Count > 1)
            {
                String my_err_msg = String.Format("Expected only one 'Bet' for state [{0}], hand [{1}] object got [{1}] ",
                    a_enum_betting_stage.ToString(),
                    a_hand_index,
                    my_previous_bets_list.Count);

                throw new Exception(my_err_msg);
            }*/

            //myHedgeEmBet = my_previous_bets_list[0];

        }
        catch (Exception ex)
        {
            string my_error_popup = "alert('Error in f_get_previous_bets_for_stage_and_hand" + ex.Message.ToString() + "');";
            ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
            HedgeEmLogEvent my_log = new HedgeEmLogEvent();
            my_log.p_message = "Exception caught in f_get_hand_stage_info_object_for_stage_and_hand function " + ex.Message;
            my_log.p_method_name = "f_get_hand_stage_info_object_for_stage_and_hand";
            my_log.p_player_id = f_get_player_id();
            my_log.p_game_id = game_id;
            my_log.p_table_id = _table_id;
            log.Error(my_log.ToString());
        }
        return my_bet_total;
    }
    protected void btn_new_user_Click(object sender, EventArgs e)
    {
        HedgeEmLogEvent my_log_event = new HedgeEmLogEvent();
        my_log_event.p_method_name = System.Reflection.MethodBase.GetCurrentMethod().ToString();
        my_log_event.p_message = "This message creates new user in database";
        log.Debug(my_log_event.ToString());
        string my_endpoint = "Not Set";

        bool user_exist;
        hedgeem_control_popup_message my_popup_message = new hedgeem_control_popup_message();
        my_popup_message.p_detailed_message_str = "";

        try
        {
            // This checks whether the entered email id exists in the database or not.
            my_endpoint = String.Format("{0}/ws_get_player_list/sessionabc123,{1},10000/", p_current_json_webservice_url_base, p_server_id);

            List<HedgeEmPlayer> my_player_list = (List<HedgeEmPlayer>)f_get_object_from_json_call_to_server(my_endpoint, typeof(List<HedgeEmPlayer>));
            user_exist = my_player_list.Exists(x => x.p_username == txt_username.Text);

            if (user_exist == false)
            {
                xxxHC_a_opening_balance = 100;
                try
                {
                    enum_authentication_method my_authentication_method = enum_authentication_method.HEDGEEM_ACCOUNT;
                    // Creates (registers) a new user (HedgeEmPlayer) in the HedgeEm Server.
                    // Note this also creates a Personal Table for them (which the HedgeEmTable is returned in the Player object 'p_personal_table_id
                    my_endpoint = String.Format("{0}/ws_register_user_and_create_personal_table/{1},{2},{3},{4},{5}/",
                                                    p_current_json_webservice_url_base,
                                                    txt_username.Text,
                                                    txt_password.Text,
                                                    txt_full_name.Text,
                                                    xxxHC_a_opening_balance,
                                                    my_authentication_method);

                    HedgeEmPlayer my_player = (HedgeEmPlayer)f_get_object_from_json_call_to_server(my_endpoint, typeof(HedgeEmPlayer));
                    if (my_player.p_error_message != null)
                    {
                        if (my_player.p_error_message != "")
                        {
                //            throw new Exception(my_player.p_error_message);




                        }
                    }

                    // If we got here we assume Player was created successfully so store Player ID and continue
                    p_session_player_id = my_player.p_player_id;


                    // login to the game
                    Session["p_session_username"] = txt_username.Text;
                    Session["password"] = txt_password.Text;
                    Session["display_name"] = txt_full_name.Text;
                    Session["p_session_personal_table_id"] = my_player.p_personal_table_id;
                    Session["p_session_username"] = my_player.p_username;
                    Session["p_session_password"] = txt_password.Text;
                    Session["p_session_display_name"] = my_player.p_display_name;

                    //sends registration mail
                    //send_user_registration_mail(txt_username.Text, txt_password.Text, txt_full_name.Text);

                    //my_popup_message.p_detailed_message_str = "Thank you for registering, you may now start to play.  Please don't forget to confirm your registration by clicking on the link in the mail we have just sent you to get your free 50 chips and benefit from extra features.";
                    //Place_Holder_Popup_Message.Controls.Add(my_popup_message);
                    HedgeemMessage my_popup_messageError = new HedgeemMessage();
                    my_popup_messageError.p_detailed_message_str = "";
                    my_popup_messageError.p_detailed_message_str = "Thank you for registering, you may now start to play.  Please don't forget to confirm your registration by clicking on the link in the mail we have just sent you to get your free 50 chips and benefit from extra features.";
                    my_popup_messageError.p_is_visible = true;

                    Place_Holder_Popup_Message.Controls.Add(my_popup_messageError);

                    my_popup_messageError.Dispose();
                   // ScriptManager.RegisterStartupScript(Page, GetType(), "OnLoad", "alert('Thank you for registering. You may now start to play. Click on the link in the mail we have just sent you to get benefit from extra features.');", true);
                    //ScriptManager.RegisterStartupScript(Page, GetType(), "OnLoad", "alert('Thank you for registering, you may now start to play.  Please don't forget to confirm your registration by clicking on the link in the mail we have just sent you to get your free 50 chips and benefit from extra features.'); if(alert){ window.location='frm_facebook_canvas.aspx';}", true);
                    if (Session["p_session_username"] != null)
                    {

                        Logout.Attributes.Add("style", "display:block!Important;");
                        btnLogout.Visible = true;
                        btnLogout.Enabled = true;
                        Page.RegisterStartupScript("OnLoading", "<script>load_edit_profile();</script>");
                        if (Session["display_name"] != null)
                        {
                            lbl_user_name.Text = Session["display_name"].ToString();
                        }
                        //LoginDiv.Attributes.Add("style", "display:none !Important;");
                        divLogin.Attributes.Add("style", "display:none !Important;");
                        if (Session["p_session_username"] != null)
                        {
                            if (File.Exists(Server.MapPath("resources/player_avatar_" + Session["p_session_username"].ToString() + ".jpg")))
                            {
                                usr_image.ImageUrl = "../resources/player_avatar_" + Session["p_session_username"].ToString() + ".jpg";
                            }
                            
                            else
                            {
                                usr_image.ImageUrl = "../resources/avitars/user_square.png";
                            }
                        }

                        btn_play_now.Enabled = true;



                        string role = "";
                        if (my_player != null)
                        {
                            role = my_player.p_role;

                            my_log_event.p_message = String.Format("User/player role hardcoded to BASIC_USER");
                            log.Debug(my_log_event.ToString());

                        }

                        if (role == enum_user_role.ADMIN.ToString())
                        {
                            btnAdmin.Attributes.Add("style", "display:block");
                        }

                        // - xxx- Hardcoding value of role to BASIC_USER as need to discuss this with Simon.
                        Session["user_role"] = "BASIC_USER";
                        Page.RegisterStartupScript("OnLoad", "<script>document.getElementById('progressbar').style.display='none';</script>");
                    }

                }
                catch (Exception ex)
                {
                    my_log_event.p_message = String.Format("Reason [{0}]", ex.Message);
                    HedgeemerrorPopup my_popup_messageError = new HedgeemerrorPopup();
                    my_popup_messageError.p_detailed_message_str = "";
                    my_popup_messageError.p_detailed_message_str = String.Format("Reason [{0}]", ex.Message);
                    my_popup_messageError.p_is_visible = true;

                    Place_Holder_Popup_Message.Controls.Add(my_popup_messageError);

                    my_popup_messageError.Dispose();
                    log.Error(my_log_event.ToString());
                 //   throw new Exception(my_log_event.ToString());
                }
            }

            else
            {
                lbl_register_status_msg.Visible = true;
                lbl_register_status_msg.Text = "This User Already exists. Please try again or Login to continue.";
                //ScriptManager.RegisterStartupScript(Page, GetType(), "OnLoad", "alert('This User Already exists. Please try again or Login to continue.');", true);
            }
        }
        catch (Exception ex)
        {
            string my_error_message = String.Format("ERROR! Unable to create user.  Reason [{0}]", ex.Message);
            //string my_error_popup = "alert('Error in creating user - " + ex.Message.ToString() + "');";
            lbl_register_status_msg.Visible = true;
            lbl_register_status_msg.Text = "ERROR! Unable to create user.  Hedge'Em Administrators have been informed.";
            log.Error("Error in creating user", new Exception(ex.Message));
            HedgeemerrorPopup my_popup_messageError = new HedgeemerrorPopup();
            my_popup_messageError.p_detailed_message_str = "";
            my_popup_messageError.p_detailed_message_str = my_error_message;
            my_popup_messageError.p_is_visible = true;

            Place_Holder_Popup_Message.Controls.Add(my_popup_messageError);

            my_popup_messageError.Dispose();
            //throw new Exception("ssssss");

        }
    }
    /// <summary>
    /// Context / Background reading
    /// ----------------------------
    /// You must understand the following before understanding this function
    /// + What the HedgeEmHandStageInfo class is and what its purpose is.
    /// 
    /// History
    /// -----------
    /// Original Author: Simon Hewins Jul 2014
    /// Last edit:       Simon Hewins Aug 2014
    /// 
    /// Description
    /// -----------
    /// 
    /// Gets a LIST of HedgeEmHandStageInfo objects for any given hand (index) at any given stage.
    /// </summary>
    /// <param name="a_enum_game_state"></param>
    /// <param name="a_hand_index"></param>
    /// <returns></returns>
    public HedgeEmHandStageInfo f_get_hand_stage_info_object_for_stage_and_hand(enum_game_state a_enum_game_state, int a_hand_index)
    {
        List<HedgeEmHandStageInfo> myHedgeEmHandStageInfoList = new List<HedgeEmHandStageInfo>();
        HedgeEmHandStageInfo myHedgeEmHandStageInfo = null;
        try
        {
            // Return without searching if not a valid state where a hand_stage_info object is expected.
            if (!(a_enum_game_state == enum_game_state.STATUS_HOLE || a_enum_game_state == enum_game_state.STATUS_FLOP || a_enum_game_state == enum_game_state.STATUS_TURN || a_enum_game_state == enum_game_state.STATUS_RIVER))
            {
                return myHedgeEmHandStageInfo;
            }
            myHedgeEmHandStageInfoList = (from handsstage_objects in _global_game_state_object.p_hand_stage_info_list
                                          where handsstage_objects.p_enum_game_state == a_enum_game_state
                             && handsstage_objects.p_hand_index == a_hand_index
                                          select handsstage_objects).ToList();

            if (myHedgeEmHandStageInfoList.Count > 1)
            {
                String my_err_msg = String.Format("Expected only one 'HandStatusInfo' for state [{0}], hand [{1}] object got [{1}] ",
                    a_enum_game_state.ToString(),
                    a_hand_index,
                    myHedgeEmHandStageInfoList.Count);

                throw new Exception(my_err_msg);
            }
            myHedgeEmHandStageInfo = myHedgeEmHandStageInfoList[0];

        }
        catch (Exception ex)
        {
            string my_error_popup = "alert('Error in f_get_hand_stage_info_object_for_stage_and_hand" + ex.Message.ToString() + "');";
            ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
            HedgeEmLogEvent my_log = new HedgeEmLogEvent();
            my_log.p_message = "Exception caught in f_get_hand_stage_info_object_for_stage_and_hand function " + ex.Message;
            my_log.p_method_name = "f_get_hand_stage_info_object_for_stage_and_hand";
            my_log.p_player_id = f_get_player_id();
            my_log.p_game_id = game_id;
            my_log.p_table_id = _table_id;
            log.Error(my_log.ToString());
            throw new Exception(my_error_popup);
        }
        return myHedgeEmHandStageInfo;
    }
    protected void f_login_anonymously(int a_player_id)
    {




        HedgeEmLogEvent my_log_event = new HedgeEmLogEvent();
        my_log_event.p_method_name = System.Reflection.MethodBase.GetCurrentMethod().ToString();
        // Log the fact this method has been called
        my_log_event.p_message = String.Format("Method [btn_login_Click] called ");
        log.Debug(my_log_event.ToString());
        string my_endpoint = "Not Set";
        
        // Declare vairibles that will be required later
        string my_username = "";
        string my_password = "";
        DataTable my_user_details;

        
        try
        {
            // Attempt to retrieve a Player object from the HedgeEm Webservice using the credentials supplied.
            my_endpoint = String.Format("{0}/ws_login/{1},{2},{3},{4}/", p_current_json_webservice_url_base, p_session_id, p_session_server_id, my_username, my_password);
            HedgeEmPlayer my_player = (HedgeEmPlayer)f_get_object_from_json_call_to_server(my_endpoint, typeof(HedgeEmPlayer));

            if (my_player == null)
            {
                string my_error_msg = String.Format("Player object is null after call to Webservice to retrieve details", my_username);
                my_log_event.p_message = my_error_msg;
                log.Error(my_log_event.ToString());
                throw new Exception(my_error_msg);
            }

            if (my_player.p_player_id <= 0)
            {
                my_log_event.p_message = my_player.p_error_message;
                log.Error(my_log_event.ToString());
                throw new Exception(my_log_event.ToString());

            }
            else
            {
                // If we have got here the user has logged into the server sucessfully so we should set some session variables for ease of use later
                int my_player_id = my_player.p_player_id;
                Session["p_session_player_id"] = my_player_id;
                Session["display_name"] = my_player.p_display_name;
                Session["p_session_username"] = my_username;
                Session["password"] = my_password;
                Session["user_role"] = my_player.p_role;
                        
                p_session_personal_table_id = my_player.p_personal_table_id;
                if (Session["p_session_username"] != null)
                {
                    if (File.Exists(Server.MapPath("resources/player_avatar_" + Session["p_session_username"].ToString() + ".jpg")))
                    {
                        usr_image.ImageUrl = "../resources/player_avatar_" + Session["p_session_username"].ToString() + ".jpg";
                    }

                    else
                    {
                        usr_image.ImageUrl = "../resources/avitars/user_square.png";
                    }
                }
                // As the user has now logged in by HedgeEm authentication hide the Facebook login DIV
                if (Session["facebooklogin"] != null)
                {
                    //LoginDiv.Attributes.Add("style", "display:none !Important;");
                }

                // As the user has now logged show the logout button and hide the login button
                // xxx Nov 2014.  Not sure why this is on condition of facebooklogin; I separated this out from if/else
                // of above to figure this out.  I assume is because you could be logged in by facebook so still want to
                // show / hide login/logout buttons appropriately
                if (Session["facebooklogin"] == null)
                {
                    lbl_user_name.Text = Session["display_name"].ToString();
                    Logout.Attributes.Add("style", "display:block !Important;");
                    //LoginDiv.Attributes.Add("style", "display:none !Important;");
                    divLogin.Attributes.Add("style", "display:none !Important;");
                    userdetails.Attributes.Add("style", "display:none !Important;");
                    btnLogout.Visible = true;
                    btnLogout.Enabled = true;
                    Page.RegisterStartupScript("OnLoad", "<script>document.getElementById('userdetails').style.display='none';</script>");
                }

                
                string role = "";
                if (my_player != null)
                {
                    role = my_player.p_role;
                    my_log_event.p_message = String.Format("User/player role determined to be [{0}].", role.ToString());
                    log.Debug(my_log_event.ToString());
                }

                
            }
        }
        catch (Exception ex)
        {
            string my_error_message = "Fatal Errorin method [btn_login_Click] - " + ex.Message.ToString() + "');";

            //  Log the error and raise a new exception
            my_log_event.p_message = String.Format(
                "Fatal error in method [btn_login_Click]. Reason [{0}]",
                        ex.Message);
            log.Error(my_log_event.ToString(), new Exception(ex.Message));
            HedgeemerrorPopup my_popup_message = new HedgeemerrorPopup();
            my_popup_message.p_detailed_message_str = "";
            my_popup_message.p_is_visible = false;

            //ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
            my_popup_message.p_detailed_message_str = my_error_message.ToString();
            my_popup_message.p_is_visible = true;
            Place_Holder_Popup_Message.Controls.Add(my_popup_message);
        }

    }
 /// <summary>
 /// Context / Background reading
 /// ----------------------------
 /// You must understand the following before understanding this function
 /// + What the HedgeEmHandStageInfo class is and what its purpose is.
 /// 
 /// History
 /// -----------
 /// Original Author: Simon Hewins Jul 2014
 /// Last edit:       Simon Hewins Aug 2014
 /// 
 /// Description
 /// -----------
 /// 
 /// Gets a LIST of HedgeEmHandStageInfo objects for any given hand (index) at any given stage.
 /// </summary>
 /// <param name="a_enum_game_state"></param>
 /// <param name="a_hand_index"></param>
 /// <returns></returns>
 public List<HedgeEmHandStageInfo> f_get_hand_stage_info_object_for_stage_and_hand_list(enum_game_state a_enum_game_state, int a_hand_index)
 {
     List<HedgeEmHandStageInfo> myHedgeEmHandStageInfo = new List<HedgeEmHandStageInfo>();
     try
     {
         myHedgeEmHandStageInfo = (from handsstage_objects in _global_game_state_object.p_hand_stage_info_list
                                   where handsstage_objects.p_enum_game_state == a_enum_game_state
                      && handsstage_objects.p_hand_index == a_hand_index
                                   select handsstage_objects).ToList();
     }
     catch (Exception ex)
     {
         string my_error_popup = "alert('Error in f_get_hand_stage_info_object_for_stage_and_hand" + ex.Message.ToString() + "');";
         ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
         HedgeEmLogEvent my_log = new HedgeEmLogEvent();
         my_log.p_message = "Exception caught in f_get_hand_stage_info_object_for_stage_and_hand function " + ex.Message;
         my_log.p_method_name = "f_get_hand_stage_info_object_for_stage_and_hand";
         my_log.p_player_id = f_get_player_id();
         my_log.p_game_id = game_id;
         my_log.p_table_id = _table_id;
         log.Error(my_log.ToString());
     }
     return myHedgeEmHandStageInfo;
 }
    protected void f_login_anonymously(int a_player_id)
    {
        HedgeEmLogEvent my_log_event = new HedgeEmLogEvent();
        my_log_event.p_method_name = System.Reflection.MethodBase.GetCurrentMethod().ToString();
        // Log the fact this method has been called
        my_log_event.p_message = String.Format("Method [btn_login_Click] called ");
        log.Debug(my_log_event.ToString());
        string my_endpoint = "Not Set";
        
        // Declare vairibles that will be required later
        string my_username = "";
        string my_password = "";
        DataTable my_user_details;

        
        try
        {
            // Attempt to retrieve a Player object from the HedgeEm Webservice using the credentials supplied.
            my_endpoint = String.Format("{0}/ws_login/{1},{2},{3},{4}/", p_current_json_webservice_url_base, p_session_id, p_session_server_id, my_username, my_password);
            HedgeEmPlayer my_player = (HedgeEmPlayer)f_get_object_from_json_call_to_server(my_endpoint, typeof(HedgeEmPlayer));

            if (my_player == null)
            {
                string my_error_msg = String.Format("Player object is null after call to Webservice to retrieve details", my_username);
                my_log_event.p_message = my_error_msg;
                log.Error(my_log_event.ToString());
                throw new Exception(my_error_msg);
            }

            if (my_player.p_player_id <= 0)
            {
                my_log_event.p_message = my_player.p_error_message;
                log.Error(my_log_event.ToString());
                throw new Exception(my_log_event.ToString());

            }
            else
            {
                // If we have got here the user has logged into the server sucessfully so we should set some session variables for ease of use later
                int my_player_id = my_player.p_player_id;
                Session["p_session_player_id"] = my_player_id;
                Session["display_name"] = my_player.p_display_name;
                Session["p_session_username"] = my_username;
                Session["password"] = my_password;
                Session["user_role"] = my_player.p_role;
                        
                p_session_personal_table_id = my_player.p_personal_table_id;
                
                
                string role = "";
                if (my_player != null)
                {
                    role = my_player.p_role;
                    my_log_event.p_message = String.Format("User/player role determined to be [{0}].", role.ToString());
                    log.Debug(my_log_event.ToString());
                }

                
            }
        }
        catch (Exception ex)
        {
            string my_error_message = "Fatal Errorin method [btn_login_Click] - " + ex.Message.ToString() + "');";

            //  Log the error and raise a new exception
            my_log_event.p_message = String.Format(
                "Fatal error in method [btn_login_Click]. Reason [{0}]",
                        ex.Message);
            log.Error(my_log_event.ToString(), new Exception(ex.Message));
            HedgeemerrorPopup my_popup_message = new HedgeemerrorPopup();
            my_popup_message.p_detailed_message_str = "";
            my_popup_message.p_is_visible = false;

            //ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
            my_popup_message.p_detailed_message_str = my_error_message.ToString();
            my_popup_message.p_is_visible = true;
            Place_Holder_Popup_Message.Controls.Add(my_popup_message);
        }

    }
    //This function is used to Maintain Hand Panel Values when Bet is Placed on a Hand.
    public void f_place_bet()
    {
        HedgeEmLogEvent my_log = new HedgeEmLogEvent();
        my_log.p_message = String.Format("Method called. Player [{0}], Table [{1}], Game [{2}]", f_get_player_id(), _table_id, game_id);
        my_log.p_method_name = "frm_hedgeem_table.f_place_bet()";
        my_log.p_player_id = f_get_player_id();
        my_log.p_game_id = game_id;
        my_log.p_table_id = _table_id;

        enum_betting_stage my_betting_stage = (enum_betting_stage)Session["sess_betting_stage_enum"];


        log.Debug(my_log.ToString());
        /* Get value of Selected_Hand_Panel for bet from textbox and save it in a variable */
        try
        {
            // Get the hand_index from the hidden control
            int handindexbet = Convert.ToInt32(btn_hidden_control_temp_store_for_hand_index.Value);
            DC_bet_acknowledgement my_bet_ack;

            // xxx_HC hardcode the bet value to be £1
            int bet_amount = 1;
            enum_betting_stage my_betting_stage_enum = (enum_betting_stage)Session["sess_betting_stage_enum"];
            my_bet_ack = f_place_bet(my_betting_stage_enum, handindexbet, bet_amount);
            if (my_bet_ack.p_ack_or_nak != enum_acknowledgement_type.ACK.ToString())
            {
                string short_desc = "Bet not accepted because.  Reason: ";
                //To show error description that why bet is not accepted inside div
                short_description.InnerHtml = short_desc + my_bet_ack.p_nak_reason + " Player Id: " + f_get_player_id() + " Stage: " + my_betting_stage;
                ScriptManager.RegisterStartupScript(Page, GetType(), "JsStatus", "document.getElementById('error_message').style.display = 'block';document.getElementById('fade').style.display = 'block';", true);
            }
        }
        catch (Exception ex)
        {
            string my_error_popup = "alert('Error in frm.hedgeem_table.cs.f_place_bet" + ex.Message.ToString() + "');";
            ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
            my_log = new HedgeEmLogEvent();
            my_log.p_message = "Exception caught in f_place_bet function " + ex.Message;
            my_log.p_method_name = "f_place_bet";
            my_log.p_player_id = f_get_player_id();
            my_log.p_game_id = game_id;
            my_log.p_table_id = _table_id;
            log.Error(my_log.ToString());
        }
    }
    private void f_goto_table(int a_table_id)
    {
        HedgeEmLogEvent my_log_event = new HedgeEmLogEvent();
        my_log_event.p_method_name = System.Reflection.MethodBase.GetCurrentMethod().ToString();
        my_log_event.p_message = "Method Entered";
        my_log_event.p_server_id = 4663662;
        my_log_event.p_table_id = a_table_id;
        my_log_event.p_player_id = p_session_player_id;

        log.Debug(my_log_event.ToString());

        /* Get reference to table by this table id
         For this GUI to work we need a HedgeEMTable object that it will obtain its data from (e.g. cards to display,
         odds for each hand etc).  So create a place-holder object that we will set later. */
        string my_endpoint = "Not Set";


        try
        {
            if (p_valid_session_exists)
            {

                HedgeemThemeInfo my_hedgeem_theme_info = new HedgeemThemeInfo();
                bool xxxHC_my_get_theme_info_from_server_definition = false;
                string theme_name = enum_theme.ONLINE.ToString();

                if (xxxHC_my_get_theme_info_from_server_definition){
                    my_endpoint = String.Format("{0}/ws_get_theme_details_for_hedgeem_table/{1}/", p_current_json_webservice_url_base, a_table_id);
                    my_hedgeem_theme_info = (HedgeemThemeInfo)f_get_object_from_json_call_to_server(my_endpoint, typeof(HedgeemThemeInfo));

                    if (my_hedgeem_theme_info == null)
                    {
                        throw new Exception(String.Format("Unable to determine theme for table [{0}]", a_table_id));
                    }

                    if (my_hedgeem_theme_info._error_message != "")
                    {
                        throw new Exception(my_hedgeem_theme_info._error_message);
                    }
                    theme_name = my_hedgeem_theme_info.short_name;
                    Session["theme"] = theme_name;
                }


                // xxx Note from Simon Jan 2015 - not sure what this next line does.  If it is just a pop up it can be deleted (esp as it does not work anyway)
                //ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", "alert('" + "Theme name -" + Session["theme"].ToString() + "');", true);

                my_log_event.p_message = String.Format("Successfully retrieved theme for table ID [{0}] Theme [{1}] so redirecting to (opening) HedgeEmTable page so ASP can render page to this theme.", a_table_id, theme_name);
                log.Debug(my_log_event.ToString());

                Response.Redirect("frm_hedgeem_table.aspx", false);
            }
            else
            {
                Page.RegisterStartupScript("OnLoad", "<script>alert('You need to be logged in to sit at this table');</script>");
            }
        }
        catch (Exception ex)
        {
            // xxx_eh error not show to user
            string my_error_popup = "alert('Error in method [f_goto_table] - " + ex.Message.ToString() + "');";
        //    ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
            my_log_event.p_message = String.Format("Error", ex.Message);
            log.Error(my_log_event.ToString());
            //throw new Exception(my_log_event.ToString());               


            HedgeemerrorPopup my_popup_message = new HedgeemerrorPopup();
            my_popup_message.p_detailed_message_str = "";
              my_popup_message.p_detailed_message_str = my_error_popup;
            my_popup_message.p_is_visible = true;
            
            //newuser.Visible = false;
            
            Place_Holder_Popup_Message.Controls.Add(my_popup_message);
        
            my_popup_message.Dispose();

        }
    }
 // preinit event changes the theme of the page at runtime before page loads
 protected void Page_PreInit(object sender, EventArgs e)
 {
     HedgeEmLogEvent my_log_event = new HedgeEmLogEvent();
     my_log_event.p_method_name = "frm_home_page.aspx.cs-Page_PreInit";
     my_log_event.p_message = "Method called";
     log.Debug(my_log_event.ToString());
     //ThreadStart tsTask = new ThreadStart(TaskLoop);
     //Thread MyTask = new Thread(tsTask);
     //MyTask.Start();
     try
     {
         if (Session["theme"] == null)
         {
             my_log_event.p_message = "Warning - hard coding of theme to ONLINE (should never get here)";
             log.Warn(my_log_event.ToString());
             Session["theme"] = "ONLINE";
             this.Page.Theme = this.Page.Theme = Session["theme"].ToString();
         }
         else
         {
             // this changes the theme of the hedgeem table according to the theme selected by the user.
             this.Page.Theme = Session["theme"].ToString();
             if (this.Page.Theme == "") ;
             {
                 // xxxeh - need to throw error when string =""
                 this.Page.Theme = "ONLINE";
             }
         }
     }
     catch (Exception ex)
     {
         string my_error_popup = "alert('Error in Page PreInit - " + ex.Message.ToString() + "');";
         ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
         HedgeEmLogEvent my_log = new HedgeEmLogEvent();
         my_log.p_message = ex.Message;
         my_log.p_method_name = "Page Load";
         my_log.p_player_id = f_get_player_id();
         my_log.p_table_id = _table_id;
         log.Error(my_log.ToString());
     }
 }
    /// <summary>
    /// WARNING OF DUPLICACTE CODE - See btn_anon_casino_Click, btn_anon_online_Click, and btn_anon_retro_Click
    /// only difference is theme selected
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btn_anon_casino_Click(object sender, EventArgs e)
    {
        // Log that the user has clicked the 'Play now' button.
        HedgeEmLogEvent my_log_event = new HedgeEmLogEvent();
        my_log_event.p_method_name = System.Reflection.MethodBase.GetCurrentMethod().ToString();
        my_log_event.p_table_id = p_session_personal_table_id;
        my_log_event.p_server_id = p_session_server_id;
        my_log_event.p_message = String.Format("User [{0}] clicked 'Play Casino Anonymously", p_session_username);
        log.Info(my_log_event.ToString());

        try
        {
            f_play_anon(enum_theme.CASINO);
        }
        catch (Exception ex)
        {
            my_log_event.p_message = String.Format("Error user try to play Anonymously using CASINO Theme.  Reason [{0}]", ex.Message);
            log.Error(my_log_event.ToString());
            // Cant throw a exception here
            //throw new Exception(my_log_event.ToString());
            
        }
    }
    private void f_update_hedgeem_control_buttons_with_info_from_server()
    {
        log.Debug("f_update_hedgeem_control_buttons_with_info_from_server called");
        // Determine the new state of the game and display the appropriate buttons
        try
        {
            switch (_game_state)
            {
                case enum_game_state.STATUS_START:
                    //btnDealHole.Visible = true;
                    //btnDealFlop.Visible = false;
                    //btnDealTurn.Visible = false;
                    //btnDealRiver.Visible = false;
                    //btnNextGame.Visible = false;
                    f_clear_players_bets_lablels();
                    break;

                case enum_game_state.STATUS_HOLE:
                    //btnDealHole.Visible = false;
                    //btnDealFlop.Visible = true;
                    //btnDealTurn.Visible = false;
                    //btnDealRiver.Visible = false;
                    //btnNextGame.Visible = false;
                    break;

                case enum_game_state.STATUS_FLOP:
                    //btnDealHole.Visible = false;
                    //btnDealFlop.Visible = false;
                    //btnDealTurn.Visible = true;
                    //btnDealRiver.Visible = false;
                    //btnNextGame.Visible = false;
                    break;

                case enum_game_state.STATUS_TURN:
                    //btnDealHole.Visible = false;
                    //btnDealFlop.Visible = false;
                    //btnDealTurn.Visible = false;
                    //btnDealRiver.Visible = true;
                    //btnNextGame.Visible = false;
                    break;

                case enum_game_state.STATUS_RIVER:
                    //btnDealHole.Visible = false;
                    //btnDealFlop.Visible = false;
                    //btnDealTurn.Visible = false;
                    //btnDealRiver.Visible = false;
                    //btnNextGame.Visible = true;
                    hedgeem_control_winner_message my_winner_message = new hedgeem_control_winner_message();
                    my_winner_message.p_winner_message_str = f_calculate_winnings();
                    if (my_winner_message.p_winner_message_str != "")
                    {
                        Place_Holder_Winner_Message.Controls.Add(my_winner_message);
                    }
                    break;

                default:
                    //btnDealHole.Visible = false;
                    //btnDealFlop.Visible = false;
                    //btnDealTurn.Visible = false;
                    //btnDealRiver.Visible = false;
                    //btnNextGame.Visible = true;
                    break;
            }



        }
        catch (Exception ex)
        {
            string my_error_popup = "alert('Error in f_update_hedgeem_control_buttons_with_info_from_server" + ex.Message.ToString() + "');";
            ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
            HedgeEmLogEvent my_log = new HedgeEmLogEvent();
            my_log.p_message = "Exception caught in f_update_hedgeem_control_buttons_with_info_from_server function " + ex.Message;
            my_log.p_method_name = "f_update_hedgeem_control_buttons_with_info_from_server";
            my_log.p_player_id = f_get_player_id();
            my_log.p_game_id = game_id;
            my_log.p_table_id = _table_id;
            log.Error(my_log.ToString());
        }

    }
    public static string f_facebook_login_called_from_javascript()
    {
        log.Warn("WANRING - COPIED NOT USED f_check_user_role called to check the role of the user.");
        string role = "Herman";
        string email = HttpContext.Current.Request.QueryString["uid"].ToString();

        hedgeem_control_popup_message my_popup_message = new hedgeem_control_popup_message();
        my_popup_message.p_detailed_message_str = "";

        HedgeEmLogEvent my_log_event = new HedgeEmLogEvent();
        my_log_event.p_method_name = System.Reflection.MethodBase.GetCurrentMethod().ToString();
        // Log the fact this method has been called
        my_log_event.p_message = String.Format("Method [btn_login_Click] called ");
        log.Debug(my_log_event.ToString());

        my_log_event.p_method_name = System.Reflection.MethodBase.GetCurrentMethod().ToString();
        my_log_event.p_message = "This message creates new fb user in database";
        string my_endpoint = "Not Set";
        try
        {
            int xxxHC_a_opening_balance = 25;
            string xxx_default_password = "******";
            try
            {

                // Creates (registers) a new user (HedgeEmPlayer) in the HedgeEm Server.
                // Note this also creates a Personal Table for them (which the HedgeEmTable is returned in the Player object 'p_personal_table_id
                enum_authentication_method my_authentication_method = enum_authentication_method.FACEBOOK;
                my_endpoint = String.Format("{0}/ws_register_user_and_create_personal_table/{1},{2},{3},{4},{5}/",
                                                p_current_json_webservice_url_base,
                                                email,
                                                xxx_default_password,
                                                email,
                                                xxxHC_a_opening_balance,
                                                my_authentication_method);

                HedgeEmPlayer my_player = (HedgeEmPlayer)f_get_object_from_json_call_to_server(my_endpoint, typeof(HedgeEmPlayer));
                if (my_player.p_error_message != null)
                {
                    if (my_player.p_error_message != "")
                    {
                        throw new Exception(my_player.p_error_message);
                    }
                }



                //Page.RegisterStartupScript("OnLoad", "<script>alert('Thank you for registering, you are now logged in an can start to play HedgeEm'); if(alert){ window.location='frm_facebook_canvas.aspx';}</script>");
            }
            /*
        catch (System.Net.WebException webex)
        {
            HttpWebResponse my_error_response = webex.Response as HttpWebResponse;
            switch (my_error_response.StatusCode)
            {
                case HttpStatusCode.BadRequest:
                    my_log_event.p_message = String.Format(
                       "Error (Web Exception: BadRequest). Endpoint URI probably badly formed ...\nEndpoint [{0}], Status Code [{1}]",
                              my_endpoint,
                               my_error_response.StatusCode
                              );
                    break;

                case HttpStatusCode.NotFound:
                    my_log_event.p_message = String.Format(
                       "Error (Web Exception: NotFound). Endpoint URI not found; Endpoint [{0}], Status Code [{1}]",
                              my_endpoint,
                               my_error_response.StatusCode
                              );
                    break;

                default: my_log_event.p_message = String.Format(
                       "Error unexpected status code (Web Exception of type Status Code [{0}] for Endpoint [{1}], ",
                              my_error_response.StatusCode,
                              my_endpoint
                              );
                    break;
            }
            throw new WebException(my_log_event.ToString(), webex);

        }*/
            catch (Exception ex)
            {
                string my_error_message = "Error while btn_new_fb_user_Click" + ex.Message;
                string my_error_popup = "alert('Error in btn_new_fb_user_Click - " + ex.Message.ToString() + "');";
                log.Error(my_error_message);
           throw new Exception(my_error_message);
               // System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>" + my_error_popup + "</SCRIPT>");
            }
        }
        catch (Exception ex)
        {
            string my_error_message = "Error while btn_new_fb_user_Click" + ex.Message;
            string my_error_popup = "alert('Error in creating user - " + ex.Message.ToString() + "');";
            log.Error(my_error_message);
         throw new Exception(my_error_message);
            //System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>" + my_error_popup + "</SCRIPT>");
        }


        // Detemine if there is a session varible set for facebook. 
        // xxx Nov 2014 Note ... Not sure why - I assmume this is to check
        // if the user has already authenticated via facebook so we can make choices about what to display
        //if (Session["chkfb"] != null)
        //{
        //   chk_fb_visibility.Visible = true;
        //    log.Debug(String.Format("Session variable 'chkfb' is {0}", Session["chkfb"].ToString()));
        //}
        //else
        // {
        //  chk_fb_visibility.Visible = false;
        //  chk_fb_visibility.Visible = false;
        //}

        // Declare vairibles that will be required later
        string my_username = email;
        string my_password = "";
        DataTable my_user_details;

        try
        {
            string xxxHC_password = "******";

            // Attempt to retrieve a Player object from the HedgeEm Webservice using the credentials supplied.
            my_endpoint = String.Format("{0}/ws_login/{1},{2},{3},{4}/", p_current_json_webservice_url_base, p_session_id, p_server_id, my_username, xxxHC_password);

            // Might need to make next method static
            HedgeEmPlayer my_player = null;
            my_player = (HedgeEmPlayer)f_get_object_from_json_call_to_server(my_endpoint, typeof(HedgeEmPlayer));
            if (my_player == null)
            {
                string my_error_msg = String.Format("Player object is null after call to Webservice to retrieve details", my_username);
                my_log_event.p_message = my_error_msg;
                log.Error(my_log_event.ToString());
                throw new Exception(my_error_msg);
            }

            if (my_player.p_player_id <= 0)
            {
                my_log_event.p_message = my_player.p_error_message;
                log.Warn(my_log_event.ToString());
                //throw new Exception(my_log_event.ToString());

            }
            else
            {
                // If we have got here the user has logged into the server sucessfully so we should set some session variables for ease of use later
                int my_player_id = my_player.p_player_id;
                HttpContext.Current.Session["p_session_player_id"] = my_player_id;
                HttpContext.Current.Session["display_name"] = my_player.p_display_name;
                HttpContext.Current.Session["p_session_username"] = my_username;
                HttpContext.Current.Session["password"] = my_password;
                HttpContext.Current.Session["p_session_personal_table_id"] = my_player.p_personal_table_id;

                string my_info_msg = String.Format("Session vars set: p_session_player_id[{0}], display_name[{1}], p_session_username[{2}], password[{3}], p_session_personal_table_id[{4}], ",
                                    HttpContext.Current.Session["p_session_player_id"],
                                    HttpContext.Current.Session["display_name"],
                                    HttpContext.Current.Session["p_session_username"],
                                    HttpContext.Current.Session["password"],
                                    HttpContext.Current.Session["p_session_personal_table_id"]);

                my_log_event.p_message = my_info_msg;
                log.Info(my_log_event.ToString());


                // As the user has now logged in by HedgeEm authentication hide the Facebook login DIV
                if (HttpContext.Current.Session["facebooklogin"] != null)
                {
                    //LoginDiv.Attributes.Add("style", "display:none !Important;");
                }

                // As the user has now logged show the logout button and hide the login button
                // xxx Nov 2014.  Not sure why this is on condition of facebooklogin; I separated this out from if/else
                // of above to figure this out.  I assume is because you could be logged in by facebook so still want to
                // show / hide login/logout buttons appropriately
                if (HttpContext.Current.Session["facebooklogin"] == null)
                {
                    //lbl_user_name.Text = HttpContext.Current.Session["display_name"].ToString();
                    //Logout.Attributes.Add("style", "display:block !Important;");
                    //LoginDiv.Attributes.Add("style", "display:none !Important;");
                }

                // As the user has now logged in Enable the 'Play Now' button
                //btn_play_now.Enabled = true;



                // If the 'fb_hide_logout' is set it implies xxxxxxxxxxxxxxxxxxxxx so enable the 'Play Now' button
                if (HttpContext.Current.Session["fb_hide_logout"] != null)
                {
                    //    chk_fb_visibility_logout.Visible = false;
                    //btn_play_now.Visible = true;

                }

                // If the 'chk_logout_hide' is set it implies xxxxxxxxxxxxxxxxxxxxx so enable the 'Play Now' button
                if (HttpContext.Current.Session["chk_logout_hide"] != null)
                {

                    //   chk_fb_visibility.Visible = true;
                    //btn_play_now.Visible = true;
                    //btnLogout.Visible = false;
                }
                //Page.RegisterStartupScript("OnLoading", "<script>load_edit_profile();</script>");
                // Response.Redirect("frm_facebook_canvas.aspx");
                //Page.RegisterStartupScript("OnLoad", "<script>document.getElementById('progressbar').style.display='none';</script>");
            }
            return role;
        }
        catch (Exception ex)
        {
            string my_error_message = "Fatal Errorin method [btn_login_Click] - " + ex.Message.ToString() + "');";

            //  Log the error and raise a new exception
            my_log_event.p_message = String.Format(
                "Fatal error in method [btn_login_Click]. Reason [{0}]",
                        ex.Message);
            log.Error(my_log_event.ToString(), new Exception(ex.Message));
            throw ex;
            //Place_Holder_Popup_Message.Controls.Add(my_popup_message);
        }
       
    }
    protected void btn_play_for_real_deposit_pledge_Click(object sender, EventArgs e)
    {
        HedgeEmLogEvent _xxx_log_event = new HedgeEmLogEvent();
        _xxx_log_event.p_method_name = "btn_play_for_real_deposit_pledge_Click";
        log.Info("[" + Session["username"].ToString() + "] clicked on Play for Real Deposit Pledge");
        try
        {
            // This will save the value of pledge amount in the database.
            play_for_real_deposit_pledge _play_for_real_deposit_pledge = new play_for_real_deposit_pledge
            {
                p_playerid = f_get_player_id(),
                p_play_for_real_amount = Convert.ToDouble(txt_play_for_real_deposit_pledge.Text)
            };

            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(play_for_real_deposit_pledge));
            MemoryStream mem = new MemoryStream();
            ser.WriteObject(mem, _play_for_real_deposit_pledge);
            string data =
                Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
            WebClient webClient = new WebClient();
            webClient.Headers["Content-type"] = "application/json";
            webClient.Encoding = Encoding.UTF8;
            webClient.UploadString("http://devserver.hedgeem.com/Service1.svc/f_set_play_for_real_deposit_pledge", data);
            webClient.UploadString("http://localhost:59225/Service1.svc/f_set_play_for_real_deposit_pledge", data);
            // Empties the value of textbox
            txt_play_for_real_deposit_pledge.Text = "";
            _global_game_state_object = (DC_hedgeem_game_state)f_get_object_from_json_call_to_server("get_game_state_object/" + _table_id, typeof(DC_hedgeem_game_state));
            game_id = _global_game_state_object.p_game_id;
            int my_number_of_hands = _global_game_state_object.p_number_of_hands_int;
            enum_betting_stage my_betting_stage = f_get_current_betting_stage();
            _game_state = _global_game_state_object.p_current_state_enum;
            _hedgeem_hand_panels = new hedgeem_hand_panel[my_number_of_hands];
            _int_number_of_betting_stages = _global_game_state_object.p_number_of_betting_stages_int;
            _hedgeem_betting_panels = new BETTING_PANEL[_int_number_of_betting_stages, my_number_of_hands];
            f_update_game_id();
            // Method which calls the functions to render the screen.
            f_call_functions_to_render_screen();
        }
        catch (Exception ex)
        {
            string my_error_popup = "alert('Error in btn_play_for_real_deposit_pledge_Click - " + ex.Message.ToString() + "');";
            ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
            HedgeEmLogEvent my_log = new HedgeEmLogEvent();
            my_log.p_message = "Exception caught in btn_play_for_real_deposit_pledge_Click function " + ex.Message;
            my_log.p_method_name = "btn_play_for_real_deposit_pledge_Click";
            my_log.p_player_id = f_get_player_id();
            my_log.p_game_id = game_id;
            my_log.p_table_id = _table_id;
            log.Error(my_log.ToString());
        }
    }