/// <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='>");
    }
    //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());
        }
    }
    // 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);
        }
    }
 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);
 }
    /// <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)
    {
        // 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());

        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);
            }

            if (myHedgeEmHandStageInfoList.Count > 0)
            {
                myHedgeEmHandStageInfo = myHedgeEmHandStageInfoList[0];
            } else
            {
                my_log_event.p_message = String.Format("Unusual circumstance.  Did not find any 'HandStatusInfo' for GameState [{0}], Hand Index[{1}] ", a_enum_game_state.ToString(), a_hand_index);
                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.Warn(my_log_event.ToString());

            }

        }
        catch (Exception ex)
        {
            //  ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
            my_log_event.p_message = String.Format("Exception caught [{0}] ", 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());
            
            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_log_event.p_message;
            my_popup_message.p_is_visible = true;
            Place_Holder_Popup_Message.Controls.Add(my_popup_message);
        }
        return myHedgeEmHandStageInfo;
    }
    // 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");
        }
    }
    // 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());
        }
    }
    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());
        }
    }
    /// <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 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); 
        }
    }
 /// <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;
 }
    /// <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)
    {
        // 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());

        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)
        {
            //ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
            my_log_event.p_message = String.Format("Exception caught [{0}] ", 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());
            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_log_event.p_message;
            my_popup_message.p_is_visible = true;
            Place_Holder_Popup_Message.Controls.Add(my_popup_message);
        }
        return myHedgeEmHandStageInfo;
    }