/// <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;

    }
    //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());
        }
    }
    // 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());
        }
    }
    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());
        }
    }
    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 btn_play_for_real_Click(object sender, EventArgs e)
    {
        // Create a 'log event' object to audit execution
        HedgeEmLogEvent my_log_event = new HedgeEmLogEvent();
        my_log_event.p_method_name = System.Reflection.MethodBase.GetCurrentMethod().ToString();
        log.Info("[" + Session["p_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/" + Convert.ToInt32(Session["p_session_player_id"]), null));

            // This will increment the value of count.
            play_for_real _play_for_real = new play_for_real
            {
                p_playerid = Convert.ToInt32(Session["p_session_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;

            string my_service_url = WebConfigurationManager.AppSettings["hedgeem_server_default_webservice_url"];
            webClient.UploadString(my_service_url + "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/" + p_session_personal_table_id, typeof(DC_hedgeem_game_state));
            game_id = _global_game_state_object.p_game_id;
            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[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, 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 = "Error in btn_play_for_real_Click - " + ex.Message.ToString();
            //ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
            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_popup;
            my_popup_message.p_is_visible = true;
            Place_Holder_Popup_Message.Controls.Add(my_popup_message);
            my_log_event.p_message = "Exception caught in btn_play_for_real_Click function " + ex.Message;
            my_log_event.p_method_name = "btn_play_for_real_Click";
            my_log_event.p_player_id = Convert.ToInt32(Session["p_session_player_id"]);
            my_log_event.p_game_id = game_id;
            my_log_event.p_table_id = p_session_personal_table_id;
            log.Error(my_log_event.ToString());
        }
    }
 protected void Timer1_Tick(object sender, EventArgs e)
 {
     _global_game_state_object = (DC_hedgeem_game_state)f_get_object_from_json_call_to_server("get_game_state_object/1000", 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();
     //img_countdown.Visible = false;
     // btn_deal_next_stage_Click();
     //img_countdown.Visible = true;
     //ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", "LoadTimer();", true);
     // ScriptManager.RegisterStartupScript(this, GetType(), "myFunction", "LoadTimer();", true);
 }
    public string[] f_update_hedgeem_control_hand_panels()
    {

        // Create a 'log event' object to audit execution
        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_player_id = p_session_player_id;
        //my_log_event.p_table_id = p_session_personal_table_id;
        log.Debug(my_log_event.ToString());


        log.Debug("f_update_hedgeem_control_hand_panels_with_info_from_server called");
        List<string> details = new List<string>();
        DC_hedgeem_game_state _global_game_state_object = new DC_hedgeem_game_state();
        int p_session_personal_table_id = 2058;



        object obj = null;
        HttpWebRequest request;
        String my_service_url = "not set";
        my_service_url = WebConfigurationManager.AppSettings["hedgeem_server_default_webservice_url"];

        request = WebRequest.Create(my_service_url + "get_game_state_object/2058") 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);
                                throw new Exception(my_error_msg);
                            }
                            var ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
                            if (typeof(DC_hedgeem_game_state) != null)
                            {
                                var ser = new DataContractJsonSerializer(typeof(DC_hedgeem_game_state));
                                obj = ser.ReadObject(ms);
                            }
                            else
                            {
                                obj = json;
                            }
                        }

                        finally
                        {
                            reader.Close();
                        }
                    }
                }
            }


        _global_game_state_object = (DC_hedgeem_game_state)obj;



        int my_number_of_seats = _global_game_state_object.p_number_of_seats_int;
        try
        {
            string p_hand_card1 = "ZZ";
            string p_hand_card2 = "ZZ";
            //ArrayList list = new ArrayList();
            //int number_of_hands = _global_game_state_object.p_number_of_hands_int;
            int number_of_hands = 4;
            for (int hand_index = 0; hand_index < number_of_hands; hand_index++)
            {
                // call to get HedgeEmHandStageInfo for given hand index at given stage
                //  HedgeEmHandStageInfo my_hedgeem_hand_stage_info = f_get_hand_stage_info_object_for_stage_and_hand(_global_game_state_object.p_current_state_enum, hand_index);

                if (_global_game_state_object._hands.Count() == 0)
                {
                    p_hand_card1 = "ZZ";
                    p_hand_card2 = "ZZ";
                }

                else
                {
                    p_hand_card1 = _global_game_state_object._hands[hand_index].Substring(0, 2);

                    p_hand_card2 = _global_game_state_object._hands[hand_index].Substring(2, 2);
                }
                // Create a new HedgeEm Control that will be used to display the status of one Hand in the Web page.
                int _int_number_of_betting_stages = _global_game_state_object.p_number_of_betting_stages_int;
                int my_num_stages = _int_number_of_betting_stages;
                hedgeem_hand_panel[] _hedgeem_hand_panels;

                _hedgeem_hand_panels = new hedgeem_hand_panel[number_of_hands];

                _hedgeem_hand_panels[hand_index] = new hedgeem_hand_panel(my_num_stages, my_number_of_seats);
                //// Hand_Index
                _hedgeem_hand_panels[hand_index].p_hand_index = hand_index;

                // Card 1
                _hedgeem_hand_panels[hand_index].p_card1 = p_hand_card1;

                // Card 2 
                _hedgeem_hand_panels[hand_index].p_card2 = p_hand_card2;

                string st = _hedgeem_hand_panels[hand_index].p_card_image_filename_card1;
                string st1 = _hedgeem_hand_panels[hand_index].p_card_image_filename_card2;

                //string st = p_hand_card1;
                //string st1 = p_hand_card2;

                details.Add(st);
                details.Add(st1);

                //list.Add(st);
                //list.Add(st1);

                // Add the created control to the Webpage (HedgeEmTable.aspx) for display to the user.
                //_hedgeem_hand_panels[hand_index].ID = "auto_div_hand_id" + hand_index;
                //_hedgeem_hand_panels[hand_index].CssClass = "auto_div_hand_id_class";
                // Place_Holder_Hand_Panel.Controls.Add(_hedgeem_hand_panels[hand_index]);

            }

        }


        catch (Exception ex)
        {
            string my_error_popup = "alert('Error in f_update_hedgeem_control_hand_panels_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_hand_panels_with_info_from_server function " + ex.Message;
            my_log.p_method_name = "f_update_hedgeem_control_hand_panels_with_info_from_server";
            // my_log.p_player_id = Convert.ToInt32(Session["p_session_player_id"]);
            // my_log.p_game_id = game_id;
            //       my_log.p_table_id = p_session_personal_table_id;
            log.Error(my_log.ToString());
            // xxxeh - this error does not pop up
            throw new Exception(my_error_popup);

        }
        // JavaScriptSerializer TheSerializer = new JavaScriptSerializer();
        // var TheJson = TheSerializer.Serialize(details);
        return details.ToArray();
    }
    // This function is used to get value of clicked hand
    protected void btn_Get_Clicked_Hand_Value_Click(object sender, EventArgs e)
    {
        try
        {
            log.Debug("f_place_bet is called in btn_Get_Clicked_Hand_Value_Click ");
            // calls place bet function
            f_place_bet();
            log.Debug("f_call_function_to_render_screen is called in btn_Get_Clicked_Hand_Value_Click");

            _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];
            Session["sess_betting_stage_enum"] = _global_game_state_object.p_current_betting_stage_enum;
            _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_message = String.Format("Error in f_update_hedgeem_control_hand_panels_with_info_from_server_previous_bets. Reason {0}", ex.Message);

            string my_error_popup = "alert('Error in btn_Get_Clicked_Hand_Value_Click" + ex.Message.ToString() + "');";
            // xxxeh popup does not show
            ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
            HedgeEmLogEvent my_log = new HedgeEmLogEvent();
            my_log.p_message = "Exception caught in btn_Get_Clicked_Hand_Value_Click function " + ex.Message;
            my_log.p_method_name = "btn_Get_Clicked_Hand_Value_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(my_error_popup);
        }
    }
    // 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)
    {
        // Create a 'log event' object to audit execution
        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_player_id = p_session_player_id;
        my_log_event.p_table_id = p_session_personal_table_id;
        log.Debug(my_log_event.ToString());

        try
        {
            my_log_event.p_message = "Method called ";
            my_log_event.p_method_name = "btn_get_chips_add_Click";
            my_log_event.p_player_id = Convert.ToInt32(Session["p_session_player_id"]);
            my_log_event.p_game_id = game_id;
            my_log_event.p_table_id = p_session_personal_table_id;
            log.Debug(my_log_event.ToString());
            log.Info("[" + Session["p_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 = Convert.ToInt32(Session["p_session_player_id"]),
                p_tableid = p_session_personal_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,
                                                        p_session_personal_table_id,
                                                        xxx_HC_seat_id,
                                                        my_get_chips_top_up_amount,
                                                        Convert.ToInt32(Session["p_session_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["p_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/" + p_session_personal_table_id, typeof(DC_hedgeem_game_state));
            game_id = _global_game_state_object.p_game_id;
            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[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, 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();
            updPanl_to_avoid_Postback.Update();
            ScriptManager.RegisterStartupScript(Page, GetType(), "", "alert('Congratulations £" + my_get_chips_top_up_amount + " have been added to your seat amount........!');", true);
        }
        catch (Exception ex)
        {
            // xxxeh this exeception does not show to users
            string my_error_popup = "Error in btn_get_chips_add_Click - " + ex.Message.ToString();
           //ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
            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_popup;
            my_popup_message.p_is_visible = true;
            Place_Holder_Popup_Message.Controls.Add(my_popup_message);
            my_log_event.p_message = String.Format("Exception caught in btn_get_chips_add_Click function. Reason [{0}] ", ex.Message);
            my_log_event.p_method_name = "btn_get_chips_add_Click";
            my_log_event.p_player_id = Convert.ToInt32(Session["p_session_player_id"]);
            my_log_event.p_game_id = game_id;
            my_log_event.p_table_id = p_session_personal_table_id;
            log.Error(my_log_event.ToString());
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        var type = Request.RequestType;

        // If we dont have a player ID we need to redirect the user back to the home screen where they can login or play anonymously to get a PlayerID.
        if (Session["p_session_player_id"] == null) 
        {
            string my_webapp_home_page = WebConfigurationManager.AppSettings["hedgeem_webapp_landing_page"].ToString();
            Response.Redirect(my_webapp_home_page);
        }
        else
        {
            HedgeEmLogEvent my_log = new HedgeEmLogEvent();
            my_log.p_message = "frm_hedgeem_table.aspx.cs method called.";
            my_log.p_method_name = "Page_Load";
            my_log.p_player_id = Convert.ToInt32(Session["p_session_player_id"]);
            my_log.p_game_id = game_id;
            my_log.p_table_id = p_session_personal_table_id;
            log.Debug(my_log.ToString());
            try
            {
                // checks if session is timed out
                if (Session.Count == 0)
                {
                    Page.RegisterStartupScript("Alert Message", "<script type='text/javascript'>show_session_timeout_message();</script>");
                }
                else
                {
                    int my_player_id = Convert.ToInt32(Session["p_session_player_id"]);
                    p_session_personal_table_id = Convert.ToInt32(Session["p_session_personal_table_id"]);

                    //f_preload_images();

                    bool ispostback = Page.IsAsync;

                    if (Page.IsPostBack == false)
                    {
                        try
                        {

                            _global_game_state_object = (DC_hedgeem_game_state)f_get_object_from_json_call_to_server("get_game_state_object/" + p_session_personal_table_id, typeof(DC_hedgeem_game_state));
                            if (_global_game_state_object.p_error_message != null)
                            {
                                if (_global_game_state_object.p_error_message != "")
                                {
                                    throw new Exception(_global_game_state_object.p_error_message);
                                }
                            }

                            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());
                        }
                        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());
                            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 = String.Format("Error trying to get game state from server. Reason [{0}]", ex.Message);
                            my_popup_message.p_is_visible = true;
                            Place_Holder_Popup_Message.Controls.Add(my_popup_message);

                        }
                        int dummy_var_for_break_point = 22;
                        if (Session["user_role"] == null)
                        {
                            Session["user_role"] = enum_user_role.BASIC_USER.ToString();
                        }
                        string role = Session["user_role"].ToString();
                        // if user is admin, show cashier button
                        if (role == enum_user_role.ADMIN.ToString())
                        {
                            btn_cashier.Visible = true;
                        }
                        //if (is_table_jackpot_enabled == true)
                        //{
                        //    table_jackpot_container.Visible = true;
                        //}
                        else
                        {
                            table_jackpot_container.Visible = false;
                        }
                        ScriptManager sManager = ScriptManager.GetCurrent(this.Page);
                        //Get Image from Facebook if the user is logged in via facebook
                        string facebook_imageurl = "";
                        if (Session["Facebook_User_Id"] != null)
                        {
                            if (Session["Facebook_User_Id"] != "")
                            {
                                //Get Image from Facebook
                                facebook_imageurl = "https://graph.facebook.com/" + Session["Facebook_User_Id"].ToString() + "/picture";
                            }
                            if (facebook_imageurl != "")
                            {
                                // Get path to save the image
                                string pathToSave = Server.MapPath("~/resources/") + "player_avatar_" + Session["p_session_username"].ToString() + ".jpg";
                                //Check if the Image exists already
                                if (!File.Exists(pathToSave))
                                {
                                    //Save the image
                                    WebClient client = new WebClient();
                                    //client.DownloadFile(facebook_imageurl, pathToSave);
                                }
                            }
                        }
                        chk_admin_flag_value = 1;
                        Session["Check_AltA"] = 1;


                        if (Session["Check_AltA"] == null)
                        {
                            btn_Show_Admin_Flag.Visible = true;
                            btn_Hide_Admin_Flag.Visible = false;
                        }
                        else if (Convert.ToInt32(Session["Check_AltA"]) == 0)
                        {
                            btn_Show_Admin_Flag.Visible = false;
                            btn_Hide_Admin_Flag.Visible = true;
                        }

                        game_id = _global_game_state_object.p_game_id;
                        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[number_of_hands];
                        Session["sess_betting_stage_enum"] = _global_game_state_object.p_current_betting_stage_enum;
                        _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, number_of_hands];
                        lbl_game_id.Text = String.Format("Table/Game: {0}/{1} ", _global_game_state_object.p_table_id, game_id);
                        // gets seat balance of the current player
                        player_funds_at_seat = _global_game_state_object._seats[0].p_player_seat_balance;

                        f_call_functions_to_render_screen();
                    }
                    // Dynamically contructed the Web page title so show relevant info about Server, Table and Game the player is playing. 
                    //   String my_page_title = String.Format("Texas Hedge'Em Poker | Server [{0}], Table {1}], Game [{2}]","server id", p_table_name, p_table_id);
                    //   this.Page.Title = my_page_title;

                    /*Click on Hand_Panel to get the value of current hand via _click_hand_index  and then that value pass to hidden textbox i.e mytext, when Hand_Index_Value is shown in textbox then btn_Get_Clicked_Hand_Value method to get the value of bet that we placed i.e HOLE: £1 bet pays £4*/
                   // Page.RegisterStartupScript("Bet_Placed_Details", "<script>f_placebet(_click_hand_index);</script>");
                }
            }
            

            catch (Exception ex)
            {
                //string my_error_popup = "alert('Error in Page Load - " + ex.Message.ToString() + "');";
                string my_error_popup = String.Format("Fatal Error in frm_hedgeem_table.aspx.cs Page Load. Reason [{0}]", ex.Message);
                my_log.p_message = String.Format("Fatal Error in frm_hedgeem_table.aspx.cs Page Load. Reason [{0}]", ex.Message);
                // xxxeh This exception does not show to users
                //ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
                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_popup;
                my_popup_message.p_is_visible = true;
                Place_Holder_Popup_Message.Controls.Add(my_popup_message);
                log.Error(my_log.ToString());
                //throw new Exception(my_error_popup); 
         
            }
        }
        
    }
    /// <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>
    protected void btn_deal_next_stage_Click(object sender, EventArgs e)
    {
        // Create a 'log event' object to audit execution
        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_player_id = p_session_player_id;
        my_log_event.p_table_id = p_session_personal_table_id;
        log.Debug(my_log_event.ToString());

        string my_username = Session["p_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 = " + Convert.ToInt32(Session["p_session_player_id"]));
                ScriptManager.RegisterStartupScript(Page, GetType(), "SessionTimeOutMsg", "show_session_timeout_message();", true);
            }
            else
            {
               


                // 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/" + p_session_personal_table_id + "," + Convert.ToInt32(Session["p_session_player_id"]), typeof(DC_hedgeem_game_state));
                string stage = _global_game_state_object.p_current_state_enum.ToString();
                
                game_id = _global_game_state_object.p_game_id;
                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[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, 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();
             

                //Script For Animation of cards
                if (stage == "STATUS_HOLE")
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "animate_Hand", "animate_Hand();", true);
                }
                if (stage == "STATUS_FLOP")
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "animate_card_flop", "animate_card_flop();", true);
                }
                if (stage == "STATUS_TURN")
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "animate_card_middle_turn", "animate_card_middle_turn();", true);
                }
                if (stage == "STATUS_RIVER")
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "animate_card_middle_river", "animate_card_middle_river();", true);
                }
                if (stage == "STATUS_START")
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "animate_card_next_game", "animate_card_next_game();", true);
                }            

            }
        }
        catch (Exception ex)
        {
            string my_error_popup = "Error in btn_deal_next_stage_Click - " + ex.Message.ToString();
           // ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", "alert ('plokerror')", true);
            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_popup;
            my_popup_message.p_is_visible = true;
            Place_Holder_Popup_Message.Controls.Add(my_popup_message);
            my_log_event.p_message = String.Format("Exception caught in btn_deal_next_stage_Click function. Reason [{0}] ", ex.Message);
            my_log_event.p_method_name = "btn_deal_next_stage_Click";
            my_log_event.p_player_id = Convert.ToInt32(Session["p_session_player_id"]);
            my_log_event.p_game_id = game_id;
            my_log_event.p_table_id = p_session_personal_table_id;
            log.Error(my_log_event.ToString());
            //throw new Exception("xxx This exception is not being caught");
        }
    }
    /// <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()
    {
        // Create a 'log event' object to audit execution
        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_player_id = p_session_player_id;
        my_log_event.p_table_id = p_session_personal_table_id;
        log.Debug(my_log_event.ToString());

        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/" + p_session_personal_table_id, typeof(DC_hedgeem_game_state));
                my_log_event.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_event.ToString());
                my_enum_betting_stage = _global_game_state_object.p_current_betting_stage_enum;
            }
            catch (Exception ex)
            {
                my_log_event.p_message = String.Format("Error trying to get game state from server. Reason [{0}]", ex.Message);
                log.Error(my_log_event.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)
    {
        // Create a 'log event' object to audit execution
        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_player_id = p_session_player_id;
        my_log_event.p_table_id = p_session_personal_table_id;
        log.Debug(my_log_event.ToString());

        log.Info("[" + Session["p_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/" + p_session_personal_table_id.ToString() + "," + Convert.ToInt32(Session["p_session_player_id"]) + "," + 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/" + p_session_personal_table_id, typeof(DC_hedgeem_game_state));
            game_id = _global_game_state_object.p_game_id;
            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[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, 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 = "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);
            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_popup;
            my_popup_message.p_is_visible = true;
            Place_Holder_Popup_Message.Controls.Add(my_popup_message);
            my_log_event.p_message = "Exception caught in f_cancel_bets_for_this_hand_and_stage function " + ex.Message;
            my_log_event.p_method_name = "f_cancel_bets_for_this_hand_and_stage";
            my_log_event.p_player_id = Convert.ToInt32(Session["p_session_player_id"]);
            my_log_event.p_game_id = game_id;
            my_log_event.p_table_id = p_session_personal_table_id;
            log.Error(my_log_event.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='>");
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        HedgeEmLogEvent my_log = new HedgeEmLogEvent();
        my_log.p_message = "frm_home_page.aspx.cs method called.";
        my_log.p_method_name = "Page_Load";
        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());
        try
        {
            // checks if session is timed out
            if (Session.Count == 0)
            {
                Page.RegisterStartupScript("Alert Message", "<script type='text/javascript'>show_session_timeout_message();</script>");
            }
            else
            {
                my_log.p_message = "Warning: Hardcoding of table ID";
                log.Warn(my_log.ToString());
                int xxx_HC_table_id_for_shared_home_page_table = 1000;
                int my_player_id = Convert.ToInt32(Session["playerid"]);
                _table_id = xxx_HC_table_id_for_shared_home_page_table;

                if (Page.IsPostBack == false)
                {
                    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));
                        // _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));
                        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());
                    }
                    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());

                    }
                    if (Session["user_role"] != null)
                    {
                        string role = Session["user_role"].ToString();
                        // if user is admin, show cashier button
                        if (role == enum_user_role.ADMIN.ToString())
                        {
                            btn_cashier.Visible = true;
                        }
                    }

                    table_jackpot_container.Visible = false;

                    ScriptManager sManager = ScriptManager.GetCurrent(this.Page);

                    /*
                    //Get Image from Facebook if the user is logged in via facebook
                    string facebook_imageurl = "";
                    if (Session["Facebook_User_Id"] != "")
                    {
                        //Get Image from Facebook
                        facebook_imageurl = "https://graph.facebook.com/" + Session["Facebook_User_Id"].ToString() + "/picture";
                    }
                    if (facebook_imageurl != "")
                    {
                        // Get path to save the image
                        string pathToSave = Server.MapPath("~/resources/") + "player_avatar_" + Session["username"].ToString() + ".jpg";
                        //Check if the Image exists already
                        if (!File.Exists(pathToSave))
                        {
                            //Save the image
                            WebClient client = new WebClient();
                            client.DownloadFile(facebook_imageurl, pathToSave);
                        }
                    }
                    */

                    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];
                    //   Session["sess_betting_stage_enum"] = _global_game_state_object.p_current_betting_stage_enum;
                    _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);
                    // gets seat balance of the current player
                    player_funds_at_seat = _global_game_state_object._seats[0].p_player_seat_balance;

                    f_call_functions_to_render_screen();
                }
                // Dynamically contructed the Web page title so show relevant info about Server, Table and Game the player is playing. 
                //   String my_page_title = String.Format("Texas Hedge'Em Poker | Server [{0}], Table {1}], Game [{2}]","server id", p_table_name, p_table_id);
                //   this.Page.Title = my_page_title;
                //  Page.RegisterStartupScript("call deal button code", "<script>setInterval('" + btn_deal_next_stage_Click() + "',3000);</script>");
                //   btn_deal_next_stage_Click();
                /*Click on Hand_Panel to get the value of current hand via _click_hand_index  and then that value pass to hidden textbox i.e mytext, when Hand_Index_Value is shown in textbox then btn_Get_Clicked_Hand_Value method to get the value of bet that we placed i.e HOLE: £1 bet pays £4*/
                Page.RegisterStartupScript("Bet_Placed_Details", "<script>f_placebet(_click_hand_index);</script>");

                if (Session["username"] != null)
                {

                    Logout.Attributes.Add("style", "display:block!Important;");
                    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;");
                    usr_image.ImageUrl = "../resources/player_avatar_" + Session["username"].ToString() + ".jpg";
                    btn_play_now.Enabled = true;
                    // check user role
                    DataTable dt = service.f_get_password_from_db(Session["username"].ToString());

                    string role = "";
                    if (dt.Rows.Count > 0)
                    {
                        string password = dt.Rows[0]["password"].ToString();
                        DataTable userdetails = service.my_user_details(Session["username"].ToString(), password);
                        role = userdetails.Rows[0]["role"].ToString();

                    }
                    if (role == enum_user_role.ADMIN.ToString())
                    {
                        btnAdmin.Visible = true;
                    }
                    Session["user_role"] = role;
                    Page.RegisterStartupScript("OnLoad", "<script>document.getElementById('progressbar').style.display='none';</script>");
                }
            }
        }
        //catch (FaultException<Exception_Fault_Contract> ex)
        //{

        //}

        catch (Exception ex)
        {
            //string my_error_popup = "alert('Error in Page Load - " + ex.Message.ToString() + "');";
            string my_error_popup = "Major Error in Page_load";
            ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
            log.Error(my_log.ToString());
            //throw new Exception(my_error_popup); 
        }
    }
    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;
        
    }
    // This function is used to get value of clicked hand
    protected void btn_Get_Clicked_Hand_Value_Click(object sender, EventArgs e)
    {
        // Create a 'log event' object to audit execution
        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_player_id = p_session_player_id;
        my_log_event.p_table_id = p_session_personal_table_id;
        log.Debug(my_log_event.ToString());
        my_log_event.p_game_id = game_id;

        try
        {
            log.Debug("f_place_bet is called in btn_Get_Clicked_Hand_Value_Click ");
            // calls place bet function
            f_place_bet();
            log.Debug("f_call_function_to_render_screen is called in btn_Get_Clicked_Hand_Value_Click");

            _global_game_state_object = (DC_hedgeem_game_state)f_get_object_from_json_call_to_server("get_game_state_object/" + p_session_personal_table_id, typeof(DC_hedgeem_game_state));
            game_id = _global_game_state_object.p_game_id;
            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[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, 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_message = String.Format("Error in f_update_hedgeem_control_hand_panels_with_info_from_server_previous_bets. Reason {0}", ex.Message);

            string my_error_popup = "Error in btn_Get_Clicked_Hand_Value_Click" + ex.Message.ToString();
            // xxxeh popup does not show
           // ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
            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_popup;
            my_popup_message.p_is_visible = true;
            Place_Holder_Popup_Message.Controls.Add(my_popup_message);
            my_log_event.p_message = "Exception caught in btn_Get_Clicked_Hand_Value_Click function " + ex.Message;
            my_log_event.p_player_id = Convert.ToInt32(Session["p_session_player_id"]);
            my_log_event.p_game_id = game_id;
            my_log_event.p_table_id = p_session_personal_table_id;
            log.Error(my_log_event.ToString());
            //throw new Exception(my_error_popup);
        }
    }