using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Transactions;
using System.Text;
using System.Text.RegularExpressions;
public partial class Calltransfer : MyDataPage
{
    public DataTable dtProcess, dtProcessMaster, dtProcessLog, dtProcessLogTemp, dtProgressivedialing, dtProcessMasterUnique, dtAlternateFields;
    DataTable dtProcessMaster_Act = new DataTable();
    public DataTable dtSubDDLDetails = new DataTable();
    public DataTable dtMailDetail = new DataTable();
    public TextBox TextBox1; public ListBox ListBox1; public DropDownList DropDownList1; public CheckBox CheckBox1; public Label LabelSAN;
    public RadioButtonList RadioButtonList1; public Button Button1; HtmlGenericControl myFrame; int Log_Id;
    public HyperLink HyperLink1; public FileUpload FileUpload1;
    string orderBy = " ORDER BY No_Of_Attempts,SrNo ", sqlString;
    bool Enable_Dial = false;
    public bool bIsAutoSave = false;
    protected void Page_Init(object sender, EventArgs e)
    {
        dtProcess = FunctionClassObj.GetData("SELECT Auto_Save,Auto_Save_Time_Interval,Default_Disposition FROM Process WHERE Process.Pid = '" + FunctionClassObj.StringToInt(Convert.ToString(Session["pid"])) + "'");
        if (dtProcess.Rows.Count > 0)
        {
            bIsAutoSave = Convert.ToBoolean(dtProcess.Rows[0]["Auto_Save"]);
            AutoSaveTimeInterval.Value = Convert.ToString(FunctionClassObj.StringToInt(dtProcess.Rows[0]["Auto_Save_Time_Interval"].ToString()) * 1000);
        }
        else
            AutoSaveTimeInterval.Value = "0";
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        ShowError.Visible = false;
        ErrorMessage.Text = string.Empty;
        imgBtnSave.Enabled = imgBtnNext.Enabled = imgBtnSaveNext.Enabled = true;
        try
        {
            if (Session["Start_Time"] != null && lblstartTime.Text == "")
                lblstartTime.Text = Session["Start_Time"].ToString();
            if (Session["Pick_Time"] != null && lblPickTime.Text == "")
                lblPickTime.Text = Session["Pick_Time"].ToString();
            if (Session["Agent_Name"] != null && lblagentName.Text == "")
                lblagentName.Text = Session["Agent_Name"].ToString();
            if (Session["Extention_No"] != null && txtExtensionNo.Text == "")
                txtExtensionNo.Text = Convert.ToString(Session["Extention_No"]);

            if (!string.IsNullOrEmpty(Convert.ToString(Request.QueryString["Campaign_Id"])) && lblCampaignId.Text == "")
                lblCampaignId.Text = Convert.ToString(Request.QueryString["Campaign_Id"]);
            else if (Session["CampaignId"] != null && lblCampaignId.Text == "")
                lblCampaignId.Text = Session["CampaignId"].ToString();

            if (Session["pid"] != null && lblprocessid.Text == "")
                lblprocessid.Text = Session["pid"].ToString();
            if (Session["SrNo"] != null && (lblSrNo.Text == "" || lblSrNo.Text == "0"))
                lblSrNo.Text = Session["SrNo"].ToString();
            //Incoming with Special Field Client Id
            if (Request.QueryString["ClientId"] != null)
            {
                lblPhoneNo.Text = Phone_No.Text;
                //Session["Phone_No"] = Phone_No.Text = lblDialedPhone_No.Text = FunctionClassObj.ExecuteScalarString("SELECT Phone_No FROM Process_" + lblprocessid.Text + "_Master WHERE Client_Id = '" + Convert.ToString(Request.QueryString["ClientId"]) + "'");
                dtProcessMaster_Act = FunctionClassObj.GetData("SELECT * FROM Process_" + lblprocessid.Text + "_Master WHERE Client_Id = '" + Convert.ToString(Request.QueryString["ClientId"]) + "'");
                if (dtProcessMaster_Act.Rows.Count > 0)
                    Session["Phone_No"] = Phone_No.Text = lblDialedPhone_No.Text = dtProcessMaster_Act.Rows[0]["Phone_No"].ToString();
                if (Request.QueryString["Caller_Id"] != null)
                    lblDialedPhone_No.Text = FunctionClassObj.EncryptString(Request.QueryString["Caller_Id"].ToString().Trim());
            }
            //Dialer incoming
            if (string.IsNullOrEmpty(Phone_No.Text) && FunctionClassObj.StringToInt(Request.QueryString["SrNo"] == null ? "0" : Convert.ToString(Request.QueryString["SrNo"])) > 0)
            {
                lblPhoneNo.Text = Phone_No.Text;
                //Session["Phone_No"] = Phone_No.Text = lblDialedPhone_No.Text = FunctionClassObj.ExecuteScalarString("SELECT Phone_No FROM Process_" + lblprocessid.Text + "_Master t1,Campaign_" + lblprocessid.Text + "_Mapping t2 WHERE t1.Master_Id = t2.Customer_Id AND SrNo = " + FunctionClassObj.StringToInt(Request.QueryString["SrNo"].ToString()).ToString());
                dtProcessMaster_Act = FunctionClassObj.GetData("SELECT t1.*,t2.Campaign_Id FROM Process_" + lblprocessid.Text + "_Master t1,Campaign_" + lblprocessid.Text + "_Mapping t2 WHERE t1.Master_Id = t2.Customer_Id AND SrNo = " + FunctionClassObj.StringToInt(Request.QueryString["SrNo"].ToString()).ToString());
                if (dtProcessMaster_Act.Rows.Count > 0)
                    Session["Phone_No"] = Phone_No.Text = lblDialedPhone_No.Text = dtProcessMaster_Act.Rows[0]["Phone_No"].ToString();
                if (!string.IsNullOrEmpty(Phone_No.Text))
                {
                    Session["SrNo"] = lblSrNo.Text = FunctionClassObj.StringToInt(Request.QueryString["SrNo"].ToString()).ToString();
                    lblCampaignId.Text = dtProcessMaster_Act.Rows[0]["Campaign_Id"].ToString();
                }
                if (Request.QueryString["Caller_Id"] != null)
                    lblDialedPhone_No.Text = FunctionClassObj.EncryptString(Request.QueryString["Caller_Id"].ToString().Trim());
            }
            //Incoming or Call Log Edit or Dial Call
            if (string.IsNullOrEmpty(Phone_No.Text) && Request.QueryString["Caller_Id"] != null)
            {
                lblPhoneNo.Text = Phone_No.Text;
                Session["Phone_No"] = Phone_No.Text = lblDialedPhone_No.Text = FunctionClassObj.EncryptString(Request.QueryString["Caller_Id"].ToString().Trim());
            }
            Log_Id = Request.QueryString["Log_Id"] != null ? FunctionClassObj.StringToInt(Request.QueryString["Log_Id"].ToString()) : -1;
            if (Log_Id > 0)
            {
                DialPhone_No.Visible = false;
                Session["LogId"] = Log_Id;
            }
            if (!string.IsNullOrEmpty(lblCampaignId.Text))
            {
                dtProcess = FunctionClassObj.GetData("SELECT Process_Name,Script_Id,Agent_Mapping,Enable_CallStatus,Font_Size,no_of_master_column,no_of_log_column,Enable_CallStatus,Callback_AgentMapping,Callback_FromAnyCampaign,Agent_Dialing,Disposition_Script,Save_Script,Dial_Randomly,Edit_PhoneNo,Dial_Option,Enable_Last_Campaign_Save,Auto_Save,Auto_Save_Time_Interval,Default_Disposition,Allow_Set_Callback,Enable_Attachment_Master,Save_URL,Hide_Phone_No,Allow_Set_DNC FROM Process JOIN Campaign_Master on Process.pid = Campaign_Master.Process_Id WHERE Process.Pid = " + lblprocessid.Text + " AND Campaign_Id = " + lblCampaignId.Text);
                Enable_Dial = Convert.ToBoolean(FunctionClassObj.ExecuteScalar("Select Enable_Dial From Campaign_Master Where Process_Id=" + lblprocessid.Text + " AND Campaign_Id =" + lblCampaignId.Text));
                Phone_No.Visible = Phone_No_Lable.Visible = !Convert.ToBoolean(dtProcess.Rows[0]["Hide_Phone_No"].ToString());
                IsDoNotCall.Visible = Convert.ToBoolean(dtProcess.Rows[0]["Allow_Set_DNC"].ToString());
                Hide_Phone_No.Checked = Convert.ToBoolean(dtProcess.Rows[0]["Hide_Phone_No"].ToString());
                Save_Url.Text = dtProcess.Rows[0]["Save_URL"].ToString();
                DialPhone_No.Visible = Enable_Dial;
                lnkAttachements.Visible = Convert.ToBoolean(dtProcess.Rows[0]["Enable_Attachment_Master"].ToString());
                if (Convert.ToBoolean(dtProcess.Rows[0]["Dial_Randomly"].ToString()))
                    orderBy = " ORDER BY No_Of_Attempts,NewID() ";
                if (Convert.ToBoolean(dtProcess.Rows[0]["Edit_PhoneNo"].ToString()))
                    Phone_No.ReadOnly = false;
                else
                    Phone_No.ReadOnly = true;
            }
            if (dtProcess.Rows.Count > 0)
                lblProcessName.Text = dtProcess.Rows[0]["Process_Name"].ToString();
            else
            {
                ShowError.Visible = true;
                ErrorMessage.Text = "Process Not Found !! ";
                return;
            }
            if (ViewState["dtProcessMaster"] != null)
                dtProcessMaster = (DataTable)ViewState["dtProcessMaster"];
            else
                ViewState["dtProcessMaster"] = dtProcessMaster = FunctionClassObj.GetData("SELECT * FROM Process_Master WHERE pid = " + lblprocessid.Text + " AND Agent_Visible = 1 ORDER BY Order_No");
            if (ViewState["dtProcessLog"] != null)
                dtProcessLog = (DataTable)ViewState["dtProcessLog"];
            else
                ViewState["dtProcessLog"] = dtProcessLog = FunctionClassObj.GetData("SELECT * FROM Process_Log WHERE pid = " + lblprocessid.Text + " ORDER BY Order_No");
            #region post back
            if (!IsPostBack)
            {
                FunctionClassObj.BindDropDown(ref SANBranch_Master, "SELECT Branch_Id,Branch_Name FROM Branch_Master Order By Branch_Name");
                SANBranch_Master.Items[0].Value = "0";
                if (dtProcess.Rows[0]["Disposition_Script"].ToString() != string.Empty)
                    ddlCallStatus.Attributes.Add("onchange", dtProcess.Rows[0]["Disposition_Script"].ToString());
                if (!string.IsNullOrEmpty(dtProcess.Rows[0]["Save_Script"].ToString()))
                {
                    imgBtnSave.Attributes.Add("onclick", dtProcess.Rows[0]["Save_Script"].ToString());
                    imgBtnSaveNext.Attributes.Add("onclick", dtProcess.Rows[0]["Save_Script"].ToString());
                }
                if (string.IsNullOrEmpty(FunctionClassObj.ExecuteScalarString("SELECT Authentication_String FROM Process WHERE Pid = " + lblprocessid.Text)))
                    ImgBtnSMS.Visible = false;
                else
                    ImgBtnSMS.Visible = true;
                if (FunctionClassObj.ExecuteScalar("SELECT Count(Account_Id) FROM Email_Accounts WHERE isDefault = 1 AND Process_Id = " + lblprocessid.Text) > 0)
                    ImgBtnEMail.Visible = true;
                else
                    ImgBtnEMail.Visible = false;
                //SoftwareBackColor.BgColor = "#" + FunctionClassObj.ExecuteScalarString("SELECT TOP 1 Software_BackColor FROM Company_Setup");
                SoftwareBackColor.BgColor = "#" + FunctionClassObj.ExecuteScalarString("SELECT Software_BackColor FROM Process WHERE Pid = " + FunctionClassObj.StringToInt(Convert.ToString(Session["Pid"])));
                //lblTotalCalls.Text = FunctionClassObj.ExecuteScalarString("SELECT COUNT(Log_Id) TotalCall FROM Process_" + lblprocessid.Text + "_Log WHERE Agent_Name = '" + Session["Agent_Name"].ToString() + "' AND Campaign_Id = " +lblCampaignId.Text);
                string SQLQuery = "SELECT Convert(varchar,(SUM(Convert(int,SubString(duration,1,2))) * 3600 + SUM(Convert(int,SubString(duration,4,2))) * 60 + "
                + "SUM(Convert(int,SubString(duration,7,2))) )/3600 ) + ' : ' + Convert(varchar,((SUM(Convert(int,SubString(duration,1,2))) * 3600 + "
                + "SUM(Convert(int,SubString(duration,4,2))) * 60 + SUM(Convert(int,SubString(duration,7,2))) )%3600)/60) + ' : ' + "
                + "Convert(varchar,((SUM(Convert(int,SubString(duration,1,2))) * 3600 + SUM(Convert(int,SubString(duration,4,2))) * 60 +"
                + "SUM(Convert(int,SubString(duration,7,2))) )%3600)%60) as LoginHours FROM AMS_Log WHERE Agent_Name = '" + lblagentName.Text + "' AND Day(Log_Date) = Day(GetDate()) AND Month(Log_Date) = Month(GetDate()) AND Year(Log_Date) = Year(Log_Date)";
                //lblLoginHours.Text = FunctionClassObj.ExecuteScalarString(SQLQuery);
                FunctionClassObj.BindDropDown(ref ddlCallStatus, "SELECT Call_Status,Call_Status callstatus FROM CallStatus WHERE Agent_Selectable = 1 AND pid = " + lblprocessid.Text + " ORDER BY Call_Status");
                FunctionClassObj.SelectValue(ref ddlCallStatus, dtProcess.Rows[0]["Default_Disposition"].ToString());
                if (Convert.ToBoolean(dtProcess.Rows[0]["Auto_Save"]))
                {
                    ddlCallStatus.Items.RemoveAt(0);
                    ddlCallStatus.Items.Insert(0, new ListItem("AutoSave", "AutoSave"));
                }
                FunctionClassObj.BindDropDown(ref ddlExternalLink, "SELECT Link_Url,Link_Desc FROM External_Link WHERE Pid =" + lblprocessid.Text);
                FunctionClassObj.BindDropDown(ref ddlNewCampaign, "SELECT Campaign_Id,Campaign_Name FROM Campaign_Master WHERE Process_Id = " + lblprocessid.Text + " AND Campaign_Id <> " + lblCampaignId.Text + " AND Status ='True' ORDER BY Campaign_Name");
                FunctionClassObj.BindDropDown(ref Allow_Agent_Transfer, "SELECT Agent_Name AgentName,Agent_Name FROM Admin_Agent_Master WHERE Pid = 0 OR pid = " + lblprocessid.Text + " ORDER BY Agent_Name");
                FunctionClassObj.BindDropDown(ref Call_Transfer, "SELECT Admin_Extention_Master.Extention_No,Agent_Name + '-' + Admin_Extention_Master.Extention_No  Agent_Name FROM Admin_Extention_Master JOIN Extention_ACD ON Admin_Extention_Master.Extention_No = Extention_ACD.Extention_No JOIN Campaign_Master ON Campaign_Master.Campaign_Id = Extention_ACD.Campaign_Id WHERE Process_Id = " + lblprocessid.Text + " AND Agent_Name IS NOT NULL AND Admin_Extention_Master.Extention_No != '" + txtExtensionNo.Text + "' ORDER BY Agent_Name");
                //Show Agent Drop Down on agent transfer allowed
                Allow_Agent_Transfer.Visible = lblAgentTransfer.Visible = Convert.ToBoolean(FunctionClassObj.ExecuteScalarString("SELECT Allow_Agent_Transfer FROM Process WHERE pId = " + lblprocessid.Text));
                Call_Transfer.Visible = ImgBtnCallTransfer.Visible = Convert.ToBoolean(FunctionClassObj.ExecuteScalarString("SELECT Allow_Call_Transfer FROM Process WHERE pId = " + lblprocessid.Text));
                //Show Campaign Drop Down if Campaign Transfer Allowed
                ddlNewCampaign.Visible = Label4.Visible = Convert.ToBoolean(FunctionClassObj.ExecuteScalarString("SELECT Allow_Camp_Transfer FROM Campaign_Master WHERE Campaign_Id = " + lblCampaignId.Text));
                #region call mode
                if (Request.QueryString["callmode"] != null)
                    lblCallMode.Text = Request.QueryString["callmode"].ToString();
                else if (Convert.ToString(Session["Disposition"]) == "Fresh Call")
                    lblCallMode.Text = "Fresh Call";
                else if (Session["Disposition"] != null)
                    lblCallMode.Text = "dispositionwise";
                else
                    lblCallMode.Text = FunctionClassObj.ExecuteScalarString("SELECT Dial_Mode FROM Campaign_Master WHERE Campaign_Id = " + lblCampaignId.Text).ToLower();
                #endregion
                if (lblCallMode.Text == "editlog")
                {
                    #region Edit Old Call Log
                    ddlCallStatus.SelectedValue = FunctionClassObj.ExecuteScalarString("SELECT CallStatus FROM Process_" + lblprocessid.Text + "_Log WHERE Log_Id = " + Request.QueryString["Log_Id"].ToString());
                    lblCampaignId.Text = FunctionClassObj.ExecuteScalarString("SELECT Campaign_Id FROM Process_" + lblprocessid.Text + "_Log WHERE Log_Id = " + Request.QueryString["Log_Id"].ToString());
                    #endregion
                }
                else
                {
                    if (lblCallMode.Text == "previewdialing")
                    {
                        Session["LastSrNo"] = lblSrNo.Text;
                        imgBtnNext.Visible = imgBtnSaveNext.Visible = false;
                        imgBtnSave.Text = "Cancel";
                        Call_Log_Attempt.Text = "1";
                    }
                    else if (lblCallMode.Text == "alternateno")
                    {
                        #region Alternate No Calling
                        lblUniqueId.Text = DateTime.Now.ToString("yyyyMMdd-HHmmss-ffff");
                        lblDialedPhone_No.Text = Request.QueryString["Alternateno"] == null ? Phone_No.Text : FunctionClassObj.StringToStrPhoneNo(Request.QueryString["Alternateno"].ToString().Trim());
                        if (!FunctionClassObj.IsDNCNumber(lblDialedPhone_No.Text, FunctionClassObj.StringToInt(Session["pid"].ToString())))
                            UpdateCRMState("Manual", lblDialedPhone_No.Text, lblUniqueId.Text);
                        Session["Pick_Time"] = Session["Start_Time"] = lblstartTime.Text = lblPickTime.Text = DateTime.Now.ToString();
                        if (Request.QueryString["Visible"].ToString() == "1")
                            imgBtnSaveNext.Visible = true;
                        else if (Request.QueryString["Visible"].ToString() == "2")
                            imgBtnNext.Visible = imgBtnSaveNext.Visible = true;
                        if (Request.QueryString["CallLogAttempt"] != null)
                            Call_Log_Attempt.Text = Convert.ToString(FunctionClassObj.StringToInt(Request.QueryString["CallLogAttempt"].ToString()) + 1);
                        else
                            Call_Log_Attempt.Text = "1";
                        #endregion
                    }
                    else if (lblCallMode.Text == "incomingcall")
                    {
                        if (FunctionClassObj.ExecuteScalarString("SELECT Dial_Mode FROM Campaign_Master WHERE Campaign_Id = " + lblCampaignId.Text).ToLower() == "predictive")
                            imgBtnSaveNext.Visible = true;
                        if (FunctionClassObj.ExecuteScalar("SELECT SrNo FROM Admin_Extention_Master WHERE Extention_No = '" + txtExtensionNo.Text + "'") > 0)
                        {
                            Session["dialerincoming"] = "dialerincoming";
                            lblCallBack.Text = "Dialer Incoming";
                        }
                        else
                            lblCallBack.Text = "Incoming";
                        Call_Log_Attempt.Text = "1";
                        DataTable dtDID = FunctionClassObj.GetData("SELECT DID_Master.DID_No,Script,Template_Id,Mobile_No,Email_Id,Account_Id,EmailTemplate_Id,DID_Customize_URL,isCustomizeURL FROM DID_Master JOIN Admin_Extention_Master ON DID_Master.DID_No = Admin_Extention_Master.DID_No JOIN Script_Master ON Script_Master.Script_Id = DID_Master.Script_Id WHERE Extention_No = '" + txtExtensionNo.Text + "'");
                        if (dtDID.Rows.Count > 0)
                        {
                            if (dtDID.Rows[0]["isCustomizeURL"].ToString() == "True" && !string.IsNullOrEmpty(dtDID.Rows[0]["DID_Customize_URL"].ToString()))
                                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Script", "window.open('sukhveer.aspx','Script','channelmode=yes,resizable=yes,titlebar=yes,scrollbars=yes')", true);
                            lblEmail_Id.Text = dtDID.Rows[0]["Email_Id"].ToString();
                            lblAccount_Id.Text = dtDID.Rows[0]["Account_Id"].ToString();
                            lblEmailTemplate_Id.Text = dtDID.Rows[0]["EmailTemplate_Id"].ToString();
                            DID_No.Text = dtDID.Rows[0]["DID_No"].ToString();
                            lblScriptText.Text = Server.HtmlDecode(dtDID.Rows[0]["Script"].ToString());
                            DIDTemplate_Id.Text = dtDID.Rows[0]["Template_Id"].ToString();
                            lblDIDMobile_No.Text = dtDID.Rows[0]["Mobile_No"].ToString();
                        }
                        else
                            DID_No.Text = FunctionClassObj.ExecuteScalarString("SELECT DID_No FROM Admin_Extention_Master WHERE Extention_No = '" + txtExtensionNo.Text + "'");
                    }
                    else if (lblCallMode.Text.ToLower() == "dialerincoming")
                    {
                        lblCallBack.Text = "Dialer Incoming";
                    }
                    else if (lblCallMode.Text == "manualdialing")
                    {
                        #region Manual Dialing
                        lblUniqueId.Text = DateTime.Now.ToString("yyyyMMdd-HHmmss-ffff");
                        if (!FunctionClassObj.IsDNCNumber(Phone_No.Text, FunctionClassObj.StringToInt(Session["pid"].ToString())))
                        {
                            UpdateCRMState("Manual", Phone_No.Text, lblUniqueId.Text);
                            FunctionClassObj.ExecuteCommand("UPDATE Campaign_" + lblprocessid.Text + "_Mapping SET No_Of_Attempts = (ISNULL(No_Of_Attempts,0) + 1) WHERE SrNo = " + FunctionClassObj.StringToInt(lblSrNo.Text));
                            Call_Log_Attempt.Text = "1";
                        }
                        Session["Pick_Time"] = Session["Start_Time"] = lblstartTime.Text = lblPickTime.Text = DateTime.Now.ToString();
                        if (FunctionClassObj.ExecuteScalarString("SELECT Dial_Mode FROM Campaign_Master WHERE Campaign_Id = " + lblCampaignId.Text).ToLower() == "predictive")
                            imgBtnSaveNext.Visible = true;
                        #endregion
                    }
                    else if (lblCallMode.Text == "callbackdialing")
                    {
                        #region Call Back Dialing by Agent
                        lblUniqueId.Text = DateTime.Now.ToString("yyyyMMdd-HHmmss-ffff");
                        string strPhoneNo = Session["CallBackPhoneNo"].ToString();
                        if (string.IsNullOrEmpty(strPhoneNo))
                            strPhoneNo = Phone_No.Text;
                        if (!FunctionClassObj.IsDNCNumber(strPhoneNo, FunctionClassObj.StringToInt(Session["pid"].ToString())))
                        {
                            UpdateCRMState("Manual", strPhoneNo, lblUniqueId.Text);
                            FunctionClassObj.ExecuteCommand("UPDATE Campaign_" + lblprocessid.Text + "_Mapping SET No_Of_Attempts = (ISNULL(No_Of_Attempts,0) + 1) WHERE SrNo = " + FunctionClassObj.StringToInt(lblSrNo.Text));
                            Call_Log_Attempt.Text = "1";
                        }
                        lblCallBack.Text = Session["CallAgainType"].ToString() + " Call Back ";
                        lblCallBackTime.Text = Convert.ToString(Session["CallBack8Time"]);
                        lblCall_Again_Type.Text = Session["CallAgainType"].ToString();
                        Session["Pick_Time"] = Session["Start_Time"] = lblstartTime.Text = lblPickTime.Text = DateTime.Now.ToString();
                        if (FunctionClassObj.ExecuteScalarString("SELECT Dial_Mode FROM Campaign_Master WHERE Campaign_Id = " + lblCampaignId.Text).ToLower() == "predictive")
                            imgBtnSaveNext.Visible = true;

                        #endregion
                    }
                    else if (lblCallMode.Text == "Fresh Call")
                    {
                        #region fresh calling
                        //string queryPhoneNo = "SELECT TOP 1 Process_" + lblprocessid.Text + "_Master.*,Call_Again_Time Call_Again_Time,Campaign_" + lblprocessid.Text + "_Mapping.SrNo "
                        //+ " FROM Process_" + lblprocessid.Text + "_Master JOIN Campaign_" + lblprocessid.Text + "_Mapping ON Process_" + lblprocessid.Text + "_Master.Master_Id = Campaign_" + lblprocessid.Text + "_Mapping.Customer_Id "
                        //+ " WHERE Campaign_" + lblprocessid.Text + "_Mapping.Campaign_Id = " + lblCampaignId.Text + " AND Disposition IS NULL AND Dialed = 'False'";
                        //if (dtProcess.Rows[0]["Agent_Mapping"].ToString() == "True")
                        //    queryPhoneNo += " AND Agent_Id = '" + Session["Agent_Name"].ToString() + "'";
                        //string queryPhoneNo = "SELECT TOP 1 Phone_No,Call_Again_Time,SrNo FROM Process_" + lblprocessid.Text + "_Master t1"
                        // + " JOIN Campaign_" + lblprocessid.Text + "_Mapping t2 ON t1.Master_Id = t2.Customer_Id JOIN File_Master t3 ON t2.File_Id = t3.File_Id "
                        // + " WHERE isActive = 'True' AND Dialed = 'False' AND (Do_Not_Call IS NULL OR Do_Not_Call = 0) AND (SAN_DNC IS NULL OR SAN_DNC = 0) AND Call_Again_Time IS NULL AND Campaign_Id = " + lblCampaignId.Text;
                        string queryPhoneNo = "SELECT TOP 1 Phone_No,Call_Again_Time,SrNo FROM IPCapture" + lblprocessid.Text + " WITH (NOEXPAND) WHERE Call_Again_Time IS NULL AND Campaign_Id = " + lblCampaignId.Text;
                        if (dtProcess.Rows[0]["Agent_Mapping"].ToString() == "True")
                            queryPhoneNo += " AND Agent_Id = '" + lblagentName.Text + "'";
                        dtProgressivedialing = FunctionClassObj.GetData(queryPhoneNo + orderBy);
                        if (dtProgressivedialing.Rows.Count == 1)
                        {
                            lblCallBack.Text = "Fresh Call";
                            Session["Phone_No"] = Phone_No.Text = dtProgressivedialing.Rows[0]["Phone_No"].ToString();
                            Session["SrNo"] = lblSrNo.Text = dtProgressivedialing.Rows[0]["SrNo"].ToString();
                            FunctionClassObj.ExecuteCommand("UPDATE Campaign_" + lblprocessid.Text + "_Mapping SET Dialed = 'True',No_Of_Attempts = (ISNULL(No_Of_Attempts,0) + 1) WHERE SrNo = " + lblSrNo.Text);
                            UpdateCRMState("Outgoing", Phone_No.Text, lblUniqueId.Text);
                            //FunctionClassObj.ExecuteCommand("UPDATE Campaign_" + lblprocessid.Text + "_Mapping SET No_Of_Attempts = (ISNULL(No_Of_Attempts,0) + 1) WHERE SrNo = " + FunctionClassObj.StringToInt(lblSrNo.Text));
                            imgBtnSaveNext.Visible = true;
                            Session["Pick_Time"] = Session["Start_Time"] = lblstartTime.Text = lblPickTime.Text = DateTime.Now.ToString();
                            Call_Log_Attempt.Text = "1";
                        }
                        else
                            NoDialing();
                        #endregion
                    }
                    else if (lblCallMode.Text == "preview")
                    {
                        string queryPhoneNo1 = "SELECT TOP 1 Phone_No,Call_Again_Time,SrNo FROM Process_" + lblprocessid.Text + "_Master t1"
                      + " JOIN Campaign_" + lblprocessid.Text + "_Mapping t2 ON t1.Master_Id = t2.Customer_Id JOIN File_Master t3 ON t2.File_Id = t3.File_Id "
                      + " WHERE isActive = 'True' AND Dialed = 'False' AND (Do_Not_Call IS NULL OR Do_Not_Call = 0) AND (SAN_DNC IS NULL OR SAN_DNC = 0) AND Call_Again_Time IS NULL AND Campaign_Id = " + lblCampaignId.Text;
                        if (FunctionClassObj.ExecuteScalar("SELECT 1 FROM Process WHERE Allow_Set_DNC = 1 AND pid = " + Session["Pid"].ToString()) == 1)
                            queryPhoneNo1 += " AND (IsDNC IS NULL OR IsDNC = 0) ";
                        string queryPhoneNo = "SELECT TOP 1 Phone_No,Call_Again_Time,SrNo FROM IPCapture" + lblprocessid.Text + " WITH (NOEXPAND) WHERE Call_Again_Time IS NULL AND Campaign_Id = " + lblCampaignId.Text;
                        if (dtProcess.Rows[0]["Agent_Mapping"].ToString() == "True")
                            queryPhoneNo += " AND Agent_Id = '" + lblagentName.Text + "'";
                        lblUniqueId.Text = DateTime.Now.ToString("yyyyMMdd-HHmmss-ffff");
                        #region preview dialing
                        if (Session["LastSrNo"] != null)
                        {
                            queryPhoneNo += " AND SrNo > " + Session["LastSrNo"].ToString();
                            dtProgressivedialing = FunctionClassObj.GetData(queryPhoneNo + orderBy);
                            if (dtProgressivedialing.Rows.Count == 1)
                            {
                                Phone_No.Text = dtProgressivedialing.Rows[0]["Phone_No"].ToString();
                                Session["SrNo"] = lblSrNo.Text = dtProgressivedialing.Rows[0]["SrNo"].ToString();
                                Session["LastSrNo"] = dtProgressivedialing.Rows[0]["SrNo"].ToString();
                                //UpdateCRMState("Outgoing", Phone_No.Text, lblUniqueId.Text);
                                UpdateCRMState("Idle");
                                imgBtnNext.Visible = imgBtnSaveNext.Visible = true;
                                imgBtnSave.Enabled = imgBtnSaveNext.Enabled = false;
                                Call_Log_Attempt.Text = "0";
                            }
                            else
                                NoDialing();
                        }
                        else
                            NoDialing();
                        #endregion
                    }
                    else if (!CallBack())
                    {
                        string queryPhoneNo1 = "SELECT TOP 1 Phone_No,Call_Again_Time,SrNo FROM Process_" + lblprocessid.Text + "_Master t1"
                        + " JOIN Campaign_" + lblprocessid.Text + "_Mapping t2 ON t1.Master_Id = t2.Customer_Id JOIN File_Master t3 ON t2.File_Id = t3.File_Id "
                        + " WHERE isActive = 'True' AND Dialed = 'False' AND (Do_Not_Call IS NULL OR Do_Not_Call = 0) AND (SAN_DNC IS NULL OR SAN_DNC = 0) AND Call_Again_Time IS NULL AND Campaign_Id = " + lblCampaignId.Text;
                        if (FunctionClassObj.ExecuteScalar("SELECT 1 FROM Process WHERE Allow_Set_DNC = 1 AND pid = " + Session["Pid"].ToString()) == 1)
                            queryPhoneNo1 += " AND (IsDNC IS NULL OR IsDNC = 0) ";
                        string queryPhoneNo = "SELECT TOP 1 Phone_No,Call_Again_Time,SrNo FROM IPCapture" + lblprocessid.Text + " WITH (NOEXPAND) WHERE Call_Again_Time IS NULL AND Campaign_Id = " + lblCampaignId.Text;
                        if (dtProcess.Rows[0]["Agent_Mapping"].ToString() == "True")
                            queryPhoneNo += " AND Agent_Id = '" + lblagentName.Text + "'";
                        lblUniqueId.Text = DateTime.Now.ToString("yyyyMMdd-HHmmss-ffff");

                        if (lblCallMode.Text == "progressive")
                        {
                            #region progressiove dialing
                            DataTable CallDisposition = FunctionClassObj.GetData("SELECT callstatus FROM Campaign_Disposition WHERE Campaign_Id = " + lblCampaignId.Text);
                            if (CallDisposition.Rows.Count > 0)
                            {
                                for (int l = 0; l < CallDisposition.Rows.Count; l++)
                                {
                                    dtProgressivedialing = FunctionClassObj.GetData(queryPhoneNo1 + " AND Disposition = '" + CallDisposition.Rows[l][0].ToString() + "'" + orderBy);
                                    if (dtProgressivedialing.Rows.Count == 1)
                                    {
                                        Session["Phone_No"] = Phone_No.Text = dtProgressivedialing.Rows[0]["Phone_No"].ToString();
                                        Session["SrNo"] = lblSrNo.Text = dtProgressivedialing.Rows[0]["SrNo"].ToString();
                                        FunctionClassObj.ExecuteCommand("UPDATE Campaign_" + lblprocessid.Text + "_Mapping SET Dialed = 'True',No_Of_Attempts = (ISNULL(No_Of_Attempts,0) + 1) WHERE SrNo = " + dtProgressivedialing.Rows[0]["SrNo"].ToString());
                                        UpdateCRMState("Outgoing", Phone_No.Text, lblUniqueId.Text);
                                        //FunctionClassObj.ExecuteCommand("UPDATE Campaign_" + lblprocessid.Text + "_Mapping SET No_Of_Attempts = (ISNULL(No_Of_Attempts,0) + 1) WHERE SrNo = " + FunctionClassObj.StringToInt(lblSrNo.Text));
                                        imgBtnSaveNext.Visible = true;
                                        Session["Pick_Time"] = Session["Start_Time"] = lblstartTime.Text = lblPickTime.Text = DateTime.Now.ToString();
                                        Call_Log_Attempt.Text = "1";
                                        break;
                                    }
                                }
                            }
                            if (string.IsNullOrEmpty(Phone_No.Text))
                            {
                                if (dtProcess.Rows[0]["Dial_Option"].ToString() == "Default")
                                    dtProgressivedialing = FunctionClassObj.GetData(queryPhoneNo + orderBy);
                                else
                                    dtProgressivedialing = FunctionClassObj.GetData("NextPhoneNo " + lblprocessid.Text + "," + lblCampaignId.Text);
                                if (dtProgressivedialing.Rows.Count == 1)
                                {
                                    lblCallBack.Text = "";
                                    Session["Phone_No"] = Phone_No.Text = dtProgressivedialing.Rows[0]["Phone_No"].ToString();
                                    Session["SrNo"] = lblSrNo.Text = dtProgressivedialing.Rows[0]["SrNo"].ToString();
                                    FunctionClassObj.ExecuteCommand("UPDATE Campaign_" + lblprocessid.Text + "_Mapping SET Dialed = 'True',No_Of_Attempts = (ISNULL(No_Of_Attempts,0) + 1) WHERE SrNo = " + dtProgressivedialing.Rows[0]["SrNo"].ToString());
                                    UpdateCRMState("Outgoing", Phone_No.Text, lblUniqueId.Text);
                                    //FunctionClassObj.ExecuteCommand("UPDATE Campaign_" + lblprocessid.Text + "_Mapping SET No_Of_Attempts = (ISNULL(No_Of_Attempts,0) + 1) WHERE SrNo = " + FunctionClassObj.StringToInt(lblSrNo.Text));
                                    Session["Pick_Time"] = Session["Start_Time"] = lblstartTime.Text = lblPickTime.Text = DateTime.Now.ToString();
                                    imgBtnSaveNext.Visible = true;
                                    Call_Log_Attempt.Text = "1";
                                }
                                else
                                    NoDialing();
                            }
                            #endregion
                        }
                        else if (lblCallMode.Text == "dispositionwise")
                        {
                            #region disposition wise calling
                            queryPhoneNo = "SELECT TOP 1 Master_Id,Phone_No,Call_Again_Time,SrNo FROM Process_" + lblprocessid.Text + "_Master t1"
                            + " JOIN Campaign_" + lblprocessid.Text + "_Mapping t2 ON t1.Master_Id = t2.Customer_Id JOIN File_Master t3 ON t2.File_Id = t3.File_Id "
                            + " WHERE isActive = 'True' AND (Do_Not_Call IS NULL OR Do_Not_Call = 0) AND (SAN_DNC IS NULL OR SAN_DNC = 0) AND Campaign_Id = " + lblCampaignId.Text;
                            if (FunctionClassObj.ExecuteScalar("SELECT 1 FROM Process WHERE Allow_Set_DNC = 1 AND pid = " + Session["Pid"].ToString()) == 1)
                                queryPhoneNo += " AND (IsDNC IS NULL OR IsDNC = 0) ";
                            if (dtProcess.Rows[0]["Agent_Mapping"].ToString() == "True")
                                queryPhoneNo += " AND Agent_Id = '" + lblagentName.Text + "'";
                            queryPhoneNo += " AND Disposition = '" + Session["Disposition"].ToString() + "'";
                            if (dtProcess.Rows[0]["Agent_Dialing"].ToString() == "False")
                                queryPhoneNo += " AND Dialed = 'False'";
                            else if (Session["LastSrNo"] != null)
                                queryPhoneNo += " AND SrNo > " + Session["LastSrNo"].ToString();
                            dtProgressivedialing = FunctionClassObj.GetData(queryPhoneNo + orderBy);
                            if (dtProgressivedialing.Rows.Count == 1)
                            {
                                lblCallBack.Text = Session["Disposition"].ToString();
                                Session["Phone_No"] = Phone_No.Text = dtProgressivedialing.Rows[0]["Phone_No"].ToString();
                                Session["SrNo"] = lblSrNo.Text = dtProgressivedialing.Rows[0]["SrNo"].ToString();
                                FunctionClassObj.ExecuteCommand("UPDATE Campaign_" + lblprocessid.Text + "_Mapping SET Dialed = 'True',No_Of_Attempts = (ISNULL(No_Of_Attempts,0) + 1) WHERE SrNo = " + dtProgressivedialing.Rows[0]["SrNo"].ToString());
                                UpdateCRMState("Outgoing", Phone_No.Text, lblUniqueId.Text);
                                //FunctionClassObj.ExecuteCommand("UPDATE Campaign_" + lblprocessid.Text + "_Mapping SET No_Of_Attempts = (ISNULL(No_Of_Attempts,0) + 1) WHERE SrNo = " + FunctionClassObj.StringToInt(lblSrNo.Text));
                                Session["LastSrNo"] = dtProgressivedialing.Rows[0]["SrNo"].ToString();
                                imgBtnSaveNext.Visible = true;
                                Session["Pick_Time"] = Session["Start_Time"] = lblstartTime.Text = lblPickTime.Text = DateTime.Now.ToString();
                                Call_Log_Attempt.Text = "1";
                            }
                            else
                                NoDialing();
                            #endregion
                        }
                        else
                            NoDialing();
                    }
                    //lblAttempts.Text = FunctionClassObj.ExecuteScalarString("SELECT COUNT(Phone_No) FROM Process_" + lblprocessid.Text + "_Log WHERE Phone_No = '" + Phone_No.Text + "'");
                    lblCampaignName.Text = FunctionClassObj.ExecuteScalarString("SELECT Campaign_Name FROM Campaign_Master WHERE Campaign_Id = " + lblCampaignId.Text);
                }
            }
            #endregion
            #region Show Hide Callback required
            if (Convert.ToBoolean(dtProcess.Rows[0]["Allow_Set_Callback"]))
                Label2.Visible = txtCallBackDate.Visible = callbacktimeHr.Visible = callbacktimeMm.Visible = Label10.Visible = Call_Again_PhoneNo.Visible = !Convert.ToBoolean(FunctionClassObj.ExecuteScalarString("if Exists(SELECT SetCallBackNotRequired FROM CallStatus WHERE PId = " + lblprocessid.Text + " AND Call_Status = '" + ddlCallStatus.SelectedValue + "') SELECT SetCallBackNotRequired FROM CallStatus WHERE PId = " + lblprocessid.Text + " AND Call_Status = '" + ddlCallStatus.SelectedValue + "' ELSE SELECT 'True' SetCallBackNotRequired"));
            else
                Label2.Visible = txtCallBackDate.Visible = callbacktimeHr.Visible = callbacktimeMm.Visible = Label10.Visible = Call_Again_PhoneNo.Visible = false;

            if (dtProcessMaster_Act.Rows.Count == 0 && !string.IsNullOrEmpty(Phone_No.Text))
            {
                if (!string.IsNullOrEmpty(Master_Id.Text))
                    sqlString = "SELECT TOP 1 * FROM Process_" + lblprocessid.Text + "_Master WHERE Master_Id = '" + Master_Id.Text + "'";
                else
                    sqlString = "SELECT TOP 1 * FROM Process_" + lblprocessid.Text + "_Master WHERE Phone_No = '" + Phone_No.Text + "'";
                dtProcessMaster_Act = FunctionClassObj.GetData(sqlString);
                if (dtProcessMaster_Act.Rows.Count == 0)
                {
                    dtAlternateFields = FunctionClassObj.GetData("SELECT Field_Name FROM Process_Master WHERE Pid = " + lblprocessid.Text + " AND Field_Type = 'Phone No'");
                    for (int i = 0; i < dtAlternateFields.Rows.Count; i++)
                        sqlString += " OR " + dtAlternateFields.Rows[i][0].ToString() + " = '" + Phone_No.Text + "'";
                    dtProcessMaster_Act = FunctionClassObj.GetData(sqlString);
                }
            }
            #endregion
            if (dtProcessMaster_Act.Rows.Count > 0)
            {
                Session["Phone_No"] = Phone_No.Text = FunctionClassObj.StringToStrPhoneNo(dtProcessMaster_Act.Rows[0]["Phone_No"].ToString());
                Session["Master_Id"] = Master_Id.Text = dtProcessMaster_Act.Rows[0]["Master_Id"].ToString();
                if (!IsPostBack)
                {
                    FunctionClassObj.SelectValue(ref SANBranch_Master, dtProcessMaster_Act.Rows[0]["Branch_Id"].ToString());
                    if (Convert.ToBoolean(dtProcess.Rows[0]["Enable_Last_Campaign_Save"]) && lblCallMode.Text == "manualdialing")
                    {
                        string intCampaignId = FunctionClassObj.ExecuteScalarString("SELECT Campaign_Id FROM Process_" + lblprocessid.Text + "_Log WHERE Master_Id = '" + Master_Id.Text + "' ORDER BY Log_Id DESC");
                        if (FunctionClassObj.ExecuteScalar("SELECT Count(Campaign_Id) FROM Campaign_Master WHERE Campaign_Id = '" + intCampaignId.ToString() + "'") > 0)
                            lblCampaignId.Text = intCampaignId.ToString();
                    }
                }
            }
            dtProcessLogTemp = FunctionClassObj.GetData("SELECT * FROM Process_" + lblprocessid.Text + "_Log WHERE Log_Id = '" + Log_Id + "' ");
            GetTableFields("Process_Master", PlaceHolder_Master, dtProcessMaster, "Master", FunctionClassObj.StringToInt(dtProcess.Rows[0]["no_of_master_column"].ToString()), Convert.ToBoolean(dtProcess.Rows[0]["Enable_CallStatus"].ToString()), FunctionClassObj.StringToInt(dtProcess.Rows[0]["Font_Size"].ToString()));
            GetTableFields("Process_Log", PlaceHolder_Log, dtProcessLog, "Log", FunctionClassObj.StringToInt(dtProcess.Rows[0]["no_of_log_column"].ToString()), Convert.ToBoolean(dtProcess.Rows[0]["Enable_CallStatus"].ToString()), FunctionClassObj.StringToInt(dtProcess.Rows[0]["Font_Size"].ToString()));
            GetSearchFields(FunctionClassObj.FilterRecords(dtProcessMaster, "Allow_Filter = 1", "Order_No"), FunctionClassObj.StringToInt(dtProcess.Rows[0]["no_of_master_column"].ToString()), FunctionClassObj.StringToInt(dtProcess.Rows[0]["Font_Size"].ToString()));
            if (Request.QueryString["Log_Id"] == null)
            {
                DataTable dtCheck = FunctionClassObj.GetData("SELECT Call_Log_Count,Call_Log_Any_Campaign,Call_Log_Active_File FROM Campaign_Master WHERE Campaign_Id = " + FunctionClassObj.StringToInt(lblCampaignId.Text));
                string fieldToDisplay = " Row_Number() OVER (ORDER BY Log_Id) AS CallNo,Log_Id,Campaign_Name Campaign,File_Name [FileName],Agent_Name,CONVERT(Varchar,Start_Time,13) Start_Time,CONVERT(varchar,Pick_Time,13) Pick_Time,CONVERT(Varchar,End_Time,13) End_Time,CallType,CallStatus CallDisposition";
                for (int k = 0; k < dtProcessLog.Rows.Count; k++)
                {
                    if (Convert.ToBoolean(dtProcessLog.Rows[k]["Show_In_CallTrail"].ToString()))
                        fieldToDisplay += "," + dtProcessLog.Rows[k]["Field_Name"].ToString();
                }
                dtProcessLogTemp = FunctionClassObj.GetData("SELECT TOP " + dtCheck.Rows[0][0].ToString() + " " + fieldToDisplay + " FROM Process_" + lblprocessid.Text + "_Log t1 JOIN Campaign_" + lblprocessid.Text + "_Mapping t2 ON t1.SrNo = t2.SrNo JOIN Campaign_Master t4 ON t2.Campaign_Id = t4.Campaign_Id "
                + " JOIN File_Master t3 ON t2.File_Id = t3.File_Id WHERE CallStatus IS NOT NULL AND Master_Id = '" + Master_Id.Text + "' "
                + (dtCheck.Rows[0][2].ToString() == "True" ? " AND t3.IsActive = 1 " : " ") + (dtCheck.Rows[0][1].ToString() == "False" ? " AND t1.Campaign_Id = " + lblCampaignId.Text : " ") + " ORDER BY CallNo DESC");
                gvLogTable.DataSource = dtProcessLogTemp;
                gvLogTable.DataBind();
            }
        }
        catch (Exception ex)
        {
            ErrorMessage.Visible = true;
            ErrorMessage.Text = "Error Page Loading : " + ex.Message;
            FunctionClassObj.ExecuteCommand("INSERT INTO Error_Log(User_Name,Error_Desc) Values('" + lblagentName.Text + "','" + ex.Message.Replace("'", "''") + "')");
        }
        this.Title = FunctionClassObj.SoftwareVersion() + " : Servicing Call : " + Convert.ToString(Session["CompanyName"]);
        if (!string.IsNullOrEmpty(lblPhoneNo.Text))
            Phone_No.Text = FunctionClassObj.StringToStrPhoneNo(lblPhoneNo.Text);
        if (string.IsNullOrEmpty(lblDialedPhone_No.Text))
            lblDialedPhone_No.Text = Phone_No.Text;
    }
    public void GetTableFields(string tableName, PlaceHolder paraPlaceHolder, DataTable paraDT, string tableType, int l, bool CallStatusType, int Font_Size)
    {
        int l1, l2;
        Table Table1 = new Table();
        Table1.Style["class"] = "border";
        //Table1.Style["width"] = "100%";
        Table1.CellPadding = 1;
        Table1.CellSpacing = 0;
        Table1.BorderWidth = 0;
        TableRow Row1, RowHeading;
        TableCell Cell1;
        DataTable dtGroup = FunctionClassObj.GetData("SELECT DISTINCT Group_Name FROM " + tableName + " WHERE Pid = " + lblprocessid.Text);
        for (int j = 0; j < dtGroup.Rows.Count; j++)
        {
            DataTable dtFields = new DataTable();
            if (tableName == "Process_Log" && CallStatusType == true && ddlCallStatus.SelectedValue == "--Select--")
                dtFields = FunctionClassObj.FilterRecords(paraDT, "Group_Name = '" + dtGroup.Rows[j][0].ToString() + "' AND Call_Status = '0'", "Order_No");
            else if (tableName == "Process_Log" && CallStatusType == true && ddlCallStatus.SelectedValue != "--Select--" && dtGroup.Rows[j][0].ToString() == "0")
                dtFields = FunctionClassObj.FilterRecords(paraDT, "Group_Name = '0'", "Order_No");
            else if (tableName == "Process_Log" && CallStatusType == true && ddlCallStatus.SelectedValue != "--Select--")
                dtFields = FunctionClassObj.FilterRecords(paraDT, "Group_Name = '" + dtGroup.Rows[j][0].ToString() + "' AND Call_Status IN('0', '" + ddlCallStatus.SelectedValue + "')", "Order_No");
            else
                dtFields = FunctionClassObj.FilterRecords(paraDT, "Group_Name = '" + dtGroup.Rows[j][0].ToString() + "'", "Order_No");

            if (dtFields.Rows.Count > 0)
            {
                //if (tableName == "Process_Log" && CallStatusType == false || tableName == "Process_Master")
                //{
                Row1 = new TableRow();
                Row1.Style["HEIGHT"] = "5px";
                Row1.Style["BORDER-BOTTOM"] = "#006699 1px solid";
                Cell1 = new TableCell();
                if (dtGroup.Rows[j][0].ToString() != "0")
                    Cell1.Text = "<font color=red>" + dtGroup.Rows[j][0].ToString() + "</font>";
                else
                    Cell1.Text = "<font color=red></font>";
                Cell1.Font.Bold = true;
                Cell1.HorizontalAlign = HorizontalAlign.Left;
                Row1.Cells.Add(Cell1);
                Table1.Rows.Add(Row1);
                // }
                int max = (dtFields.Rows.Count) / l;
                if ((dtFields.Rows.Count) % l != 0)
                    max++;
                l1 = 0;
                if (dtFields.Rows.Count < l)
                    l2 = dtFields.Rows.Count;
                else
                    l2 = l;
                for (int k = 0; k < max; k++)
                {
                    Row1 = new TableRow();
                    RowHeading = new TableRow();
                    for (int i = l1; i < l2; i++)
                    {
                        string Field_Remarks = string.Empty;
                        Field_Remarks = dtFields.Rows[i]["Remarks"].ToString();
                        string Field_Description = dtFields.Rows[i]["Field_Description"].ToString();
                        string Field_Type = dtFields.Rows[i]["Field_Type"].ToString();
                        string Field_Name = dtFields.Rows[i]["Field_Name"].ToString();
                        string Control_Type = dtFields.Rows[i]["Control_Type"].ToString();
                        string Call_Status = "0";
                        if (CallStatusType)
                            Call_Status = dtFields.Rows[i]["Call_Status"].ToString();
                        string javaScript = string.Empty;
                        if (tableType == "Log")
                            javaScript = dtFields.Rows[i]["Java_Script"].ToString();
                        int Control_Width = FunctionClassObj.StringToInt(dtFields.Rows[i]["Control_Width"].ToString());
                        int Control_Lines = FunctionClassObj.StringToInt(dtFields.Rows[i]["Control_Lines"].ToString());
                        int Field_Length = FunctionClassObj.StringToInt(dtFields.Rows[i]["Field_Length"].ToString());
                        bool editable = Convert.ToBoolean(dtFields.Rows[i]["Agent_Editable"].ToString());
                        bool AllowNull = Convert.ToBoolean(dtFields.Rows[i]["Allow_Null"].ToString());
                        string defaultValue = dtFields.Rows[i]["Default_Value"].ToString();
                        string Combo_Value = dtFields.Rows[i]["Combo_Value"].ToString();
                        bool by_Other_DB = Convert.ToBoolean(dtFields.Rows[i]["By_Other_DB"]);

                        Cell1 = new TableCell();
                        if (Field_Remarks != "" && Control_Type != "I-Frame")
                            Cell1.Text = Field_Remarks;
                        else
                            Cell1.Text = Field_Description;
                        if (!AllowNull)
                            Cell1.Text += "<font color=red>*</font>  :";
                        else
                            Cell1.Text += "  :";
                        Cell1.Font.Bold = true;
                        Cell1.Font.Size = Font_Size;
                        Cell1.HorizontalAlign = HorizontalAlign.Left;
                        if (Control_Type == "I-Frame" || Control_Type == "Html Editor")
                            Cell1.ColumnSpan = Control_Lines;
                        RowHeading.Cells.Add(Cell1);
                        #region field type phone number
                        if (Field_Type == "Phone No")
                        {
                            Cell1 = new TableCell();
                            Cell1.HorizontalAlign = HorizontalAlign.Left;
                            Cell1.VerticalAlign = VerticalAlign.Top;
                            TextBox1 = new TextBox();
                            TextBox1.ID = Field_Name;
                            TextBox1.Style["Position"] = "Static";
                            TextBox1.BorderColor = System.Drawing.Color.SteelBlue;
                            TextBox1.BorderStyle = BorderStyle.Solid;
                            //TextBox1.ForeColor = System.Drawing.Color.Red;
                            //TextBox1.BackColor = System.Drawing.Color.White;
                            TextBox1.BorderWidth = 1;
                            if (!editable)
                                TextBox1.ReadOnly = true;
                            else
                                TextBox1.ReadOnly = false;
                            //TextBox1.Enabled = editable;
                            if (Control_Width != 0)
                                TextBox1.Width = Control_Width;
                            TextBox1.MaxLength = 16;
                            TextBox1.Font.Size = Font_Size;
                            #region Database Binding Phone no
                            if (dtProcessMaster_Act.Rows.Count > 0 && tableType == "Master")
                                TextBox1.Text = dtProcessMaster_Act.Rows[0][Field_Name].ToString();
                            else if (dtProcessLogTemp.Rows.Count > 0 && tableType == "Log" && Request.QueryString["Log_Id"] != null)
                                TextBox1.Text = dtProcessLogTemp.Rows[0][Field_Name].ToString();
                            else
                                TextBox1.Text = defaultValue;
                            #endregion
                            Cell1.Controls.Add(TextBox1);
                            if (Session["LogId"] == null && Enable_Dial)
                            {
                                Button1 = new Button();
                                Button1.ID = "Dial" + Field_Name;
                                Button1.Text = "Dial";
                                #region database binding call button
                                //if (dtProcessMaster_Act.Rows.Count > 0 && tableType == "Master")
                                //    Button1.ToolTip = dtProcessMaster_Act.Rows[0][Field_Name].ToString();
                                //else if (dtProcessLogTemp.Rows.Count > 0 && tableType == "Log" && Request.QueryString["Log_Id"] != null)
                                //    Button1.ToolTip = dtProcessLogTemp.Rows[0][Field_Name].ToString();
                                //else
                                //    Button1.ToolTip = defaultValue;
                                #endregion
                                Button1.Style["Position"] = "Static";
                                Button1.Font.Bold = true;
                                Button1.BackColor = System.Drawing.Color.RoyalBlue;
                                Button1.BorderStyle = BorderStyle.None;
                                Button1.ForeColor = System.Drawing.Color.White;
                                Button1.Width = 35;
                                Button1.Click += new EventHandler(Dial_Click);
                                Cell1.Controls.Add(Button1);
                            }
                            Row1.Cells.Add(Cell1);
                        }
                        #endregion
                        #region field type Email
                        else if (Field_Type == "Email")
                        {
                            Cell1 = new TableCell();
                            Cell1.HorizontalAlign = HorizontalAlign.Left;
                            Cell1.VerticalAlign = VerticalAlign.Top;
                            TextBox1 = new TextBox();
                            TextBox1.ID = Field_Name;
                            TextBox1.Style["Position"] = "Static";
                            TextBox1.BorderColor = System.Drawing.Color.SteelBlue;
                            TextBox1.BorderStyle = BorderStyle.Solid;
                            //TextBox1.ForeColor = System.Drawing.Color.Red;
                            //TextBox1.BackColor = System.Drawing.Color.White;
                            TextBox1.BorderWidth = 1;
                            if (!editable)
                                TextBox1.ReadOnly = true;
                            else
                                TextBox1.ReadOnly = false;
                            //TextBox1.Enabled = editable;
                            TextBox1.Width = Control_Width;
                            TextBox1.MaxLength = 16;
                            TextBox1.Font.Size = Font_Size;
                            #region Database Binding Phone no
                            if (dtProcessMaster_Act.Rows.Count > 0 && tableType == "Master")
                                TextBox1.Text = dtProcessMaster_Act.Rows[0][Field_Name].ToString();
                            else if (dtProcessLogTemp.Rows.Count > 0 && tableType == "Log" && Request.QueryString["Log_Id"] != null)
                                TextBox1.Text = dtProcessLogTemp.Rows[0][Field_Name].ToString();
                            else
                                TextBox1.Text = defaultValue;
                            #endregion
                            Cell1.Controls.Add(TextBox1);
                            Row1.Cells.Add(Cell1);
                        }
                        #endregion
                        #region Control Type Html Editor
                        else if (Control_Type == "Html Editor")
                        {
                            Cell1 = new TableCell();
                            Cell1.HorizontalAlign = HorizontalAlign.Left;
                            Cell1.VerticalAlign = VerticalAlign.Top;
                            AjaxControlToolkit.HTMLEditor.Editor Editor1 = new AjaxControlToolkit.HTMLEditor.Editor();
                            Editor1.ID = Field_Name;
                            if (!editable)
                                Editor1.Enabled = true;
                            else
                                Editor1.Enabled = false;
                            Editor1.Width = Control_Width;
                            Editor1.Height = 250;
                            if (dtProcessMaster_Act.Rows.Count > 0 && tableType == "Master")
                                Editor1.Content = Server.HtmlDecode(dtProcessMaster_Act.Rows[0][Field_Name].ToString());
                            else if (dtProcessLogTemp.Rows.Count > 0 && tableType == "Log" && Request.QueryString["Log_Id"] != null)
                                Editor1.Content = Server.HtmlDecode(dtProcessLogTemp.Rows[0][Field_Name].ToString());
                            else
                                Editor1.Content = Server.HtmlDecode(defaultValue);
                            //Cell1.Controls.Add(Editor1);
                            //Row1.Cells.Add(Cell1);
                            Cell1 = new TableCell();
                            Cell1.HorizontalAlign = HorizontalAlign.Left;
                            Cell1.VerticalAlign = VerticalAlign.Top;
                            Cell1.Controls.Add(Editor1);
                            Cell1.ColumnSpan = Control_Lines;
                            Row1.Cells.Add(Cell1);
                        }
                        #endregion
                        #region Control type Hyper Link
                        else if (Control_Type == "Hyper Link")
                        {
                            Cell1 = new TableCell();
                            Cell1.HorizontalAlign = HorizontalAlign.Left;
                            Cell1.VerticalAlign = VerticalAlign.Top;
                            TextBox1 = new TextBox();
                            TextBox1.ID = Field_Name;
                            TextBox1.Style["Position"] = "Static";
                            TextBox1.BorderColor = System.Drawing.Color.SteelBlue;
                            TextBox1.BorderStyle = BorderStyle.Solid;
                            //TextBox1.ForeColor = System.Drawing.Color.Red;
                            //TextBox1.BackColor = System.Drawing.Color.White;
                            TextBox1.BorderWidth = 1;
                            if (!editable)
                                TextBox1.ReadOnly = true;
                            else
                                TextBox1.ReadOnly = false;
                            //TextBox1.Enabled = editable;
                            TextBox1.Width = Control_Width;
                            TextBox1.MaxLength = Field_Length;
                            TextBox1.Font.Size = Font_Size;
                            #region Database Binding Hyper Link
                            if (dtProcessMaster_Act.Rows.Count > 0 && tableType == "Master")
                                TextBox1.Text = dtProcessMaster_Act.Rows[0][Field_Name].ToString();
                            else if (dtProcessLogTemp.Rows.Count > 0 && tableType == "Log" && Request.QueryString["Log_Id"] != null)
                                TextBox1.Text = dtProcessLogTemp.Rows[0][Field_Name].ToString();
                            else
                                TextBox1.Text = defaultValue;
                            #endregion
                            Cell1.Controls.Add(TextBox1);
                            if (Session["LogId"] == null)
                            {
                                Button1 = new Button();
                                Button1.ID = "Open" + Field_Name;
                                Button1.Text = "Open";
                                Button1.Style["Position"] = "Static";
                                Button1.Font.Bold = true;
                                Button1.BackColor = System.Drawing.Color.RoyalBlue;
                                Button1.BorderStyle = BorderStyle.None;
                                Button1.ForeColor = System.Drawing.Color.White;
                                Button1.Width = 40;
                                Button1.Click += new EventHandler(Open_Click);
                                Cell1.Controls.Add(Button1);
                            }
                            Row1.Cells.Add(Cell1);
                        }
                        #endregion
                        #region Control type Label
                        else if (Control_Type == "Label")
                        {
                            Cell1 = new TableCell();
                            Cell1.HorizontalAlign = HorizontalAlign.Left;
                            Cell1.VerticalAlign = VerticalAlign.Top;
                            LabelSAN = new Label();
                            LabelSAN.ID = Field_Name;
                            LabelSAN.Style["Position"] = "Static";
                            TextBox1.Font.Size = Font_Size;
                            if (dtProcessMaster_Act.Rows.Count > 0 && tableType == "Master")
                                LabelSAN.Text = Server.HtmlDecode(dtProcessMaster_Act.Rows[0][Field_Name].ToString());
                            else if (dtProcessLogTemp.Rows.Count > 0 && tableType == "Log" && Request.QueryString["Log_Id"] != null)
                                LabelSAN.Text = Server.HtmlDecode(dtProcessLogTemp.Rows[0][Field_Name].ToString());
                            else
                                LabelSAN.Text = Server.HtmlDecode(defaultValue);
                            Cell1.Controls.Add(LabelSAN);
                            Row1.Cells.Add(Cell1);
                        }
                        #endregion
                        #region Control type text box
                        else if (Control_Type == "Text Box")
                        {
                            Cell1 = new TableCell();
                            Cell1.HorizontalAlign = HorizontalAlign.Left;
                            Cell1.VerticalAlign = VerticalAlign.Top;
                            TextBox1 = new TextBox();
                            TextBox1.ID = Field_Name;
                            TextBox1.Style["Position"] = "Static";
                            TextBox1.BorderColor = System.Drawing.Color.SteelBlue;
                            TextBox1.BorderStyle = BorderStyle.Solid;
                            TextBox1.BorderWidth = 1;
                            if (!editable)
                                TextBox1.ReadOnly = true;
                            else
                                TextBox1.ReadOnly = false;
                            //TextBox1.Enabled = editable;
                            TextBox1.MaxLength = Field_Length;
                            TextBox1.Font.Size = Font_Size;
                            //TextBox1.Font.Bold = true;
                            if (Control_Width != 0)
                                TextBox1.Width = Control_Width;
                            if (Control_Lines > 1)
                            {
                                TextBox1.TextMode = TextBoxMode.MultiLine;
                                TextBox1.Rows = Control_Lines;
                            }
                            if (dtProcessMaster_Act.Rows.Count > 0 && tableType == "Master")
                                TextBox1.Text = dtProcessMaster_Act.Rows[0][Field_Name].ToString();
                            else if (dtProcessLogTemp.Rows.Count > 0 && tableType == "Log" && Request.QueryString["Log_Id"] != null)
                                TextBox1.Text = dtProcessLogTemp.Rows[0][Field_Name].ToString();
                            else
                                TextBox1.Text = defaultValue;
                            Cell1.Controls.Add(TextBox1);
                            Row1.Cells.Add(Cell1);
                        }
                        #endregion
                        #region Control type combo box
                        //else if (Control_Type == "Combo Box" && Call_Status.Trim() == "0")
                        //{
                        else if (Control_Type == "Combo Box")
                        {
                            Cell1 = new TableCell();
                            Cell1.HorizontalAlign = HorizontalAlign.Left;
                            Cell1.VerticalAlign = VerticalAlign.Top;
                            DropDownList1 = new DropDownList();
                            DropDownList1.ID = Field_Name;
                            DropDownList1.ToolTip = tableType;
                            DropDownList1.Style["Position"] = "Static";
                            DropDownList1.BorderColor = System.Drawing.Color.SteelBlue;
                            DropDownList1.BorderStyle = BorderStyle.Solid;
                            DropDownList1.BorderWidth = 1;

                            DropDownList1.Enabled = editable;
                            DropDownList1.Font.Size = Font_Size;
                            if (Control_Lines == 2)
                            {
                                DropDownList1.SelectedIndexChanged += new EventHandler(DropDownList1_SelectedIndexChanged);
                                DropDownList1.AutoPostBack = true;
                            }
                            if (Control_Lines == 3)
                            {
                                DropDownList1.Attributes.Add("onchange", dtFields.Rows[i]["Java_Script"].ToString());
                            }
                            string strSelectedValue = "";
                            if (dtProcessMaster_Act.Rows.Count > 0 && tableType == "Master")
                                strSelectedValue = dtProcessMaster_Act.Rows[0][Field_Name].ToString();
                            else if (dtProcessLogTemp.Rows.Count > 0 && tableType == "Log" && Request.QueryString["Log_Id"] != null)
                                strSelectedValue = dtProcessLogTemp.Rows[0][Field_Name].ToString();
                            else
                                strSelectedValue = defaultValue;
                            strSelectedValue = strSelectedValue.Trim();
                            bool valueSelected = false;
                            if (by_Other_DB)
                            {
                                // For binding Control
                                if (Combo_Value.Contains("@@"))
                                {
                                    string pattern = "@@.*?.@@";
                                    MatchCollection matches = Regex.Matches(Combo_Value, pattern);
                                    foreach (Match match in matches)
                                    {
                                        try
                                        {
                                            string controlname = match.Value.Replace("@@", "");
                                            string controlType = Page.FindControl(controlname).GetType().ToString();
                                            if (controlType == "System.Web.UI.WebControls.TextBox")
                                            {
                                                TextBox txt = (TextBox)Page.FindControl(controlname);
                                                if (txt != null)
                                                    Combo_Value = Combo_Value.Replace(match.Value, "'" + txt.Text + "'");
                                            }
                                            else
                                            {
                                                DropDownList ddl = (DropDownList)Page.FindControl(controlname);
                                                Combo_Value = Combo_Value.Replace(match.Value, "'" + ddl.SelectedItem.Text + "'");
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            continue;
                                        }
                                    }
                                }
                                FunctionClassObj.BindDropDown(ref DropDownList1, Combo_Value);
                                DropDownList1.SelectedValue = strSelectedValue;
                                if (DropDownList1.SelectedValue == strSelectedValue)
                                    valueSelected = true;
                                else
                                {
                                    if (strSelectedValue != "" && valueSelected == false)
                                    {
                                        DropDownList1.Items.Add(strSelectedValue.Trim());
                                        valueSelected = true;
                                        DropDownList1.SelectedValue = strSelectedValue.Trim();
                                    }
                                }
                            }
                            else
                            {
                                string[] arrList = Combo_Value.Split(',');
                                DropDownList1.Items.Add("--Select--");
                                DropDownList1.Items[0].Value = "";
                                foreach (string value in arrList)
                                    DropDownList1.Items.Add(value.Trim());
                                foreach (string value in arrList)
                                {
                                    if (strSelectedValue == value)
                                    {
                                        DropDownList1.SelectedValue = strSelectedValue;
                                        valueSelected = true;
                                        break;
                                    }
                                }
                                if (strSelectedValue != "" && valueSelected == false)
                                {
                                    DropDownList1.Items.Add(strSelectedValue.Trim());
                                    valueSelected = true;
                                    DropDownList1.SelectedValue = strSelectedValue.Trim();
                                }
                            }
                            if (!valueSelected)
                                Cell1.Text = strSelectedValue;
                            // DropDownList1.Attributes.Add("onchange", "<script language=\"javascript\" type=\"text/javascript\">function fn1(){" + javaScript + "} </script>");
                            //if (Field_Name == "AddressType")
                            //    DropDownList1.Attributes.Add("onchange", "javascript:if(this.value == 'Alternate') { document.getElementById('Address').value = ''; document.getElementById('Address').value = document.getElementById('alter_address').value;} else if(this.value == 'Address') {document.getElementById('Address').value = ''; document.getElementById('Address').value = document.getElementById('resi_address').value;} else document.getElementById('Address').value = '';");
                            Cell1.Controls.Add(DropDownList1);
                            Row1.Cells.Add(Cell1);
                        }
                        #endregion
                        #region Control type list box
                        //else if (Control_Type == "List Box" && Call_Status.Trim() == "0")
                        //{
                        else if (Control_Type == "List Box")
                        {
                            Cell1 = new TableCell();
                            Cell1.HorizontalAlign = HorizontalAlign.Left;
                            Cell1.VerticalAlign = VerticalAlign.Top;
                            ListBox1 = new ListBox();
                            ListBox1.ID = Field_Name;
                            ListBox1.Style["Position"] = "Static";
                            ListBox1.BorderColor = System.Drawing.Color.SteelBlue;
                            ListBox1.BorderStyle = BorderStyle.Solid;
                            ListBox1.BorderWidth = 1;
                            ListBox1.Enabled = editable;
                            ListBox1.Font.Size = Font_Size;
                            string strSelectedValue = "";
                            if (dtProcessMaster_Act.Rows.Count > 0 && tableType == "Master")
                                strSelectedValue = dtProcessMaster_Act.Rows[0][Field_Name].ToString();
                            else if (dtProcessLogTemp.Rows.Count > 0 && tableType == "Log" && Request.QueryString["Log_Id"] != null)
                                strSelectedValue = dtProcessLogTemp.Rows[0][Field_Name].ToString();
                            else
                                strSelectedValue = defaultValue;
                            bool valueSelected = false;
                            if (by_Other_DB)
                            {
                                FunctionClassObj.BindListBox(ref ListBox1, Combo_Value);
                                ListBox1.SelectedValue = strSelectedValue;
                                if (ListBox1.SelectedValue == strSelectedValue)
                                    valueSelected = true;
                                else
                                {
                                    if (strSelectedValue != "" && valueSelected == false)
                                    {
                                        ListBox1.Items.Add(strSelectedValue.Trim());
                                        valueSelected = true;
                                        ListBox1.SelectedValue = strSelectedValue.Trim();
                                    }
                                }
                            }
                            else
                            {
                                string[] arrList = Combo_Value.Split(',');
                                foreach (string value in arrList)
                                    ListBox1.Items.Add(value);
                                foreach (string value in arrList)
                                {
                                    if (strSelectedValue == value)
                                    {
                                        ListBox1.SelectedValue = strSelectedValue;
                                        valueSelected = true;
                                        break;
                                    }
                                }
                                if (strSelectedValue != "" && valueSelected == false)
                                {
                                    DropDownList1.Items.Add(strSelectedValue.Trim());
                                    valueSelected = true;
                                    DropDownList1.SelectedValue = strSelectedValue.Trim();
                                }
                            }
                            Cell1.Controls.Add(ListBox1);
                            Row1.Cells.Add(Cell1);
                        }
                        #endregion
                        #region Control type redio button
                        //else if (Control_Type == "Radio Button" && Call_Status.Trim() == "0")
                        //{
                        else if (Control_Type == "Radio Button")
                        {
                            Cell1 = new TableCell();
                            Cell1.HorizontalAlign = HorizontalAlign.Left;
                            Cell1.VerticalAlign = VerticalAlign.Top;
                            RadioButtonList1 = new RadioButtonList();
                            RadioButtonList1.ID = Field_Name;
                            RadioButtonList1.Style["Position"] = "Static";
                            RadioButtonList1.BorderColor = System.Drawing.Color.SteelBlue;
                            RadioButtonList1.BorderStyle = BorderStyle.Solid;
                            RadioButtonList1.BorderWidth = 1;
                            RadioButtonList1.Enabled = editable;
                            RadioButtonList1.Font.Size = Font_Size;
                            if (Control_Lines == 2)
                            {
                                RadioButtonList1.RepeatDirection = RepeatDirection.Horizontal;
                                //RadioButtonList1.RepeatColumns = Control_Lines * 2;
                            }
                            string[] arrList = Combo_Value.Split(',');
                            foreach (string value in arrList)
                                RadioButtonList1.Items.Add(value);
                            string strSelectedValue = "";
                            if (dtProcessMaster_Act.Rows.Count > 0 && tableType == "Master")
                                strSelectedValue = dtProcessMaster_Act.Rows[0][Field_Name].ToString();
                            else if (dtProcessLogTemp.Rows.Count > 0 && tableType == "Log" && Request.QueryString["Log_Id"] != null)
                                strSelectedValue = dtProcessLogTemp.Rows[0][Field_Name].ToString();
                            else
                                strSelectedValue = defaultValue;
                            foreach (string value in arrList)
                            {
                                if (strSelectedValue == value)
                                {
                                    RadioButtonList1.SelectedValue = strSelectedValue;
                                    break;
                                }
                            }
                            Cell1.Controls.Add(RadioButtonList1);
                            Row1.Cells.Add(Cell1);

                        }
                        #endregion
                        #region Control type check box
                        //else if (Control_Type == "Check Box" && Call_Status.Trim() == "0")
                        //{
                        else if (Control_Type == "Check Box")
                        {
                            Cell1 = new TableCell();
                            Cell1.HorizontalAlign = HorizontalAlign.Left;
                            Cell1.VerticalAlign = VerticalAlign.Top;
                            CheckBox1 = new CheckBox();
                            CheckBox1.ID = Field_Name;
                            CheckBox1.Style["Position"] = "Static";
                            CheckBox1.Enabled = editable;
                            CheckBox1.Font.Size = Font_Size;
                            if (dtProcessMaster_Act.Rows.Count > 0 && tableType == "Master")
                                CheckBox1.Checked = Convert.ToBoolean(dtProcessMaster_Act.Rows[0][Field_Name].ToString());
                            else if (dtProcessLogTemp.Rows.Count > 0 && tableType == "Master")
                                CheckBox1.Checked = Convert.ToBoolean(dtProcessLogTemp.Rows[0][Field_Name].ToString());
                            else
                            {
                                if (defaultValue == "0")
                                    CheckBox1.Checked = false;
                                else if (defaultValue == "1")
                                    CheckBox1.Checked = true;
                            }
                            Cell1.Controls.Add(CheckBox1);
                            Row1.Cells.Add(Cell1);
                        }
                        #endregion
                        #region Control type i-frame
                        //else if (Control_Type == "I-Frame" && Call_Status.Trim() == "0")
                        //{
                        else if (Control_Type == "I-Frame")
                        {
                            myFrame = new HtmlGenericControl("iframe");
                            myFrame.ID = Field_Description;
                            if (dtProcessMaster_Act.Rows.Count > 0 && tableType == "Master")
                            {
                                for (int iProcess = 0; iProcess < dtProcessMaster_Act.Columns.Count; iProcess++)
                                {
                                    Field_Remarks = Field_Remarks.ToLower().Replace("@" + dtProcessMaster_Act.Columns[iProcess].ColumnName.ToLower() + "@", dtProcessMaster_Act.Rows[0][dtProcessMaster_Act.Columns[iProcess]].ToString());
                                }
                            }
                            myFrame.Attributes.Add("src", Field_Remarks);
                            if (Control_Width == 0)
                                myFrame.Attributes.Add("Width", "200");
                            else
                                myFrame.Attributes.Add("Width", Control_Width.ToString());
                            if (Field_Length == 0)
                                myFrame.Attributes.Add("Height", "200");
                            else
                                myFrame.Attributes.Add("Height", Field_Length.ToString());
                            Cell1 = new TableCell();
                            Cell1.HorizontalAlign = HorizontalAlign.Left;
                            Cell1.VerticalAlign = VerticalAlign.Top;
                            Cell1.Controls.Add(myFrame);
                            Cell1.ColumnSpan = Control_Lines;
                            Row1.Cells.Add(Cell1);
                        }
                        #endregion
                        #region Control type date time picker
                        //else if (Control_Type == "Date Time Picker" && Call_Status.Trim() == "0")
                        //{
                        else if (Control_Type == "Date Time Picker")
                        {
                            Cell1 = new TableCell();
                            Cell1.HorizontalAlign = HorizontalAlign.Left;
                            Cell1.VerticalAlign = VerticalAlign.Top;
                            TextBox1 = new TextBox();
                            TextBox1.ID = Field_Name;
                            TextBox1.Style["Position"] = "Static";
                            TextBox1.BorderColor = System.Drawing.Color.SteelBlue;
                            TextBox1.BorderStyle = BorderStyle.Solid;
                            TextBox1.BorderWidth = 1;
                            if (!editable)
                                TextBox1.ReadOnly = true;
                            else
                                TextBox1.ReadOnly = false;
                            //TextBox1.Enabled = editable;
                            TextBox1.Font.Size = Font_Size;
                            if (dtProcessMaster_Act.Rows.Count > 0 && tableType == "Master")
                            {
                                if (dtProcessMaster_Act.Rows[0][Field_Name].ToString() == "")
                                    TextBox1.Text = "";
                                else
                                {
                                    string date = dtProcessMaster_Act.Rows[0][Field_Name].ToString().Substring(0, 10);
                                    if (date.IndexOf(' ') > 0)
                                        date = date.Substring(0, date.IndexOf(' '));
                                    string[] datesplit = new string[3];
                                    datesplit = date.Split('/');
                                    TextBox1.Text = datesplit[1] + "/" + datesplit[0] + "/" + datesplit[2];
                                }
                            }
                            else if (dtProcessLogTemp.Rows.Count > 0 && tableType == "Log")
                            {
                                if (dtProcessLogTemp.Rows[0][Field_Name].ToString() == "")
                                    TextBox1.Text = "";
                                else
                                {
                                    string date = dtProcessLogTemp.Rows[0][Field_Name].ToString().Substring(0, 10);
                                    if (date.IndexOf(' ') > 0)
                                        date = date.Substring(0, date.IndexOf(' '));
                                    string[] datesplit = new string[3];
                                    datesplit = date.Split('/');
                                    TextBox1.Text = datesplit[1] + "/" + datesplit[0] + "/" + datesplit[2];
                                }
                            }
                            else
                            {
                                if (defaultValue != "")
                                {
                                    string[] datesplit;
                                    datesplit = defaultValue.Split('/');
                                    TextBox1.Text = datesplit[1] + "/" + datesplit[0] + "/" + datesplit[2];
                                }
                            }
                            Cell1.Controls.Add(TextBox1);
                            #region AJAX Calender
                            if (editable)
                            {
                                AjaxControlToolkit.CalendarExtender calender1 = new AjaxControlToolkit.CalendarExtender();
                                calender1.ID = "Calender_" + Field_Name;
                                calender1.Enabled = true;
                                calender1.Format = "dd/MM/yyyy";
                                calender1.TargetControlID = Field_Name;
                                UpdatePanel1.ContentTemplateContainer.Controls.Add(calender1);
                            }
                            #endregion
                            //TextBox1.Attributes.Add("onClick", "showCalendarControl(this)");
                            Row1.Cells.Add(Cell1);
                        }
                        #endregion
                    }
                    Table1.Rows.Add(RowHeading);
                    Table1.Rows.Add(Row1);
                    l1 = l1 + l;
                    if (l2 + l <= dtFields.Rows.Count)
                        l2 = l2 + l;
                    else
                        l2 = dtFields.Rows.Count;
                }
            }
        }
        paraPlaceHolder.Controls.Add(Table1);
    }
    public void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList ddlSender = (DropDownList)sender;
        string By_Other_DB = FunctionClassObj.ExecuteScalarString("Select By_Other_DB FROM Process_" + ddlSender.ToolTip.ToString() + " Where Pid = '" + lblprocessid.Text + "' AND Field_Name = '" + ddlSender.ID + "'");
        string java_script = FunctionClassObj.ExecuteScalarString("SELECT Java_Script FROM Process_" + ddlSender.ToolTip.ToString() + " WHERE Pid = '" + lblprocessid.Text + "' AND Field_Name = '" + ddlSender.ID + "'");
        string[] SubControl = java_script.Split('#');
        string Combo_Value = FunctionClassObj.ExecuteScalarString("SELECT Combo_Value FROM Process_" + ddlSender.ToolTip.ToString() + " WHERE Pid = '" + lblprocessid.Text + "' AND Field_Name = '" + SubControl[0].ToString() + "'");
        string SubControlName = SubControl[0].ToString();
        string SubControlType = Page.FindControl(SubControlName).GetType().ToString();
        if (SubControlType == "System.Web.UI.WebControls.TextBox")
        {
            TextBox txtBox = (TextBox)Page.FindControl(SubControlName);
            if (txtBox != null)
            {
                string sSQlQuery = SubControl[1].ToString().Replace("[Condition]", "'" + ddlSender.SelectedValue + "'").Replace("''", "'");
                if (sSQlQuery.Contains("@@"))
                {
                    string pattern = "@@.*?.@@";
                    MatchCollection matches = Regex.Matches(sSQlQuery, pattern);
                    foreach (Match match in matches)
                    {
                        string controlname = match.Value.Replace("@@", "");
                        string controlType = Page.FindControl(controlname).GetType().ToString();
                        if (controlType == "System.Web.UI.WebControls.TextBox")
                        {
                            TextBox txt = (TextBox)Page.FindControl(controlname);
                            if (txt != null)
                                sSQlQuery = sSQlQuery.Replace(match.Value, "'" + txt.Text + "'");
                        }
                        else
                        {
                            DropDownList ddl = (DropDownList)Page.FindControl(controlname);
                            sSQlQuery = sSQlQuery.Replace(match.Value, "'" + ddl.SelectedItem.Text + "'");
                        }
                    }
                }
                txtBox.Text = FunctionClassObj.ExecuteScalarString(sSQlQuery);
            }
        }
        else
        {
            DropDownList1 = (DropDownList)PlaceHolder_Log.FindControl(SubControl[0].ToString());
            if (!Convert.ToBoolean(By_Other_DB))
            {
                string[] arrList = Combo_Value.Split(',');
                while (DropDownList1.Items.Count > 0)
                    DropDownList1.Items.RemoveAt(0);
                DropDownList1.Items.Add("--Select--");
                DropDownList1.Items[0].Value = "";
                foreach (string value in arrList)
                {
                    string[] arrList1 = value.Split('-');
                    if (arrList1[0].ToLower().Trim() == ddlSender.SelectedValue.ToLower().Trim())
                        DropDownList1.Items.Add(arrList1[1].Trim());
                }
            }
            else
            {
                if (ddlSender.SelectedIndex != 0)
                {
                    string selectedValue = DropDownList1.SelectedValue;
                    DropDownList1.Items.Clear();
                    DropDownList1.AppendDataBoundItems = true;
                    DropDownList1.Items.Add("--Select--");
                    DropDownList1.Items[0].Value = selectedValue;
                    string sSQlQuery = SubControl[1].ToString().Replace("[Condition]", "'" + ddlSender.SelectedValue + "'").Replace("''", "'");
                    if (sSQlQuery.Contains("@@"))
                    {
                        string pattern = "@@.*?.@@";
                        MatchCollection matches = Regex.Matches(sSQlQuery, pattern);
                        foreach (Match match in matches)
                        {
                            string controlname = match.Value.Replace("@@", ""); //Combo_Value.Substring(Combo_Value.IndexOf("#$") + 2, Combo_Value.IndexOf("$#") - Combo_Value.IndexOf("#$") - 2);
                            string controlType = Page.FindControl(controlname).GetType().ToString();
                            if (controlType == "System.Web.UI.WebControls.TextBox")
                            {
                                TextBox txt = (TextBox)Page.FindControl(controlname);
                                if (txt != null)
                                    sSQlQuery = sSQlQuery.Replace(match.Value, "'" + txt.Text + "'");
                            }
                            else
                            {
                                DropDownList ddl = (DropDownList)Page.FindControl(controlname);
                                sSQlQuery = sSQlQuery.Replace(match.Value, "'" + ddl.SelectedItem.Text + "'");
                            }
                        }
                    }
                    dtTemp = FunctionClassObj.GetData(sSQlQuery);
                    DropDownList1.DataSource = dtTemp;
                    DropDownList1.DataTextField = dtTemp.Columns[1].ToString();
                    DropDownList1.DataValueField = dtTemp.Columns[0].ToString();
                    try
                    {
                        DropDownList1.DataBind();
                    }
                    catch (Exception ex)
                    {

                    }
                }
                else
                {
                    DropDownList1.Items.Clear();
                    DropDownList1.Items.Add("--Select--");
                    DropDownList1.Items[0].Value = "";
                }
            }
        }
    }
    public void GetSearchFields(DataTable paraDt, int l, int Font_Size)
    {
        int l1, l2, max;
        Table Table1 = new Table();
        Table1.Style["class"] = "border";
        //Table1.Style["width"] = "100%";
        Table1.CellPadding = 1;
        Table1.CellSpacing = 0;
        Table1.BorderWidth = 0;
        TableRow Row1, RowHeading;
        TableCell Cell1;
        Row1 = new TableRow();
        RowHeading = new TableRow();
        #region Master ID
        Cell1 = new TableCell();
        Cell1.Text = "Master ID :";
        Cell1.Font.Bold = true;
        Cell1.HorizontalAlign = HorizontalAlign.Left;
        Cell1.Font.Size = Font_Size;
        RowHeading.Cells.Add(Cell1);
        Cell1 = new TableCell();
        Cell1.HorizontalAlign = HorizontalAlign.Left;
        Cell1.VerticalAlign = VerticalAlign.Top;
        TextBox1 = new TextBox();
        TextBox1.ID = "Search_Master_Id";
        TextBox1.Style["Position"] = "Static";
        TextBox1.BorderColor = System.Drawing.Color.SteelBlue;
        TextBox1.BorderStyle = BorderStyle.Solid;
        TextBox1.Font.Size = Font_Size;
        TextBox1.BorderWidth = 1;
        Row1.Cells.Add(Cell1);
        Cell1.Controls.Add(TextBox1);
        Table1.Rows.Add(RowHeading);
        Table1.Rows.Add(Row1);
        #endregion
        #region Phone No
        Cell1 = new TableCell();
        Cell1.Text = "Phone No :";
        Cell1.Font.Bold = true;
        Cell1.HorizontalAlign = HorizontalAlign.Left;
        Cell1.Font.Size = Font_Size;
        RowHeading.Cells.Add(Cell1);
        Cell1 = new TableCell();
        Cell1.HorizontalAlign = HorizontalAlign.Left;
        Cell1.VerticalAlign = VerticalAlign.Top;
        TextBox1 = new TextBox();
        TextBox1.ID = "Search_Phone_No";
        TextBox1.Style["Position"] = "Static";
        TextBox1.BorderColor = System.Drawing.Color.SteelBlue;
        TextBox1.BorderStyle = BorderStyle.Solid;
        TextBox1.Font.Size = Font_Size;
        TextBox1.BorderWidth = 1;
        Row1.Cells.Add(Cell1);
        Cell1.Controls.Add(TextBox1);
        Table1.Rows.Add(RowHeading);
        Table1.Rows.Add(Row1);
        #endregion
        l1 = 0;
        if (paraDt.Rows.Count < l)
            max = l2 = paraDt.Rows.Count;
        else
        {
            l2 = l;
            max = ((paraDt.Rows.Count) / l);
            if (((paraDt.Rows.Count) % l) != 0)
                max++;
        }
        for (int k = 0; k < max; k++)
        {
            Row1 = new TableRow();
            RowHeading = new TableRow();
            for (int i = l1; i < l2; i++)
            {
                string Field_Description = paraDt.Rows[i]["Field_Description"].ToString();
                string Field_Name = "Search_" + paraDt.Rows[i]["Field_Name"].ToString();
                string Control_Type = paraDt.Rows[i]["Control_Type"].ToString();
                int Control_Width = FunctionClassObj.StringToInt(paraDt.Rows[i]["Control_Width"].ToString());
                int Control_Lines = FunctionClassObj.StringToInt(paraDt.Rows[i]["Control_Lines"].ToString());
                bool editable = Convert.ToBoolean(paraDt.Rows[i]["Agent_Editable"].ToString());
                string defaultValue = paraDt.Rows[i]["Default_Value"].ToString();
                string Combo_Value = paraDt.Rows[i]["Combo_Value"].ToString();
                string Field_Type = paraDt.Rows[i]["Field_Type"].ToString();
                bool by_Other_DB = Convert.ToBoolean(paraDt.Rows[i]["By_Other_DB"]);
                Cell1 = new TableCell();
                Cell1.Text = Field_Description + ":";
                Cell1.Font.Bold = true;
                Cell1.Font.Size = Font_Size;
                Cell1.HorizontalAlign = HorizontalAlign.Left;
                RowHeading.Cells.Add(Cell1);
                Cell1 = new TableCell();
                Cell1.HorizontalAlign = HorizontalAlign.Left;
                Cell1.VerticalAlign = VerticalAlign.Top;
                if (Field_Type == "Decimal")
                {
                    #region Decimal
                    //label1 = new Label();
                    //label1.Text = " From : ";
                    //label1.Font.Bold = true;
                    //Cell1.Controls.Add(label1);
                    TextBox1 = new TextBox();
                    TextBox1.ID = "From_" + Field_Name;
                    TextBox1.BorderColor = System.Drawing.Color.SteelBlue;
                    TextBox1.BorderStyle = BorderStyle.Solid;
                    TextBox1.BorderWidth = 1;
                    TextBox1.Width = 50;
                    TextBox1.ToolTip = "From";
                    TextBox1.Font.Size = Font_Size;
                    Cell1.Controls.Add(TextBox1);
                    //label1 = new Label();
                    //label1.Text = " To : ";
                    //label1.Font.Bold = true;
                    //Cell1.Controls.Add(label1);
                    TextBox1 = new TextBox();
                    TextBox1.ID = "To_" + Field_Name;
                    TextBox1.BorderColor = System.Drawing.Color.SteelBlue;
                    TextBox1.BorderStyle = BorderStyle.Solid;
                    TextBox1.BorderWidth = 1;
                    TextBox1.Width = 50;
                    TextBox1.ToolTip = "To";
                    TextBox1.Font.Size = Font_Size;
                    Cell1.Controls.Add(TextBox1);
                    Row1.Cells.Add(Cell1);
                    #endregion
                }
                else
                {
                    if (Control_Type == "Text Box")
                    {
                        TextBox1 = new TextBox();
                        TextBox1.ID = Field_Name;
                        TextBox1.Style["Position"] = "Static";
                        TextBox1.BorderColor = System.Drawing.Color.SteelBlue;
                        TextBox1.BorderStyle = BorderStyle.Solid;
                        TextBox1.BorderWidth = 1;
                        TextBox1.Font.Size = Font_Size;
                        Cell1.Controls.Add(TextBox1);
                    }
                    else if (Control_Type == "Combo Box")
                    {
                        DropDownList1 = new DropDownList();
                        DropDownList1.ID = Field_Name;
                        DropDownList1.Style["Position"] = "Static";
                        DropDownList1.BorderColor = System.Drawing.Color.SteelBlue;
                        DropDownList1.BorderStyle = BorderStyle.Solid;
                        DropDownList1.BorderWidth = 1;
                        DropDownList1.Font.Size = Font_Size;
                        if (by_Other_DB)
                            FunctionClassObj.BindDropDown(ref DropDownList1, Combo_Value);
                        else
                        {
                            string[] arrList = Combo_Value.Split(',');
                            DropDownList1.Items.Add("--Select--");
                            DropDownList1.Items[0].Value = "";
                            foreach (string value in arrList)
                                DropDownList1.Items.Add(value);
                        }
                        Cell1.Controls.Add(DropDownList1);
                    }
                    else if (Control_Type == "List Box")
                    {
                        ListBox1 = new ListBox();
                        ListBox1.ID = Field_Name;
                        ListBox1.Style["Position"] = "Static";
                        ListBox1.BorderColor = System.Drawing.Color.SteelBlue;
                        ListBox1.BorderStyle = BorderStyle.Solid;
                        ListBox1.BorderWidth = 1;
                        ListBox1.Font.Size = Font_Size;
                        if (by_Other_DB)
                            FunctionClassObj.BindListBox(ref ListBox1, Combo_Value);
                        else
                        {
                            string[] arrList = Combo_Value.Split(',');
                            foreach (string value in arrList)
                                ListBox1.Items.Add(value);
                        }
                        Cell1.Controls.Add(ListBox1);
                    }
                    else if (Control_Type == "Radio Button")
                    {
                        RadioButtonList1 = new RadioButtonList();
                        RadioButtonList1.ID = Field_Name;
                        RadioButtonList1.Style["Position"] = "Static";
                        RadioButtonList1.BorderColor = System.Drawing.Color.SteelBlue;
                        RadioButtonList1.BorderStyle = BorderStyle.Solid;
                        RadioButtonList1.BorderWidth = 1;
                        RadioButtonList1.Font.Size = Font_Size;
                        string[] arrList = Combo_Value.Split(',');
                        foreach (string value in arrList)
                            RadioButtonList1.Items.Add(value);
                        RadioButtonList1.Items[0].Selected = true;
                        Cell1.Controls.Add(RadioButtonList1);
                    }
                    else if (Control_Type == "Check Box")
                    {
                        CheckBox1 = new CheckBox();
                        CheckBox1.ID = Field_Name;
                        CheckBox1.Style["Position"] = "Static";
                        CheckBox1.Font.Size = Font_Size;
                        Cell1.Controls.Add(CheckBox1);
                    }
                    else if (Control_Type == "Date Time Picker")
                    {
                        TextBox1 = new TextBox();
                        TextBox1.ID = Field_Name;
                        TextBox1.Style["Position"] = "Static";
                        TextBox1.BorderColor = System.Drawing.Color.SteelBlue;
                        TextBox1.BorderStyle = BorderStyle.Solid;
                        TextBox1.BorderWidth = 1;
                        TextBox1.Font.Size = Font_Size;
                        Cell1.Controls.Add(TextBox1);
                        //TextBox1.Attributes.Add("onClick", "showCalendarControl(this)");
                        #region AJAX Calender
                        AjaxControlToolkit.CalendarExtender calender1 = new AjaxControlToolkit.CalendarExtender();
                        calender1.ID = "Calender_" + Field_Name;
                        calender1.Enabled = true;
                        calender1.Format = "dd/MM/yyyy";
                        calender1.TargetControlID = Field_Name;
                        Cell1.Controls.Add(calender1);
                        //UpdatePanel1.ContentTemplateContainer.Controls.Add(calender1);
                        #endregion
                    }
                    Row1.Cells.Add(Cell1);
                }
            }
            Table1.Rows.Add(RowHeading);
            Table1.Rows.Add(Row1);
            l1 = l1 + l;
            if (l2 + l <= paraDt.Rows.Count)
                l2 = l2 + l;
            else
                l2 = paraDt.Rows.Count;
        }
        PlaceHolder1.Controls.Add(Table1);
    }
    protected void btnStop_Click(object sender, EventArgs e)
    {
        if (Session["Phone_No"] == null || lblCallMode.Text == "alternateno")
        {
            Session["Phone_No"] = Session["SrNo"] = Session["CallBackPhoneNo"] = Session["CallBackTime"] = Session["CallAgainType"] =
Session["dialerincoming"] = null;
            FunctionClassObj.ExecuteCommand("UPDATE Admin_Extention_Master SET Caller_Id = NULL,Called_No = NULL,Unique_Id = NULL,SrNo = 0 WHERE Extention_No = '" + txtExtensionNo.Text + "'");
            Response.Redirect("CallWaiting.aspx", true);
        }
    }
    public bool savemycall()
    {
        if (ViewState["dtProcessMaster"] != null)
            dtProcessMaster = (DataTable)ViewState["dtProcessMaster"];
        else
            dtProcessMaster = FunctionClassObj.GetData("SELECT * FROM Process_Master WHERE Pid = " + lblprocessid.Text + " AND Agent_Visible = 1 ORDER BY Order_No");

        if (ViewState["dtProcessLog"] != null)
            dtProcessLog = (DataTable)ViewState["dtProcessLog"];
        else
            dtProcessLog = FunctionClassObj.GetData("SELECT * FROM Process_Log WHERE pid = " + lblprocessid.Text + " ORDER BY Order_No");

        if (FunctionClassObj.ExecuteScalar("SELECT Count(Duplicate_No_In_Process) FROM Process WHERE Duplicate_No_In_Process = 0 AND Pid = " + lblprocessid.Text) > 0 && FunctionClassObj.ExecuteScalar("SELECT Count(Master_Id) FROM Process_" + lblprocessid.Text + "_Master WHERE Phone_No = '" + Phone_No.Text + "' AND Master_Id != '" + Master_Id.Text + "'") > 0)
        {
            DisplayMessage("Phone No already Exists.");
            Phone_No.Focus();
            return false;
        }
        if (FunctionClassObj.ExecuteScalarString("SELECT IsSetCallBack FROM CallStatus WHERE pid = " + lblprocessid.Text + " AND Call_Status = '" + ddlCallStatus.SelectedValue + "'").ToLower() == "true" && string.IsNullOrEmpty(txtCallBackDate.Text.Trim()))
        {
            DisplayMessage("Call Back Date is can not be left blank.");
            txtCallBackDate.Focus();
            return false;
        }
        if (!string.IsNullOrEmpty(txtCallBackDate.Text.Trim()) && (FunctionClassObj.IsDate(txtCallBackDate.Text.Trim()) == false))
        {
            DisplayMessage("Call Back Date is not in valid format.");
            txtCallBackDate.Focus();
            return false;
        }
        if (!string.IsNullOrEmpty(txtCallBackDate.Text.Trim()))
        {
            DataTable dtCampaignDetails = FunctionClassObj.GetData("SELECT From_Hrs,To_Hrs FROM Campaign_Master WHERE Campaign_Id =" + lblCampaignId.Text);
            if (dtCampaignDetails.Rows.Count > 0)
            {
                int CallBackMins = (FunctionClassObj.StringToInt(callbacktimeHr.SelectedValue) * 60) + FunctionClassObj.StringToInt(callbacktimeMm.SelectedValue);
                int CampaignFromMin = (FunctionClassObj.StringToInt(FunctionClassObj.TimeToHr(dtCampaignDetails.Rows[0][0].ToString())) * 60) + FunctionClassObj.StringToInt(FunctionClassObj.TimeToMM(dtCampaignDetails.Rows[0][0].ToString()));
                int CampaignToMin = (FunctionClassObj.StringToInt(FunctionClassObj.TimeToHr(dtCampaignDetails.Rows[0][1].ToString())) * 60) + FunctionClassObj.StringToInt(FunctionClassObj.TimeToMM(dtCampaignDetails.Rows[0][1].ToString()));
                if (CallBackMins < CampaignFromMin || CallBackMins > CampaignToMin)
                {
                    DisplayMessage("Call Back time should be from " + dtCampaignDetails.Rows[0][0].ToString() + " to " + dtCampaignDetails.Rows[0][1].ToString() + ".");
                    callbacktimeHr.Focus();
                    return false;
                }
            }
        }
        if (Convert.ToBoolean(FunctionClassObj.ExecuteScalarString("Select IsBranch_Mandatory From Process Where PId='" + lblprocessid.Text + "'")) && SANBranch_Master.SelectedIndex == 0)
        {
            DisplayMessage("Branch Name Required.");
            SANBranch_Master.Focus();
            return false;
        }
        if (!SaveCheck(dtProcessMaster, PlaceHolder_Master) || !SaveCheck(dtProcessLog, PlaceHolder_Log))
            return false;
        else
        {
            SaveUpadteData(dtProcessMaster, PlaceHolder_Master, "Master");
            if (IsDoNotCall.Visible && IsDoNotCall.Checked)
                FunctionClassObj.ExecuteCommand("UPDATE Process_" + lblprocessid.Text + "_Master SET IsDNC = 1 WHERE Master_Id = " + Master_Id.Text);
            else
                FunctionClassObj.ExecuteCommand("UPDATE Process_" + lblprocessid.Text + "_Master SET IsDNC = 0 WHERE Master_Id = " + Master_Id.Text);
            if (FunctionClassObj.StringToInt(lblSrNo.Text) == 0)
                Session["SrNo"] = lblSrNo.Text = FunctionClassObj.getCampaignSrNo(FunctionClassObj.StringToInt(Master_Id.Text), FunctionClassObj.StringToInt(lblprocessid.Text), FunctionClassObj.StringToInt(lblCampaignId.Text), 1).ToString();
            //FunctionClassObj.ExecuteScalar("getSrNo @CustomerId = " + Master_Id.Text + ",@CampaignId = " + lblCampaignId.Text + ",@FileId = 1").ToString();
            SaveUpadteData(dtProcessLog, PlaceHolder_Log, "Log");
            if (FunctionClassObj.StringToInt(lblLogId.Text) > 0)
                FunctionClassObj.ExecuteCommand("UPDATE Campaign_" + lblprocessid.Text + "_Mapping SET Last_Log_Id = " + lblLogId.Text + " WHERE Customer_Id = " + Master_Id.Text);
            #region Send master and log table fields  to email id provided in Call Dispostion Form
            if (!string.IsNullOrEmpty(lblEmailId.Text))
            {
                SendByEmail(dtProcessMaster, dtProcessLog);
                lblEmailId.Text = string.Empty;
            }
            #endregion
            #region Send Sms
            SendSMS();
            #endregion
            if (FunctionClassObj.ExecuteScalarString("SELECT No_Did_SMS FROM CallStatus WHERE Call_Status = '" + ddlCallStatus.SelectedValue + "' AND Pid = " + lblprocessid.Text).ToLower() != "true")
            {
                #region Send DID SMS
                if (lblDIDMobile_No.Text != "")
                    SendDIDSMS();
                #endregion
                #region Send DID Email
                if (!string.IsNullOrEmpty(lblEmail_Id.Text) && FunctionClassObj.StringToInt(lblAccount_Id.Text) > 0 && FunctionClassObj.StringToInt(lblEmailTemplate_Id.Text) > 0)
                    SendDIDEmail();
                #endregion
            }
            #region Send Email
            SendEmail();
            #endregion
            if (Session["Extention_No"] != null)
                FunctionClassObj.ExecuteCommand("UPDATE Admin_Extention_Master SET Last_Time = GETDATE() WHERE Agent_Name = '" + lblagentName.Text + "' AND Extention_No = '" + txtExtensionNo.Text + "'");
            //Callback
            if (string.IsNullOrEmpty(txtCallBackDate.Text.Trim()))
                SetAutoCallBack();
            if (!string.IsNullOrEmpty(txtCallBackDate.Text.Trim()))
            {
                if (string.IsNullOrEmpty(Call_Again_PhoneNo.Text.Trim()))
                    Call_Again_PhoneNo.Text = Phone_No.Text.Trim();
                if (!Convert.ToBoolean(FunctionClassObj.ExecuteScalarString("if Exists(SELECT SetCallBackNotRequired FROM CallStatus WHERE PId = " + lblprocessid.Text + " AND Call_Status = '" + ddlCallStatus.SelectedValue + "') SELECT SetCallBackNotRequired FROM CallStatus WHERE PId = " + lblprocessid.Text + " AND Call_Status = '" + ddlCallStatus.SelectedValue + "' ELSE SELECT 'True' SetCallBackNotRequired")))
                    FunctionClassObj.ExecuteCommand("UPDATE Campaign_" + lblprocessid.Text + "_Mapping SET Dialed = 'False',Agent_Id = '" + lblagentName.Text + "',Call_Again_Time = '" + FunctionClassObj.ConvertMdy(txtCallBackDate.Text.Trim()) + " " + callbacktimeHr.SelectedValue + ":" + callbacktimeMm.SelectedValue + "',Last_Call_Time = '" + DateTime.Now.ToString() + "',Disposition = '" + ddlCallStatus.SelectedValue + "',Call_Again_PhoneNo = '" + Call_Again_PhoneNo.Text + "',Call_Again_Type = 'Telecaller' WHERE SrNo = '" + lblSrNo.Text + "'");
            }
            else
                FunctionClassObj.ExecuteCommand("UPDATE Campaign_" + lblprocessid.Text + "_Mapping SET Dialed = 'True',Agent_Id = '" + lblagentName.Text + "',Call_Again_Time = NULL,Last_Call_Time = '" + DateTime.Now.ToString() + "',Disposition = '" + ddlCallStatus.SelectedValue + "' WHERE SrNo = '" + lblSrNo.Text + "'");

            if (ddlNewCampaign.SelectedValue != "--Select--")
                FunctionClassObj.ExecuteCommand("DELETE Campaign_" + lblprocessid.Text + "_Mapping WHERE Campaign_Id = " + ddlNewCampaign.SelectedValue + " AND Customer_Id = " + Master_Id.Text + "; UPDATE Campaign_" + lblprocessid.Text + "_Mapping SET Campaign_Id = " + ddlNewCampaign.SelectedValue + " WHERE Campaign_Id = " + lblCampaignId.Text + " AND Customer_Id =" + Master_Id.Text);
            if (Allow_Agent_Transfer.SelectedValue != "--Select--")
                FunctionClassObj.ExecuteCommand("UPDATE Campaign_" + lblprocessid.Text + "_Mapping SET Agent_Id = '" + Allow_Agent_Transfer.SelectedValue + "' WHERE SrNo = " + lblSrNo.Text);
            int iNoOfAttempCampaign = FunctionClassObj.ExecuteScalar("SELECT ISNULL(No_Of_Attempts,0) FROM Campaign_" + lblprocessid.Text + "_Mapping WHERE SrNo = " + lblSrNo.Text);
            int iNoOfAttempLog = FunctionClassObj.ExecuteScalar("SELECT COUNT(SrNo) FROM Process_" + lblprocessid.Text + "_Log WHERE SrNo = " + lblSrNo.Text);
            if (iNoOfAttempCampaign < iNoOfAttempLog)
                FunctionClassObj.ExecuteReader("UPDATE Campaign_" + lblprocessid.Text + "_Mapping SET No_Of_Attempts = " + iNoOfAttempLog + " WHERE SrNo = " + lblSrNo.Text);
        }
        return true;
    }
    public bool SaveCheck(DataTable paraDt, PlaceHolder paraPlaceHolder)
    {
        if (string.IsNullOrEmpty(lblSrNo.Text.Trim()) || lblSrNo.Text == "0")
            Session["SrNo"] = lblSrNo.Text = FunctionClassObj.ExecuteScalarString("SELECT SrNo FROM Admin_Extention_Master WHERE Extention_No = '" + txtExtensionNo.Text + "'");
        if (string.IsNullOrEmpty(DID_No.Text.Trim()))
            DID_No.Text = FunctionClassObj.ExecuteScalarString("SELECT DID_No FROM Admin_Extention_Master WHERE Extention_No = '" + txtExtensionNo.Text + "'");
        if (lblCallMode.Text.Trim() == "incomingcall" && (FunctionClassObj.ExecuteScalar("SELECT Count(Campaign_Id) FROM Campaign_Master WHERE Dial_Mode = 'predictive' AND Campaign_Id = " + lblCampaignId.Text) == 1))
        {
            dtTemp = FunctionClassObj.GetData("SELECT Unique_Id,Call_Connected FROM Campaign_" + lblprocessid.Text + "_Mapping WHERE SrNo = " + lblSrNo.Text);
            if (dtTemp.Rows.Count > 0)
            {
                lblUniqueId.Text = dtTemp.Rows[0][0].ToString();
                lblCallConnected.Text = dtTemp.Rows[0][1].ToString();
                lblCallCount.Text = "1";
            }
        }
        else
        {
            dtTemp = FunctionClassObj.GetData("SELECT Call_Connected,Call_Count FROM Admin_Extention_Master WHERE Extention_No = '" + txtExtensionNo.Text + "'");
            if (dtTemp.Rows.Count > 0)
            {
                lblCallConnected.Text = dtTemp.Rows[0]["Call_Connected"].ToString();
                lblCallCount.Text = dtTemp.Rows[0]["Call_Count"].ToString();
            }
        }
        if (string.IsNullOrEmpty(lblUniqueId.Text.Trim()))
            lblUniqueId.Text = FunctionClassObj.ExecuteScalarString("SELECT Unique_Id FROM Admin_Extention_Master WHERE Extention_No = '" + txtExtensionNo.Text + "'");
        for (int i = 0; i < paraDt.Rows.Count; i++)
        {
            string Field_Description = paraDt.Rows[i]["Field_Description"].ToString();
            string Field_Name = paraDt.Rows[i]["Field_Name"].ToString();
            string Field_Type = paraDt.Rows[i]["Field_Type"].ToString();
            string Control_Type = paraDt.Rows[i]["Control_Type"].ToString();
            bool editable = Convert.ToBoolean(paraDt.Rows[i]["Agent_Editable"].ToString());
            bool allow_null = Convert.ToBoolean(paraDt.Rows[i]["allow_null"].ToString());
            if (Control_Type == "Date Time Picker")
            {
                TextBox1 = (TextBox)paraPlaceHolder.FindControl(Field_Name);
                if (TextBox1 != null)
                {
                    if (TextBox1.Text.Trim() != string.Empty && (FunctionClassObj.IsDate(TextBox1.Text) == false))
                    {
                        DisplayMessage(Field_Description + " is not in valid format.");
                        TextBox1.Focus();
                        return false;
                    }
                }
            }
            if (Control_Type == "Text Box" && Field_Type == "Phone No")
            {
                TextBox1 = (TextBox)paraPlaceHolder.FindControl(Field_Name);
                if (TextBox1 != null)
                {
                    if (!string.IsNullOrEmpty(TextBox1.Text.Trim()) && string.IsNullOrEmpty(FunctionClassObj.StringToPhoneNo(TextBox1.Text.Trim())))
                    {
                        DisplayMessage(Field_Description + " Not a valid Phone No");
                        TextBox1.Focus();
                        return false;
                    }
                }
            }
            if (editable == true && !allow_null)
            {
                if (Control_Type == "Text Box")
                {
                    TextBox1 = (TextBox)paraPlaceHolder.FindControl(Field_Name);
                    if (TextBox1 != null)
                    {
                        if (Field_Type == "Varchar" || Field_Type == "EMail")
                        {
                            if (TextBox1.Text.Replace("'", "") == "")
                            {
                                DisplayMessage(Field_Description + " can not be left blank");
                                TextBox1.Focus();
                                return false;
                            }
                        }
                        else
                        {
                            if (FunctionClassObj.StringToDecimal(TextBox1.Text) == 0)
                            {
                                DisplayMessage(Field_Description + " can not be left blank");
                                TextBox1.Focus();
                                return false;
                            }
                        }
                    }
                }
                else if (Control_Type == "Combo Box")
                {
                    DropDownList1 = (DropDownList)paraPlaceHolder.FindControl(Field_Name);
                    if (DropDownList1 != null)
                    {
                        if (DropDownList1.SelectedIndex == 0)
                        {
                            DisplayMessage(Field_Description + " can not be left blank");
                            DropDownList1.Focus();
                            return false;
                        }
                    }
                }
                else if (Control_Type == "List Box")
                {
                    ListBox1 = (ListBox)paraPlaceHolder.FindControl(Field_Name);
                    if (ListBox1 != null)
                    {
                        if (ListBox1.SelectedValue == "")
                        {
                            DisplayMessage(Field_Description + " can not be left blank");
                            ListBox1.Focus();
                            return false;
                        }
                    }
                }
                else if (Control_Type == "Radio Button")
                {
                    RadioButtonList1 = (RadioButtonList)paraPlaceHolder.FindControl(Field_Name);
                    if (RadioButtonList1 != null)
                    {
                        if (RadioButtonList1.SelectedValue == "")
                        {
                            DisplayMessage(Field_Description + " can not be left blank");
                            RadioButtonList1.Focus();
                            return false;
                        }
                    }
                }
                else if (Control_Type == "Date Time Picker")
                {
                    TextBox1 = (TextBox)paraPlaceHolder.FindControl(Field_Name);
                    if (TextBox1 != null)
                    {
                        if (FunctionClassObj.IsDate(TextBox1.Text) == false)
                        {
                            DisplayMessage(Field_Description + " can not be left blank");
                            TextBox1.Focus();
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }
    public void SaveUpadteData(DataTable paraDt, PlaceHolder paraPlaceHolder, string tableType)
    {
        string CallType = "Received";
        if (lblCallBack.Text == "Dialer Incoming")
            CallType = "Dialer Incoming";
        else if (lblCallBack.Text == "Incoming")
            CallType = "Received";
        else if (lblstartTime.Text.ToString() == lblPickTime.Text.ToString())
            CallType = "Dialed";
        if ((tableType == "Log" && Request.QueryString["Log_Id"] == null) || (tableType == "Master" && Master_Id.Text.Trim() == ""))
        {
            string fieldName = "";
            string fieldValue = "";
            string InsertQuery = "";
            if (tableType == "Master")
            {
                fieldName = "INSERT INTO Process_" + lblprocessid.Text + "_Master(Phone_No,Branch_Id";
                fieldValue = " VALUES('" + FunctionClassObj.StringToPhoneNo(Phone_No.Text.Trim()) + "','" + SANBranch_Master.SelectedValue + "'";
            }
            else
            {
                int TeamLeaderId = FunctionClassObj.ExecuteScalar("SELECT Team_Leader_Id FROM Admin_Agent_Master WHERE Agent_Name='" + lblagentName.Text + "'");
                //fieldName = "IF NOT Exists(SELECT Log_Id FROM Process_" + lblprocessid.Text + "_Log WHERE Phone_No = '" + Phone_No.Text
                //+ "' AND Start_Time = '" + lblstartTime.Text.Trim() + "') INSERT INTO Process_" + lblprocessid.Text
                //+ "_Log (Master_Id,Phone_No,Extention_No,Agent_Name,Start_Time,Pick_Time,End_Time,CallType,CallStatus,Campaign_Id,Team_Leader_Id,Duration";
                fieldName = "IF NOT Exists(SELECT Log_Id FROM Process_" + lblprocessid.Text + "_Log WHERE Phone_No = '" + Phone_No.Text + "' AND Start_Time = '" + lblstartTime.Text.Trim()
                + "') BEGIN INSERT INTO Process_" + lblprocessid.Text + "_Log (DID_No,Call_Log_Attempt,Master_Id,Phone_No,Extention_No,Agent_Name,Start_Time,Pick_Time,End_Time,CallType,CallStatus,Campaign_Id,Team_Leader_Id,Duration";

                fieldValue = "VALUES('" + DID_No.Text.Replace("'", "").Trim() + "'," + FunctionClassObj.StringToInt(Call_Log_Attempt.Text) + "," + Master_Id.Text + ",'" + FunctionClassObj.StringToPhoneNo(lblDialedPhone_No.Text.Trim()) + "','" + txtExtensionNo.Text
                + "','" + lblagentName.Text + "','" + lblstartTime.Text + "',";
                if (lblstartTime.Text.ToString() == lblPickTime.Text.ToString())
                    fieldValue += "NULL";
                else
                    fieldValue += "'" + lblPickTime.Text + "'";
                string sEndTime = "";
                sEndTime = FunctionClassObj.ExecuteScalarString("SELECT CASE WHEN CRM_State = 'Wrapup' THEN State_Time ELSE GETDATE() END FROM Admin_Extention_Master WHERE Extention_No = '" + txtExtensionNo.Text + "'");
                if (sEndTime == "")
                    sEndTime = "GETDATE()";
                else
                    sEndTime = "'" + sEndTime + "'";
                fieldValue += "," + sEndTime + ",'" + CallType + "','" + ddlCallStatus.SelectedValue + "','" + lblCampaignId.Text + "'," + TeamLeaderId + ",convert(decimal(10,2),convert(int,(DateDiff(second,'" + lblPickTime.Text + "'," + sEndTime + "))) / 60 +((convert(decimal(10,2),(DateDiff(second,'" + lblPickTime.Text + "'," + sEndTime + "))) % 60)/100))";
                //fieldValue += ",'" + DateTime.Now.ToString() + "','" + CallType + "','" + ddlCallStatus.SelectedValue + "','" + lblCampaignId.Text + "'," + TeamLeaderId + ",convert(decimal(10,2),convert(int,(DateDiff(second,'" + lblPickTime.Text + "','" + DateTime.Now.ToString() + "'))) / 60 +((convert(decimal(10,2),(DateDiff(second,'" + lblPickTime.Text + "','" + DateTime.Now.ToString() + "'))) % 60)/100))";
            }
            #region Field Conditions
            for (int i = 0; i < paraDt.Rows.Count; i++)
            {
                string Field_Name = paraDt.Rows[i]["Field_Name"].ToString();
                string Field_Type = paraDt.Rows[i]["Field_Type"].ToString();
                string Control_Type = paraDt.Rows[i]["Control_Type"].ToString();
                if (Control_Type != "I-Frame")
                {
                    fieldName += ",[" + Field_Name + "]";
                    fieldValue += ",";
                    //  InsertQuery += ",";
                }
                if (Control_Type == "Html Editor")
                {
                    AjaxControlToolkit.HTMLEditor.Editor Editor1 = (AjaxControlToolkit.HTMLEditor.Editor)paraPlaceHolder.FindControl(Field_Name);
                    if (Editor1 != null)
                        fieldValue += "'" + Server.HtmlEncode(Editor1.Content.Replace("'", "''")) + "'";
                    else
                        fieldValue += "NULL";
                }
                else if (Control_Type == "Label")
                {
                    LabelSAN = (Label)paraPlaceHolder.FindControl(Field_Name);
                    fieldValue += "'" + LabelSAN.Text.Replace("'", "") + "'";
                }
                else if (Control_Type == "Text Box" || Control_Type == "Hyper Link")
                {
                    TextBox1 = (TextBox)paraPlaceHolder.FindControl(Field_Name);
                    if (TextBox1 != null)
                    {
                        if (Field_Type == "Varchar" || Field_Type == "EMail")
                            fieldValue += "'" + TextBox1.Text.Replace("'", "") + "'";
                        else if (Field_Type == "Phone No")
                            fieldValue += "'" + FunctionClassObj.StringToPhoneNo(TextBox1.Text.Trim()) + "'";
                        //InsertQuery += "'" + TextBox1.Text.Replace("'","") + "'";
                        else if (Field_Type == "Decimal" && FunctionClassObj.IsDecimal(TextBox1.Text.Replace("'", "")))
                            fieldValue += TextBox1.Text.Replace("'", "");
                        //InsertQuery += TextBox1.Text.Replace("'", "");
                        else
                            fieldValue += "NULL";
                        //InsertQuery +="NULL";
                    }
                    else
                        fieldValue += "NULL";
                    //InsertQuery += "NULL";
                }
                else if (Control_Type == "Combo Box")
                {
                    DropDownList1 = (DropDownList)paraPlaceHolder.FindControl(Field_Name);
                    if (DropDownList1 != null)
                        fieldValue += "'" + DropDownList1.SelectedValue + "'";
                    //InsertQuery += "'" + DropDownList1.SelectedValue + "'";
                    else
                        fieldValue += "NULL";
                    //InsertQuery += "NULL";
                }
                else if (Control_Type == "List Box")
                {
                    ListBox1 = (ListBox)paraPlaceHolder.FindControl(Field_Name);
                    if (ListBox1 != null)
                        fieldValue += "'" + ListBox1.SelectedValue + "'";
                    //InsertQuery += "'" + ListBox1.SelectedValue + "'";
                    else
                        fieldValue += "NULL";
                    //InsertQuery += "NULL";
                }
                else if (Control_Type == "Radio Button")
                {
                    RadioButtonList1 = (RadioButtonList)paraPlaceHolder.FindControl(Field_Name);
                    if (RadioButtonList1 != null)
                        fieldValue += "'" + RadioButtonList1.SelectedValue + "'";
                    //InsertQuery += "'" + RadioButtonList1.SelectedValue + "'";
                    else
                        fieldValue += "NULL";
                    //InsertQuery += "NULL";
                }
                else if (Control_Type == "Check Box")
                {
                    CheckBox1 = (CheckBox)paraPlaceHolder.FindControl(Field_Name);
                    if (CheckBox1 != null)
                        fieldValue += "'" + CheckBox1.Checked + "'";
                    //InsertQuery += "'" + CheckBox1.Checked + "'";
                    else
                        fieldValue += "NULL";
                    //InsertQuery += "NULL";
                }
                else if (Control_Type == "Date Time Picker")
                {
                    TextBox1 = (TextBox)paraPlaceHolder.FindControl(Field_Name);
                    if (TextBox1 != null)
                    {
                        if (TextBox1.Text.Trim() != "")
                        {
                            string[] datesplit;
                            datesplit = TextBox1.Text.Split('/');
                            if (datesplit.GetLength(0) == 3)
                            {
                                string date = datesplit[1] + "/" + datesplit[0] + "/" + datesplit[2];
                                if (FunctionClassObj.IsDate(TextBox1.Text))
                                    fieldValue += "'" + date + "'";
                                //InsertQuery += "'" + date + "'";
                                else
                                    fieldValue += "NULL";
                                //InsertQuery += "NULL";
                            }
                            else
                                fieldValue += "NULL";
                            //InsertQuery += "NULL";
                        }
                        else
                            fieldValue += "NULL";
                        //InsertQuery += "NULL";
                    }
                    else
                        fieldValue += "NULL";
                    //InsertQuery += "NULL";
                }
            }
            #endregion
            if (tableType != "Master")
            {
                fieldName += ",Unique_Id,Call_Connected,Call_Count,SrNo,isAlternateNo,CallBack_Dialed_PhoneNo,CallBack_Dial_Time,CallBack_Type";
                fieldValue += ",'" + lblUniqueId.Text + "','" + lblCallConnected.Text + "','" + lblCallCount.Text + "'," + lblSrNo.Text;
                if (lblDialedPhone_No.Text.Trim() != Phone_No.Text.Trim())
                    fieldValue += ",1";
                else
                    fieldValue += ",0";
                if (Session["CallBackPhoneNo"] == null)
                    fieldValue += ",NULL";
                else
                    fieldValue += ",'" + Convert.ToString(Session["CallBackPhoneNo"]) + "',";
                if (Session["CallBackTime"] == null)
                    fieldValue += ",NULL";
                else
                    fieldValue += "'" + Convert.ToString(Session["CallBackTime"]) + "'";
                if (Session["CallAgainType"] == null)
                    fieldValue += ",NULL";
                else
                    fieldValue += ",'" + Convert.ToString(Session["CallAgainType"]) + "'";
                fieldName += ",HangupCause_Code";
                string sHangupCauseCode = FunctionClassObj.ExecuteScalarString("SELECT Hangup_Cause FROM Campaign_" + lblprocessid.Text + "_Mapping WHERE SrNo = " + lblSrNo.Text);
                if (string.IsNullOrEmpty(sHangupCauseCode))
                    fieldValue += ",NULL";
                else
                    fieldValue += "," + sHangupCauseCode;
                InsertQuery = fieldName + ")" + fieldValue + ")";
                lblLogId.Text = FunctionClassObj.ExecuteScalarString(InsertQuery + ";SELECT SCOPE_IDENTITY() END ELSE SELECT Log_Id FROM Process_" + lblprocessid.Text + "_Log WHERE Phone_No = '" + Phone_No.Text + "' AND Start_Time = '" + lblstartTime.Text.Trim() + "'");
            }
            else
            {
                InsertQuery = fieldName + ")" + fieldValue + ")";
                FunctionClassObj.ExecuteCommand(InsertQuery);
            }
        }
        else if ((tableType == "Log" && Request.QueryString["Log_Id"] != null) || (tableType == "Master" && Master_Id.Text.Trim() != ""))
        {
            string updateQuery = "";
            if (tableType == "Log") //Update Disposition on Edit Log
                updateQuery += " CallStatus = '" + ddlCallStatus.SelectedValue + "'";
            #region Field Condition
            for (int i = 0; i < paraDt.Rows.Count; i++)
            {
                string Field_Name = paraDt.Rows[i]["Field_Name"].ToString();
                string Field_Type = paraDt.Rows[i]["Field_Type"].ToString();
                string Control_Type = paraDt.Rows[i]["Control_Type"].ToString();
                if (updateQuery != "" && Control_Type != "I-Frame")
                    updateQuery += ",";
                if (Control_Type == "Html Editor")
                {
                    AjaxControlToolkit.HTMLEditor.Editor Editor1 = (AjaxControlToolkit.HTMLEditor.Editor)paraPlaceHolder.FindControl(Field_Name);
                    if (Editor1 != null)
                        updateQuery += "[" + Field_Name + "] = '" + Server.HtmlEncode(Editor1.Content.Replace("'", "''")) + "'";
                    else
                        updateQuery += "[" + Field_Name + "] = NULL";
                }
                else if (Control_Type == "Label")
                {
                    LabelSAN = (Label)paraPlaceHolder.FindControl(Field_Name);
                    updateQuery += "[" + Field_Name + "] = '" + LabelSAN.Text.Replace("'", "") + "'";
                }
                else if (Control_Type == "Text Box")
                {
                    TextBox1 = (TextBox)paraPlaceHolder.FindControl(Field_Name);
                    if (TextBox1 != null)
                    {
                        if (Field_Type == "Varchar" || Field_Type == "EMail")
                            updateQuery += "[" + Field_Name + "] = '" + TextBox1.Text.Replace("'", "") + "'";
                        else if (Field_Type == "Phone No")
                            updateQuery += "[" + Field_Name + "] = '" + FunctionClassObj.StringToPhoneNo(TextBox1.Text.Trim()) + "'";
                        else if (Field_Type == "Decimal" && FunctionClassObj.IsDecimal(TextBox1.Text.Replace("'", "")))
                            updateQuery += "[" + Field_Name + "] = " + TextBox1.Text.Replace("'", "");
                        else
                            updateQuery += "[" + Field_Name + "] = NULL";
                    }
                    else
                        updateQuery += "[" + Field_Name + "] = NULL";
                }
                else if (Control_Type == "Hyper Link")
                {
                    TextBox1 = (TextBox)paraPlaceHolder.FindControl(Field_Name);
                    if (TextBox1 != null)
                        updateQuery += "[" + Field_Name + "] = '" + TextBox1.Text.Replace("'", "") + "'";
                    else
                        updateQuery += "[" + Field_Name + "] = NULL";
                }
                else if (Control_Type == "Combo Box")
                {
                    DropDownList1 = (DropDownList)paraPlaceHolder.FindControl(Field_Name);
                    if (DropDownList1 != null)
                        updateQuery += "[" + Field_Name + "] = '" + DropDownList1.SelectedValue + "'";
                    else
                        updateQuery += "[" + Field_Name + "] = NULL";
                }
                else if (Control_Type == "List Box")
                {
                    ListBox1 = (ListBox)paraPlaceHolder.FindControl(Field_Name);
                    if (ListBox1 != null)
                        updateQuery += "[" + Field_Name + "] = '" + ListBox1.SelectedValue + "'";
                    else
                        updateQuery += "[" + Field_Name + "] = NULL";
                }
                else if (Control_Type == "Radio Button")
                {
                    RadioButtonList1 = (RadioButtonList)paraPlaceHolder.FindControl(Field_Name);
                    if (RadioButtonList1 != null)
                        updateQuery += "[" + Field_Name + "]='" + RadioButtonList1.SelectedValue + "'";
                    else
                        updateQuery += "[" + Field_Name + "] = NULL";
                }
                else if (Control_Type == "Check Box")
                {
                    CheckBox1 = (CheckBox)paraPlaceHolder.FindControl(Field_Name);
                    if (CheckBox1 != null)
                        updateQuery += "[" + Field_Name + "] = '" + CheckBox1.Checked + "'";
                    else
                        updateQuery += "[" + Field_Name + "] = NULL";
                }
                else if (Control_Type == "Date Time Picker")
                {
                    TextBox1 = (TextBox)paraPlaceHolder.FindControl(Field_Name);
                    if (TextBox1 != null)
                    {
                        if (TextBox1.Text.Trim() != "")
                        {
                            string[] datesplit;
                            datesplit = TextBox1.Text.Split('/');
                            if (datesplit.GetLength(0) == 3)
                            {
                                string date = datesplit[1] + "/" + datesplit[0] + "/" + datesplit[2];
                                if (FunctionClassObj.IsDate(TextBox1.Text))
                                    updateQuery += "[" + Field_Name + "] = '" + date + "'";
                                else
                                    updateQuery += "[" + Field_Name + "] = NULL";
                            }
                            else
                                updateQuery += "[" + Field_Name + "] = NULL";
                        }
                        else
                            updateQuery += "[" + Field_Name + "] = NULL";
                    }
                    else
                        updateQuery += "[" + Field_Name + "] = NULL";
                }
            }
            #endregion
            if (updateQuery != "")
            {
                if (tableType == "Master")
                    updateQuery = "UPDATE Process_" + lblprocessid.Text + "_Master SET Phone_No = '" + Phone_No.Text.Trim() + "',Branch_Id = '" + SANBranch_Master.SelectedValue + "'," + updateQuery + " WHERE Master_Id = " + Master_Id.Text.Trim();
                else
                    updateQuery = "UPDATE Process_" + lblprocessid.Text + "_Log SET " + updateQuery + " WHERE Log_Id = " + Log_Id;
                FunctionClassObj.ExecuteCommand(updateQuery);
            }
        }
        if (string.IsNullOrEmpty(Master_Id.Text))
            Master_Id.Text = FunctionClassObj.ExecuteScalarString("SELECT Master_Id FROM Process_" + lblprocessid.Text + "_Master WHERE Phone_No = '" + Phone_No.Text.Trim().Replace("'", "") + "'");
    }
    public void SendByEmail(DataTable dataTableMaster, DataTable dataTableLog)
    {
        StringBuilder EMailString = new StringBuilder();
        EMailString.Append("<table width = 600 border = 1 cellspacing = 1 cellpadding = 1 >");
        EMailString.Append("<tr><td width = 200> <b> Phone No : </b></td><td width = 400>&nbsp;" + Phone_No.Text.Replace("'", "") + "</td></tr>");
        int i = 0;
        #region Data Table Master
        for (i = 0; i < dataTableMaster.Rows.Count; i++)
        {
            if (Convert.ToBoolean(dataTableMaster.Rows[i]["Send_By_Email"].ToString()))
            {
                string Field_Name = dataTableMaster.Rows[i]["Field_Name"].ToString();
                string Field_Desc = dataTableMaster.Rows[i]["Field_Description"].ToString();
                string Control_Type = dataTableMaster.Rows[i]["Control_Type"].ToString();
                if (Control_Type == "Text Box")
                {
                    TextBox1 = (TextBox)PlaceHolder_Master.FindControl(Field_Name);
                    if (TextBox1 != null)
                        EMailString.Append("<tr><td width = 200> <b> " + Field_Desc + " : </b></td><td width = 400>&nbsp;" + TextBox1.Text.Replace("'", "") + "</td></tr>");
                }
                else if (Control_Type == "Combo Box")
                {
                    DropDownList1 = (DropDownList)PlaceHolder_Master.FindControl(Field_Name);
                    if (DropDownList1 != null)
                    {
                        if (DropDownList1.SelectedItem.Text != "--Select--")
                            EMailString.Append("<tr><td width = 200> <b> " + Field_Desc + " : </b></td><td width = 400>&nbsp;" + DropDownList1.SelectedItem.Text + "</td></tr>");
                    }
                }
                else if (Control_Type == "List Box")
                {
                    ListBox1 = (ListBox)PlaceHolder_Master.FindControl(Field_Name);
                    if (ListBox1 != null)
                    {
                        if (ListBox1.SelectedItem.Text != "--Select--")
                            EMailString.Append("<tr><td width = 200> <b> " + Field_Desc + " : </b></td><td width = 400>&nbsp;" + ListBox1.SelectedItem.Text + "</td></tr>");
                    }
                }
                else if (Control_Type == "Radio Button")
                {
                    RadioButtonList1 = (RadioButtonList)PlaceHolder_Master.FindControl(Field_Name);
                    if (RadioButtonList1 != null)
                        EMailString.Append("<tr><td width = 200> <b> " + Field_Desc + " : </b></td><td width = 400>&nbsp;" + RadioButtonList1.SelectedItem.Text + "</td></tr>");
                }
                else if (Control_Type == "Check Box")
                {
                    CheckBox1 = (CheckBox)PlaceHolder_Master.FindControl(Field_Name);
                    if (CheckBox1 != null)
                        EMailString.Append("<tr><td width = 200> <b> " + Field_Desc + " : </b></td><td width = 400>&nbsp;" + CheckBox1.Checked + "</td></tr>");
                }
                else if (Control_Type == "Date Time Picker")
                {
                    TextBox1 = (TextBox)PlaceHolder_Master.FindControl(Field_Name);
                    if (TextBox1 != null)
                        EMailString.Append("<tr><td width = 200> <b> " + Field_Desc + " : </b></td><td width = 400>&nbsp;" + TextBox1.Text.Trim().Replace("'", "") + "</td></tr>");
                }
            }
        }
        #endregion
        #region Data Table Log
        for (i = 0; i < dataTableLog.Rows.Count; i++)
        {
            if (Convert.ToBoolean(dataTableLog.Rows[i]["Send_By_Email"].ToString()))
            {
                string Field_Name = dataTableLog.Rows[i]["Field_Name"].ToString();
                string Field_Desc = dataTableLog.Rows[i]["Field_Description"].ToString();
                string Control_Type = dataTableLog.Rows[i]["Control_Type"].ToString();
                if (Control_Type == "Text Box")
                {
                    TextBox1 = (TextBox)PlaceHolder_Log.FindControl(Field_Name);
                    if (TextBox1 != null)
                        EMailString.Append("<tr><td width = 200> <b> " + Field_Desc + " : </b></td><td width = 400>&nbsp;" + TextBox1.Text.Replace("'", "") + "</td></tr>");
                }
                else if (Control_Type == "Combo Box")
                {
                    DropDownList1 = (DropDownList)PlaceHolder_Log.FindControl(Field_Name);
                    if (DropDownList1 != null)
                    {
                        if (DropDownList1.SelectedItem.Text != "--Select--")
                            EMailString.Append("<tr><td width = 200> <b> " + Field_Desc + " : </b></td><td width = 400>&nbsp;" + DropDownList1.SelectedItem.Text + "</td></tr>");
                    }
                }
                else if (Control_Type == "List Box")
                {
                    ListBox1 = (ListBox)PlaceHolder_Log.FindControl(Field_Name);
                    if (ListBox1 != null)
                    {
                        if (ListBox1.SelectedItem.Text != "--Select--")
                            EMailString.Append("<tr><td width = 200> <b> " + Field_Desc + " : </b></td><td width = 400>&nbsp;" + ListBox1.SelectedItem.Text + "</td></tr>");
                    }
                }
                else if (Control_Type == "Radio Button")
                {
                    RadioButtonList1 = (RadioButtonList)PlaceHolder_Log.FindControl(Field_Name);
                    if (RadioButtonList1 != null)
                        EMailString.Append("<tr><td width = 200> <b> " + Field_Desc + " : </b></td><td width = 400>&nbsp;" + RadioButtonList1.SelectedItem.Text + "</td></tr>");
                }
                else if (Control_Type == "Check Box")
                {
                    CheckBox1 = (CheckBox)PlaceHolder_Log.FindControl(Field_Name);
                    if (CheckBox1 != null)
                        EMailString.Append("<tr><td width = 200> <b> " + Field_Desc + " : </b></td><td width = 400>&nbsp;" + CheckBox1.Checked + "</td></tr>");
                }
                else if (Control_Type == "Date Time Picker")
                {
                    TextBox1 = (TextBox)PlaceHolder_Log.FindControl(Field_Name);
                    if (TextBox1 != null)
                        EMailString.Append("<tr><td width = 200> <b> " + Field_Desc + " : </b></td><td width = 400>&nbsp;" + TextBox1.Text.Trim().Replace("'", "") + "</td></tr>");
                }
            }
        }
        #endregion
        EMailString.Append("<tr><td width = 200> <b> Agent Name : </b></td><td width = 400>&nbsp;" + lblagentName.Text + "</td></tr>");
        EMailString.Append("</table>");
        SendEmail(FunctionClassObj.ExecuteScalarString("SELECT Account_Id FROM Email_Accounts WHERE Process_Id = " + lblprocessid.Text), lblEmailId.Text.Trim(), ddlCallStatus.SelectedItem.Text, EMailString.ToString());
    }
    protected void ddlCallStatus_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlCallStatus.SelectedValue != "--Select--")
            lblEmailId.Text = FunctionClassObj.ExecuteScalarString("SELECT Email_Id FROM CallStatus WHERE Call_Status = '" + ddlCallStatus.SelectedValue + "'");
        else
            lblEmailId.Text = "";
    }
    protected void lnkBtnViewDetails_Click(object sender, EventArgs e)
    {
        try
        {
            LinkButton lnkbtnDetail = (LinkButton)sender;
            Session["sLogId"] = lnkbtnDetail.ToolTip.ToString();
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Details", "window.open('LogDetails.aspx','LogDetails','channelmode=yes,resizable=yes,titlebar=yes,scrollbars=yes')", true);
        }
        catch (Exception ex)
        {
            ShowError.Visible = true;
            ErrorMessage.Text = "Error View " + ex.Message;
        }
    }
    protected void btnScript_Click(object sender, EventArgs e)
    {
        //if (btnScript.Text == "Display Script")
        //{
        //    LiteralScript.Text = Server.HtmlDecode(FunctionClassObj.ExecuteScalarString("SELECT Script FROM Script_Master WHERE Script_Id = ( SELECT Script_Id FROM Process WHERE pid = " + lblprocessid.Text + ")"));
        //    btnScript.Text = "Hide Script";
        //}
        //else if (btnScript.Text == "Hide Script")
        //{
        //    LiteralScript.Text = Server.HtmlDecode(string.Empty);
        //    btnScript.Text = "Display Script";
        //}
        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Script", "window.open('Script.aspx','Script','channelmode=yes,resizable=yes,titlebar=yes,scrollbars=yes')", true);
    }
    protected void ddlExternalLink_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlExternalLink.SelectedValue != "--Select--")
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Script", "window.open('" + ddlExternalLink.SelectedValue.Replace("##Agent_Name##", lblagentName.Text).Replace("##Customer_Id##", Master_Id.Text).Replace("##Phone_No##", Phone_No.Text) + "','Script','channelmode=yes,resizable=yes,titlebar=yes,scrollbars=yes')", true);
    }
    protected void Dial1_Click(object sender, EventArgs e)
    {
        if (Phone_No.Text != string.Empty)
        {
            lblUniqueId.Text = DateTime.Now.ToString("yyyyMMdd-HHmmss-ffff");
            lblDialedPhone_No.Text = FunctionClassObj.StringToPhoneNo(Phone_No.Text.Trim());
            if (!FunctionClassObj.IsDNCNumber(lblDialedPhone_No.Text.Trim(), FunctionClassObj.StringToInt(Session["pid"].ToString())))
            {
                //FunctionClassObj.ExecuteCommand("UPDATE Admin_Extention_Master SET Called_No = '" + lblDialedPhone_No.Text.Trim() + "',Dial_Time = NULL,Unique_Id = '" + lblUniqueId.Text + "' WHERE Extention_No = '" + txtExtensionNo.Text + "'");
                UpdateCRMState("Manual", lblDialedPhone_No.Text.Trim(), lblUniqueId.Text);
                FunctionClassObj.ExecuteCommand("UPDATE Campaign_" + lblprocessid.Text + "_Mapping SET No_Of_Attempts = (ISNULL(No_Of_Attempts,0) + 1) WHERE SrNo = " + FunctionClassObj.StringToInt(lblSrNo.Text));
                Call_Log_Attempt.Text = Convert.ToString(FunctionClassObj.StringToInt(Call_Log_Attempt.Text) + 1);
            }
            if (lblCallMode.Text.ToLower() == "preview")
            {
                Session["Pick_Time"] = Session["Start_Time"] = lblstartTime.Text = lblPickTime.Text = DateTime.Now.ToString();
                Session["Phone_No"] = FunctionClassObj.StringToPhoneNo(Phone_No.Text.Trim());
                FunctionClassObj.ExecuteCommand("UPDATE Campaign_" + lblprocessid.Text + "_Mapping SET Dialed = 'True', Call_Again_Time = NULL WHERE Customer_Id = " + Master_Id.Text + " AND Campaign_Id =" + lblCampaignId.Text);
                imgBtnSave.Enabled = imgBtnSaveNext.Enabled = true;
            }
            if (lblCallMode.Text.ToLower() == "previewdialing")
            {
                Session["Pick_Time"] = Session["Start_Time"] = lblstartTime.Text = lblPickTime.Text = DateTime.Now.ToString();
                Session["Phone_No"] = FunctionClassObj.StringToPhoneNo(Phone_No.Text.Trim());
                FunctionClassObj.ExecuteCommand("UPDATE Campaign_" + lblprocessid.Text + "_Mapping SET Dialed = 'True', Call_Again_Time = NULL WHERE Customer_Id = " + Master_Id.Text + " AND Campaign_Id =" + lblCampaignId.Text);
                imgBtnSave.Text = "Save";
            }
        }
    }
    protected void Dial_Click(object sender, EventArgs e)
    {
        try
        {
            Button btn = (Button)sender;
            TextBox1 = (TextBox)PlaceHolder_Master.FindControl(btn.ID.Substring(4));
            if (TextBox1 != null)
            {
                if (FunctionClassObj.StringToDecimal(TextBox1.Text) != 0)
                {
                    string dialno = FunctionClassObj.StringToPhoneNo(TextBox1.Text.Trim());
                    dtProcessMaster = FunctionClassObj.GetData("SELECT * FROM Process_Master WHERE Pid = " + lblprocessid.Text + " AND Agent_Visible = 1 ORDER BY Order_No");
                    if (SaveCheck(dtProcessMaster, PlaceHolder_Master) == false)
                        return;
                    SaveUpadteData(dtProcessMaster, PlaceHolder_Master, "Master");
                    if (!FunctionClassObj.IsDNCNumber(FunctionClassObj.StringToPhoneNo(Phone_No.Text), FunctionClassObj.StringToInt(Session["pid"].ToString())))
                    {
                        if (lblCallMode.Text == "preview")
                            Response.Redirect("CallTransfer.aspx?callmode=alternateno&Caller_Id=" + FunctionClassObj.EncryptString(FunctionClassObj.StringToPhoneNo(Phone_No.Text)) + "&Alternateno=" + dialno + "&Visible=2&CallLogAttempt=" + Call_Log_Attempt.Text, true);
                        else if (lblCallMode.Text == "progressive")
                            Response.Redirect("CallTransfer.aspx?callmode=alternateno&Caller_Id=" + FunctionClassObj.EncryptString(FunctionClassObj.StringToPhoneNo(Phone_No.Text)) + "&Alternateno=" + dialno + "&Visible=1&CallLogAttempt=" + Call_Log_Attempt.Text, true);
                        else if (lblCallMode.Text == "incomingcall" || lblCallBack.Text == "Dialer Incoming")
                        {
                            //FunctionClassObj.ExecuteCommand("UPDATE Admin_Extention_Master SET Called_No = '" + dialno + "',Dial_Time = NULL,Unique_Id = '" + lblUniqueId.Text + "' WHERE Extention_No = '" + txtExtensionNo.Text + "'");
                            UpdateCRMState("Manual", dialno, lblUniqueId.Text);
                            Call_Log_Attempt.Text = Convert.ToString(FunctionClassObj.StringToInt(Call_Log_Attempt.Text) + 1);
                        }
                        else
                            Response.Redirect("CallTransfer.aspx?callmode=alternateno&Caller_Id=" + FunctionClassObj.EncryptString(FunctionClassObj.StringToPhoneNo(Phone_No.Text)) + "&Alternateno=" + dialno + "&Visible=0&CallLogAttempt=" + Call_Log_Attempt.Text, true);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            ShowError.Visible = true;
            ErrorMessage.Text = ex.Message;
        }
    }
    public bool CallBack()
    {
        lblUniqueId.Text = DateTime.Now.ToString("yyyyMMdd-HHmmss-ffff");
    mycallBack:
        dtProgressivedialing = FunctionClassObj.GetData("getCallBack @ProcessId = '" + lblprocessid.Text + "',@CampaignId = '" + lblCampaignId.Text + "',@AgentName = '" + lblagentName.Text + "'");
        if (dtProgressivedialing.Rows.Count == 1)
        {
            if (!FunctionClassObj.IsDNCNumber(dtProgressivedialing.Rows[0]["Call_Again_PhoneNo"].ToString(), FunctionClassObj.StringToInt(Session["pid"].ToString())))
            {
                int intCampaignId = 0;
                Session["Phone_No"] = Phone_No.Text = FunctionClassObj.StringToStrPhoneNo(dtProgressivedialing.Rows[0]["Phone_No"].ToString());
                Session["SrNo"] = lblSrNo.Text = dtProgressivedialing.Rows[0]["SrNo"].ToString();
                lblCallBack.Text = dtProgressivedialing.Rows[0]["Call_Again_Type"].ToString() + " Call Back "; //+ dtProgressivedialing.Rows[0]["Call_Again_Time"].ToString();
                Session["CallAgainType"] = lblCall_Again_Type.Text = dtProgressivedialing.Rows[0]["Call_Again_Type"].ToString();
                Session["CallBackPhoneNo"] = Phone_No.Text;
                Session["CallBackTime"] = dtProgressivedialing.Rows[0]["Call_Again_Time"].ToString();
                lblCampaignId.Text = dtProgressivedialing.Rows[0]["Campaign_Id"].ToString();
                if (Convert.ToBoolean(dtProcess.Rows[0]["Enable_Last_Campaign_Save"]))
                    intCampaignId = FunctionClassObj.ExecuteScalar("SELECT Campaign_Id FROM Campaign_Master WHERE Campaign_Id = (SELECT TOP 1 Campaign_Id FROM Process_" + lblprocessid.Text + "_Log WHERE Master_Id = '" + dtProgressivedialing.Rows[0]["Master_Id"].ToString() + "' ORDER BY Log_Id DESC)");
                lblCampaignId.Text = intCampaignId > 0 ? intCampaignId.ToString() : dtProgressivedialing.Rows[0]["Campaign_Id"].ToString();
                FunctionClassObj.ExecuteCommand("UPDATE Campaign_" + lblprocessid.Text + "_Mapping SET Dialed = 'True',Call_Again_Time = NULL,Call_Again_PhoneNo = NULL,Call_Again_Type = NULL WHERE SrNo = " + dtProgressivedialing.Rows[0]["SrNo"].ToString());
                UpdateCRMState("Outgoing", dtProgressivedialing.Rows[0]["Call_Again_PhoneNo"].ToString(), lblUniqueId.Text);
                Session["Pick_Time"] = Session["Start_Time"] = lblstartTime.Text = lblPickTime.Text = dtProgressivedialing.Rows[0]["Start_Time"].ToString();
                imgBtnSaveNext.Visible = true;
                Call_Log_Attempt.Text = "1";
                lblCallBack.Text = dtProgressivedialing.Rows[0]["Call_Again_Type"].ToString() + " Call Back ";
                lblCallBackTime.Text = Convert.ToString(Session["CallBackTime"]);
                return true;
            }
            else
            {
                FunctionClassObj.ExecuteCommand("UPDATE Campaign_" + lblprocessid.Text + "_Mapping SET Dialed = 'True',Call_Again_Time = NULL,Call_Again_PhoneNo = NULL,Call_Again_Type = NULL WHERE SrNo = " + dtProgressivedialing.Rows[0]["SrNo"].ToString());
                goto mycallBack;
            }
        }
        return false;
    }
    public void NoDialing()
    {
        //UpdateCRMState("Idle");
        Response.Redirect("CallWaiting.aspx", true);
        // Session["LastSrNo"] = null;
        // DisplayMessage("No more record found for Preview Dialing!!");
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        string sqlQuery = "SELECT * FROM Process_" + lblprocessid.Text + "_Master WHERE 1 = 1 ";
        string search = string.Empty;
        //dtProcessLog = FunctionClassObj.GetData("SELECT * FROM Process_Master WHERE Pid = " + lblprocessid.Text + " AND Unique_Field = 1 ORDER BY Order_No");
        dtProcessMasterUnique = FunctionClassObj.FilterRecords(dtProcessMaster, "Allow_Filter = 1");
        if (((TextBox)PlaceHolder1.FindControl("Search_Phone_No")).Text.Trim() != "")
            search = " AND Phone_No = '" + ((TextBox)PlaceHolder1.FindControl("Search_Phone_No")).Text.Trim() + "'";
        if (((TextBox)PlaceHolder1.FindControl("Search_Master_Id")).Text.Trim() != "")
            search = " AND Master_Id = '" + ((TextBox)PlaceHolder1.FindControl("Search_Master_Id")).Text.Trim() + "'";
        for (int i = 0; i < dtProcessMasterUnique.Rows.Count; i++)
        {
            string Field_Name = dtProcessMasterUnique.Rows[i]["Field_Name"].ToString();
            string Control_Type = dtProcessMasterUnique.Rows[i]["Control_Type"].ToString();
            string Field_Type = dtProcessMasterUnique.Rows[i]["Field_Type"].ToString();
            if (Field_Type == "Decimal")
            {
                string from = ((TextBox)Page.FindControl("From_Search_" + Field_Name)).Text.Trim().Replace("'", "");
                string to = ((TextBox)Page.FindControl("To_Search_" + Field_Name)).Text.Trim().Replace("'", "");
                if (from != "" && to != "")
                    search += " AND " + Field_Name + " BETWEEN " + from + " AND " + to;
            }
            else
            {
                if (Control_Type == "Text Box")
                {
                    if (((TextBox)PlaceHolder1.FindControl("Search_" + Field_Name)).Text.Trim() != "")
                        search += " AND " + Field_Name + " LIKE '%" + ((TextBox)PlaceHolder1.FindControl("Search_" + Field_Name)).Text.Trim().Replace("'", "") + "%'";
                }
                else if (Control_Type == "Combo Box")
                {
                    string selectedText = ((DropDownList)PlaceHolder1.FindControl("Search_" + Field_Name)).SelectedItem.Text;
                    if (selectedText != "--Select--")
                        search += " AND " + Field_Name + " = '" + selectedText + "'";
                }
                else if (Control_Type == "List Box")
                {
                    string selectedText = ((ListBox)PlaceHolder1.FindControl("Search_" + Field_Name)).SelectedItem.Text;
                    if (selectedText != "--Select--")
                        search += " AND " + Field_Name + " = '" + selectedText + "'";
                }
                else if (Control_Type == "Radio Button")
                    search += " AND " + Field_Name + " = '" + ((RadioButtonList)PlaceHolder1.FindControl("Search_" + Field_Name)).SelectedItem.Text + "'";
                else if (Control_Type == "Check Box")
                    search += " AND " + Field_Name + "='" + ((CheckBox)PlaceHolder1.FindControl("Search_" + Field_Name)).Checked + "'";
                else if (Control_Type == "Date Time Picker")
                {
                    if (((TextBox)PlaceHolder1.FindControl("Search_" + Field_Name)).Text.Trim() != string.Empty)
                        search += " AND " + Field_Name + "='" + FunctionClassObj.ConvertMdy(((TextBox)PlaceHolder1.FindControl("Search_" + Field_Name)).Text.Trim().Replace("'", "")) + "'";
                }
            }
        }
        if (!string.IsNullOrEmpty(search))
        {
            DataTable dtSearchResult = FunctionClassObj.GetData("SELECT * FROM Process_" + lblprocessid.Text + "_Master WHERE 1 = 1 " + search);
            if (Hide_Phone_No.Checked)
            {
                dtSearchResult.Columns.Remove("Phone_No");
                dtSearchResult.AcceptChanges();
            }
            gvSearchResult.DataSource = dtSearchResult;
            gvSearchResult.DataBind();
        }
        else
        {
            gvSearchResult.DataSource = FunctionClassObj.GetData("SELECT * FROM Process_" + lblprocessid.Text + "_Master WHERE 1 = 2");
            gvSearchResult.DataBind();
        }
        //Search.Update();
        ModalPopupExtender1.Show();
    }
    protected void lnkSelect_Click(object sender, EventArgs e)
    {
        LinkButton lnkbtn = (LinkButton)sender;
        if (lnkbtn != null)
        {
            string masterId = lnkbtn.CommandArgument.ToString();
            if (ViewState["dtProcessMaster"] != null)
                dtProcessMaster = (DataTable)ViewState["dtProcessMaster"];
            else
                dtProcessMaster = FunctionClassObj.GetData("SELECT * FROM Process_Master WHERE pid = " + lblprocessid.Text + " and Agent_Visible = 1 ORDER BY Order_No");
            FunctionClassObj.SelectValue(ref SANBranch_Master, FunctionClassObj.ExecuteScalarString("SELECT Branch_Id FROM Process_" + lblprocessid.Text + "_Master WHERE Master_Id = '" + masterId + "'"));
            DisplayData(FunctionClassObj.GetData("SELECT * FROM Process_" + lblprocessid.Text + "_Master WHERE Master_Id = '" + masterId + "'"));
            UpdatePanel1.Update();
            Search.Update();
            ModalPopupExtender1.Show();
        }
    }
    public void DisplayData(DataTable dataTableMaster)
    {
        for (int i = 0; i < dtProcessMaster.Rows.Count; i++)
        {
            string Field_Name = dtProcessMaster.Rows[i]["Field_Name"].ToString();
            string Field_Value = dataTableMaster.Rows[0][Field_Name].ToString();
            string Control_Type = dtProcessMaster.Rows[i]["Control_Type"].ToString();
            if (Control_Type == "Text Box")
            {
                TextBox1 = (TextBox)PlaceHolder_Master.FindControl(Field_Name);
                if (TextBox1 != null)
                    TextBox1.Text = Field_Value;
            }
            else if (Control_Type == "Combo Box")
            {
                DropDownList1 = (DropDownList)PlaceHolder_Master.FindControl(Field_Name);
                if (DropDownList1 != null)
                    FunctionClassObj.SelectValue(ref DropDownList1, Field_Value);
            }
            else if (Control_Type == "List Box")
            {
                ListBox1 = (ListBox)PlaceHolder_Master.FindControl(Field_Name);
                if (ListBox1 != null)
                    FunctionClassObj.SelectValue(ref ListBox1, Field_Value);
            }
            else if (Control_Type == "Radio Button")
            {
                RadioButtonList1 = (RadioButtonList)PlaceHolder_Master.FindControl(Field_Name);
                if (RadioButtonList1 != null)
                    FunctionClassObj.SelectValue(ref RadioButtonList1, Field_Value);
            }
            else if (Control_Type == "Check Box")
            {
                CheckBox1 = (CheckBox)PlaceHolder_Master.FindControl(Field_Name);
                if (CheckBox1 != null)
                {
                    if (FunctionClassObj.StringToBool(Field_Value) == "1")
                        CheckBox1.Checked = true;
                }
            }
            else if (Control_Type == "Date Time Picker")
            {
                TextBox1 = (TextBox)PlaceHolder_Master.FindControl(Field_Name);
                if (TextBox1 != null)
                {
                    if (Field_Value.Trim() == "")
                        TextBox1.Text = "";
                    else
                    {
                        string date = Field_Value.ToString().Substring(0, 10);
                        if (date.IndexOf(' ') > 0)
                            date = date.Substring(0, date.IndexOf(' '));
                        string[] datesplit = new string[3];
                        datesplit = date.Split('/');
                        TextBox1.Text = datesplit[1] + "/" + datesplit[0] + "/" + datesplit[2];
                    }
                }
            }
        }
    }
    protected void gvSearchResult_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        string masterId = gvSearchResult.Rows[e.NewSelectedIndex].Cells[1].Text.ToString();
        if (ViewState["dtProcessMaster"] != null)
            dtProcessMaster = (DataTable)ViewState["dtProcessMaster"];
        else
            dtProcessMaster = FunctionClassObj.GetData("SELECT * FROM Process_Master WHERE pid = " + lblprocessid.Text + " AND Agent_Visible = 1 ORDER BY Order_No");
        DisplayData(FunctionClassObj.GetData("SELECT * FROM Process_" + lblprocessid.Text + "_Master WHERE Master_Id = '" + masterId + "'"));
        //UpdatePanel1.Update();
        //Search.Update();
        ModalPopupExtender1.Show();
    }
    protected void lnkShowCenterDetails_Click(object sender, EventArgs e)
    {
        if (SANBranch_Master.SelectedValue != "0")
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Script", "window.open('BranchDetail.aspx?BranchId=" + SANBranch_Master.SelectedValue + "','BranchDetails','height=400,width=500,resizable=yes')", true);
    }
    protected void ExecuteURL()
    {
        bool check = false;
        string sFields = string.Empty;
        string smsTemplate = Save_Url.Text;
        int m = 0;
        int startIndex = 0;
        int endIndex = 0;
        smsTemplate = smsTemplate.Replace("<<Phone_No>>", Phone_No.Text.Replace("'", "").Trim());
        smsTemplate = smsTemplate.Replace("<<Master_Id>>", Master_Id.Text.Replace("'", "").Trim());
        smsTemplate = smsTemplate.Replace("<<Disposition>>", ddlCallStatus.SelectedValue);
        smsTemplate = smsTemplate.Replace("<<CallBackDate>>", txtCallBackDate.Text + " " + callbacktimeHr.SelectedItem.Text + ":" + callbacktimeMm.SelectedItem.Text);
        while (smsTemplate.Length > m)
        {
            startIndex = smsTemplate.IndexOf("<", m);
            if (startIndex > 0)
            {
                startIndex = startIndex + 2;
                endIndex = smsTemplate.IndexOf(">", startIndex);
                if (endIndex > 0)
                    sFields += " " + smsTemplate.Substring(startIndex, endIndex - startIndex);
            }
            if (startIndex == -1)
                break;
            m = endIndex + 2;
        }
        string[] checkField = sFields.Split(' ');
        for (int j = 0; checkField.Length > j; j++)
        {
            check = false;
            dtMain = FunctionClassObj.GetData("SELECT Field_Name,Control_Type FROM Process_Master WHERE Pid = " + lblprocessid.Text + " AND Field_Name = '" + checkField[j] + "'");
            if (dtMain.Rows.Count > 0)
            {
                check = true;
                if (dtMain.Rows[0]["Control_Type"].ToString() == "Phone No")
                {
                    TextBox1 = (TextBox)PlaceHolder_Master.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                    if (TextBox1 != null)
                        smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", TextBox1.Text.Trim().Replace("'", "''"));
                    else
                        smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", "");
                }
                else if (dtMain.Rows[0]["Control_Type"].ToString() == "Text Box")
                {
                    TextBox1 = (TextBox)PlaceHolder_Master.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                    if (TextBox1 != null)
                        smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", TextBox1.Text.Trim().Replace("'", "''"));
                    else
                        smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", "");
                }
                else if (dtMain.Rows[0]["Control_Type"].ToString() == "Combo Box")
                {
                    DropDownList1 = (DropDownList)PlaceHolder_Master.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                    if (DropDownList1 != null)
                        smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", DropDownList1.SelectedItem.Text);
                    else
                        smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", "");
                }
                else if (dtMain.Rows[0]["Control_Type"].ToString() == "List Box")
                {
                    ListBox1 = (ListBox)PlaceHolder_Master.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                    if (ListBox1 != null)
                        smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", ListBox1.SelectedItem.Text);
                    else
                        smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", "");
                }
                else if (dtMain.Rows[0]["Control_Type"].ToString() == "Date Time Picker")
                {
                    TextBox1 = (TextBox)PlaceHolder_Master.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                    if (TextBox1 != null)
                        smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", TextBox1.Text.Trim().Replace("'", "''"));
                    else
                        smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", "");
                }
            }
            if (check == false)
            {
                dtMain = FunctionClassObj.GetData("SELECT Field_Name,Control_Type FROM Process_Log WHERE Pid = " + lblprocessid.Text + " AND Field_Name = '" + checkField[j] + "'");
                if (dtMain.Rows.Count > 0)
                {
                    if (dtMain.Rows[0]["Control_Type"].ToString() == "Phone No")
                    {
                        TextBox1 = (TextBox)PlaceHolder_Log.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                        if (TextBox1 != null)
                            smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", TextBox1.Text.Trim().Replace("'", "''"));
                        else
                            smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", "");
                    }
                    else if (dtMain.Rows[0]["Control_Type"].ToString() == "Text Box")
                    {
                        TextBox1 = (TextBox)PlaceHolder_Log.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                        if (TextBox1 != null)
                            smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", TextBox1.Text.Trim().Replace("'", "''"));
                        else
                            smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", "");
                    }
                    else if (dtMain.Rows[0]["Control_Type"].ToString() == "Combo Box")
                    {
                        DropDownList1 = (DropDownList)PlaceHolder_Log.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                        if (DropDownList1 != null)
                            smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", DropDownList1.SelectedItem.Text);
                        else
                            smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", "");
                    }
                    else if (dtMain.Rows[0]["Control_Type"].ToString() == "List Box")
                    {
                        ListBox1 = (ListBox)PlaceHolder_Log.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                        if (ListBox1 != null)
                            smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", ListBox1.SelectedItem.Text);
                        else
                            smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", "");
                    }
                    else if (dtMain.Rows[0]["Control_Type"].ToString() == "Date Time Picker")
                    {
                        TextBox1 = (TextBox)PlaceHolder_Log.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                        if (TextBox1 != null)
                            smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", TextBox1.Text.Trim().Replace("'", "''"));
                        else
                            smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", "");
                    }
                }
            }
        }
        //sukhveer
        Session["smsTemplate"] = smsTemplate;
        //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", "fn_OpenPopUp2('CallBackManagement.aspx','CallBackManagement')", true);
        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Script123", "window.open('" + smsTemplate + "','ScriptSaveURL','height=400,width=500,resizable=yes')", true);
        //FunctionClassObj.ExecuteURLInBackground(smsTemplate);
    }
    
    protected void SendSMS()
    {
        bool check= false;
        string sFields = string.Empty;
        dtTemp = FunctionClassObj.GetData("SELECT Template_Master.Template_Text,Template_Master.Max_Length,SMS_Disposition.Other_No,SMS_Disposition.Send_To_Client,SMS_Disposition.Send_To_Branch,SMS_Disposition.Default_No_Field,Other_Field,Other_Field_Value FROM Template_Master JOIN SMS_Disposition ON SMS_Disposition.Template_ID = Template_Master.Template_ID WHERE Call_Status = '" + ddlCallStatus.SelectedItem.Text + "' AND Pid = " + lblprocessid.Text);
        for (int i = 0; i < dtTemp.Rows.Count; i++)
        {
            try
            {
                string controlname = dtTemp.Rows[i]["Other_Field"].ToString();
                if (!string.IsNullOrEmpty(controlname))
                {
                    string controlValue = dtTemp.Rows[i]["Other_Field_Value"].ToString();
                    string controlType = Page.FindControl(controlname).GetType().ToString();
                    if (controlType == "System.Web.UI.WebControls.TextBox")
                    {
                        TextBox txt = (TextBox)Page.FindControl(controlname);
                        if (txt != null && controlValue.ToLower().Trim().Replace("'", "") == txt.Text.ToLower().Trim().Replace("'", ""))
                            dtTemp = FunctionClassObj.FilterRecords(dtTemp, "Other_Field_Value='" + controlValue + "'");
                        else
                            dtTemp = FunctionClassObj.FilterRecords(dtTemp, "Other_Field_Value='' OR Other_Field_Value IS NULL");
                    }
                    else
                    {
                        DropDownList ddl = (DropDownList)Page.FindControl(controlname);
                        if (ddl != null && controlValue.ToLower().Trim().Replace("'", "") == ddl.SelectedItem.Text.ToLower().Trim().Replace("'", ""))
                            dtTemp = FunctionClassObj.FilterRecords(dtTemp, "Other_Field_Value='" + controlValue + "'");
                        else
                            dtTemp = FunctionClassObj.FilterRecords(dtTemp, "Other_Field_Value='' OR Other_Field_Value IS NULL");
                    }
                }
            }
            catch (Exception ex)
            {
                continue;
            }
        }
        DataTable dtProcessDataMaster = FunctionClassObj.GetData("SELECT * FROM Process_" + lblprocessid.Text + "_Master WHERE Master_Id = '" + Master_Id.Text + "'");
        DataTable dtProcessLogMaster = FunctionClassObj.GetData("SELECT * FROM Process_" + lblprocessid.Text + "_Log WHERE Log_Id = '" + lblLogId.Text + "'");
        DataTable dtBranchMaster = FunctionClassObj.GetData("SELECT [Branch_Name],[Contact_Person],[Branch_Address],[Branch_PhoneNo],[Branch_EmailId] FROM Branch_Master WHERE Branch_Id = '" + FunctionClassObj.StringToInt(SANBranch_Master.SelectedValue) + "'");
        if (dtTemp.Rows.Count > 0)
        {
            for (int i = 0; dtTemp.Rows.Count > i; i++)
            {
                string smsTemplate = dtTemp.Rows[i]["Template_Text"].ToString();
                #region Branch Fields
                if (dtBranchMaster.Rows.Count > 0)
                {
                    smsTemplate = smsTemplate.Replace("<<Branch_Name>>", dtBranchMaster.Rows[0]["Branch_Name"].ToString());
                    smsTemplate = smsTemplate.Replace("<<Branch_Contact_Person>>", dtBranchMaster.Rows[0]["Contact_Person"].ToString());
                    smsTemplate = smsTemplate.Replace("<<Branch_Address>>", dtBranchMaster.Rows[0]["Branch_Address"].ToString());
                    smsTemplate = smsTemplate.Replace("<<Branch_PhoneNo>>", dtBranchMaster.Rows[0]["Branch_PhoneNo"].ToString());
                    smsTemplate = smsTemplate.Replace("<<Branch_EmailId>>", dtBranchMaster.Rows[0]["Branch_EmailId"].ToString());
                }
                #endregion
                int m = 0;
                int startIndex = 0;
                int endIndex = 0;
                while (smsTemplate.Length > m)
                {
                    startIndex = smsTemplate.IndexOf("<", m);
                    if (startIndex > 0)
                    {
                        startIndex = startIndex + 2;
                        endIndex = smsTemplate.IndexOf(">", startIndex);
                        if (endIndex > 0)
                            sFields += " " + smsTemplate.Substring(startIndex, endIndex - startIndex);
                    }
                    if (startIndex == -1)
                        break;
                    m = endIndex + 2;
                }
                string[] checkField = sFields.Split(' ');
                check = false;
                for (int j = 0; checkField.Length > j; j++)
                {
                    dtMain = FunctionClassObj.GetData("SELECT Field_Name,Control_Type FROM Process_Master WHERE Pid = " + lblprocessid.Text + " AND Field_Name = '" + checkField[j] + "'");
                    if (dtMain.Rows.Count > 0)
                    {
                        check = true;
                        smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", dtProcessDataMaster.Rows[0][dtMain.Rows[0]["Field_Name"].ToString()].ToString());
                    }
                    if (check == false)
                    {
                        dtMain = FunctionClassObj.GetData("SELECT Field_Name,Control_Type FROM Process_Log WHERE Pid =" + lblprocessid.Text + " AND Field_Name = '" + checkField[j] + "'");
                        if (dtMain.Rows.Count > 0)
                            smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", dtProcessLogMaster.Rows[0][dtMain.Rows[0]["Field_Name"].ToString()].ToString());
                    }
                }
                #region Process Master
                for (int j = 0; j < dtProcessDataMaster.Columns.Count; j++)
                    smsTemplate = smsTemplate.Replace("<<" + dtProcessDataMaster.Columns[j].ColumnName.ToString() + ">>", dtProcessDataMaster.Rows[0][dtProcessDataMaster.Columns[j].ColumnName.ToString()].ToString());
                #endregion
                #region Process Log
                for (int j = 0; j < dtProcessLogMaster.Columns.Count; j++)
                    smsTemplate = smsTemplate.Replace("<<" + dtProcessLogMaster.Columns[j].ColumnName.ToString() + ">>", dtProcessLogMaster.Rows[0][dtProcessLogMaster.Columns[j].ColumnName.ToString()].ToString());
                #endregion

                smsTemplate = smsTemplate.Replace("<<Agent_Name>>", Session["Agent_Name"].ToString()); 
                
                if (smsTemplate.Length > Convert.ToInt32(dtTemp.Rows[i]["Max_Length"]) && Convert.ToInt32(dtTemp.Rows[i]["Max_Length"]) != 0)
                    smsTemplate = smsTemplate.Substring(0, Convert.ToInt32(dtTemp.Rows[i]["Max_Length"]));
                string phone_nos;
                phone_nos = "";
                if (Convert.ToBoolean(dtTemp.Rows[i]["Send_To_Client"]) && FunctionClassObj.IsMobileNo(Phone_No.Text.Trim()))
                    phone_nos = Phone_No.Text.Trim();
                if (dtTemp.Rows[i]["Other_No"].ToString() != "" && dtTemp.Rows[i]["Other_No"] != DBNull.Value)
                {
                    if (phone_nos != "")
                        phone_nos += ",";
                    phone_nos += dtTemp.Rows[i]["Other_No"].ToString();
                }
                if (dtTemp.Rows[i]["Default_No_Field"].ToString() != "" && dtTemp.Rows[i]["Default_No_Field"].ToString() != "--Select--")
                {
                    TextBox1 = (TextBox)PlaceHolder_Master.FindControl(dtTemp.Rows[i]["Default_No_Field"].ToString());
                    if (TextBox1 != null)
                    {
                        if (FunctionClassObj.IsMobileNo(TextBox1.Text.Trim()))
                        {
                            if (phone_nos != "")
                                phone_nos += ",";
                            phone_nos += TextBox1.Text.Trim();
                        }
                    }
                }
                if (Convert.ToBoolean(dtTemp.Rows[i]["Send_To_Branch"]))
                {
                    string _PhoneNo = FunctionClassObj.ExecuteScalarString("SELECT Branch_PhoneNo FROM Branch_Master WHERE Branch_Id = '" + FunctionClassObj.StringToInt(SANBranch_Master.SelectedValue) + "'");
                    if (_PhoneNo != "")
                    {
                        if (phone_nos != "")
                            phone_nos += ",";
                        phone_nos += _PhoneNo;
                    }
                }
                if (phone_nos != "")
                {
                    string lblMessage = FunctionClassObj.SendSMS(FunctionClassObj.ExecuteScalarString("SELECT Authentication_String FROM Process WHERE Pid = '" + FunctionClassObj.StringToInt(lblprocessid.Text) + "'"), phone_nos, smsTemplate);
                    FunctionClassObj.generateSMSLog(phone_nos, smsTemplate.Replace("'", "''"), lblMessage.Replace("'", "''"), lblagentName.Text.Replace("'", "''"), lblprocessid.Text, FunctionClassObj.StringToInt(lblCampaignId.Text));
                }
            }
        }
    }
    protected void SendDIDSMS()
    {
        bool check = false;
        string sFields = string.Empty;
        dtTemp = FunctionClassObj.GetData("SELECT Template_Text FROM Template_Master WHERE Template_Id = '" + DIDTemplate_Id.Text + "'");
        if (dtTemp.Rows.Count > 0)
        {
            string smsTemplate = "";
            for (int i = 0; dtTemp.Rows.Count > i; i++)
            {
                smsTemplate = Convert.ToString(dtTemp.Rows[i]["Template_Text"]);
                int m = 0;
                int startIndex = 0;
                int endIndex = 0;
                smsTemplate = smsTemplate.Replace("<<Phone_No>>", Phone_No.Text.Replace("'", "").Trim());
                smsTemplate = smsTemplate.Replace("<<Master_Id>>", Master_Id.Text.Replace("'", "").Trim());
                while (smsTemplate.Length > m)
                {
                    startIndex = smsTemplate.IndexOf("<", m);
                    if (startIndex > 0)
                    {
                        startIndex = startIndex + 2;
                        endIndex = smsTemplate.IndexOf(">", startIndex);
                        if (endIndex > 0)
                            sFields += " " + smsTemplate.Substring(startIndex, endIndex - startIndex);
                    }
                    if (startIndex == -1)
                        break;
                    m = endIndex + 2;
                }
                string[] checkField = sFields.Split(' ');
                for (int j = 0; checkField.Length > j; j++)
                {
                    check = false;
                    dtMain = FunctionClassObj.GetData("SELECT Field_Name,Control_Type FROM Process_Master WHERE Pid = " + lblprocessid.Text + " AND Field_Name = '" + checkField[j] + "'");
                    if (dtMain.Rows.Count > 0)
                    {
                        check = true;
                        if (dtMain.Rows[0]["Control_Type"].ToString() == "Phone No")
                        {
                            TextBox1 = (TextBox)PlaceHolder_Master.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                            if (TextBox1 != null)
                                smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", TextBox1.Text.Trim().Replace("'", "''"));
                            else
                                smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", "");
                        }
                        else if (dtMain.Rows[0]["Control_Type"].ToString() == "Text Box")
                        {
                            TextBox1 = (TextBox)PlaceHolder_Master.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                            if (TextBox1 != null)
                                smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", TextBox1.Text.Trim().Replace("'", "''"));
                            else
                                smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", "");
                        }
                        else if (dtMain.Rows[0]["Control_Type"].ToString() == "Combo Box")
                        {
                            DropDownList1 = (DropDownList)PlaceHolder_Master.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                            if (DropDownList1 != null)
                                smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", DropDownList1.SelectedItem.Text);
                            else
                                smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", "");
                        }
                        else if (dtMain.Rows[0]["Control_Type"].ToString() == "List Box")
                        {
                            ListBox1 = (ListBox)PlaceHolder_Master.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                            if (ListBox1 != null)
                                smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", ListBox1.SelectedItem.Text);
                            else
                                smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", "");
                        }
                        else if (dtMain.Rows[0]["Control_Type"].ToString() == "Date Time Picker")
                        {
                            TextBox1 = (TextBox)PlaceHolder_Master.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                            if (TextBox1 != null)
                                smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", TextBox1.Text.Trim().Replace("'", "''"));
                            else
                                smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", "");
                        }
                    }
                    if (check == false)
                    {
                        dtMain = FunctionClassObj.GetData("SELECT Field_Name,Control_Type FROM Process_Log WHERE Pid = " + lblprocessid.Text + " AND Field_Name = '" + checkField[j] + "'");
                        if (dtMain.Rows.Count > 0)
                        {
                            if (dtMain.Rows[0]["Control_Type"].ToString() == "Phone No")
                            {
                                TextBox1 = (TextBox)PlaceHolder_Log.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                                if (TextBox1 != null)
                                    smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", TextBox1.Text.Trim().Replace("'", "''"));
                                else
                                    smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", "");
                            }
                            else if (dtMain.Rows[0]["Control_Type"].ToString() == "Text Box")
                            {
                                TextBox1 = (TextBox)PlaceHolder_Log.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                                if (TextBox1 != null)
                                    smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", TextBox1.Text.Trim().Replace("'", "''"));
                                else
                                    smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", "");
                            }
                            else if (dtMain.Rows[0]["Control_Type"].ToString() == "Combo Box")
                            {
                                DropDownList1 = (DropDownList)PlaceHolder_Log.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                                if (DropDownList1 != null)
                                    smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", DropDownList1.SelectedItem.Text);
                                else
                                    smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", "");
                            }
                            else if (dtMain.Rows[0]["Control_Type"].ToString() == "List Box")
                            {
                                ListBox1 = (ListBox)PlaceHolder_Log.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                                if (ListBox1 != null)
                                    smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", ListBox1.SelectedItem.Text);
                                else
                                    smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", "");
                            }
                            else if (dtMain.Rows[0]["Control_Type"].ToString() == "Date Time Picker")
                            {
                                TextBox1 = (TextBox)PlaceHolder_Log.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                                if (TextBox1 != null)
                                    smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", TextBox1.Text.Trim().Replace("'", "''"));
                                else
                                    smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", "");
                            }
                        }
                    }
                }

                if (lblDIDMobile_No.Text != "")
                {
                    string lblMessage = FunctionClassObj.SendSMS(FunctionClassObj.ExecuteScalarString("SELECT Authentication_String FROM Process WHERE Pid = '" + FunctionClassObj.StringToInt(lblprocessid.Text) + "'"), lblDIDMobile_No.Text, smsTemplate);
                    FunctionClassObj.generateSMSLog(lblDIDMobile_No.Text, smsTemplate.Replace("'", "''"), lblMessage.Replace("'", "''"), lblagentName.Text.Replace("'", "''"), lblprocessid.Text, FunctionClassObj.StringToInt(lblCampaignId.Text));
                }
            }
        }
    }
    public void SendEmail()
    {
        bool check = false;
        string sFields = string.Empty;
        dtTemp = FunctionClassObj.GetData("SELECT Account_Id,Email_Template.Email_Content,Email_Template.Email_Subject,Email_Disposition.Other_Email,Email_Disposition.Send_To_Client,Email_Disposition.Default_Email_Field,Email_Disposition.Send_To_Branch,Other_Field,Other_Field_Value FROM Email_Template JOIN Email_Disposition ON Email_Disposition.Email_Template_ID = Email_Template.Email_Template_ID WHERE Call_Status = '" + ddlCallStatus.SelectedItem.Text + "' AND Pid = " + lblprocessid.Text);
        for (int i = 0; i < dtTemp.Rows.Count; i++)
        {
            try
            {
                string controlname = dtTemp.Rows[i]["Other_Field"].ToString();
                if (!string.IsNullOrEmpty(controlname))
                {
                    string controlValue = dtTemp.Rows[i]["Other_Field_Value"].ToString();
                    string controlType = Page.FindControl(controlname).GetType().ToString();
                    if (controlType == "System.Web.UI.WebControls.TextBox")
                    {
                        TextBox txt = (TextBox)Page.FindControl(controlname);
                        if (txt != null && controlValue.ToLower().Trim().Replace("'", "") == txt.Text.ToLower().Trim().Replace("'", ""))
                            dtTemp = FunctionClassObj.FilterRecords(dtTemp, "Other_Field_Value='" + controlValue + "'");
                        else
                            dtTemp = FunctionClassObj.FilterRecords(dtTemp, "Other_Field_Value='' OR Other_Field_Value IS NULL");
                    }
                    else
                    {
                        DropDownList ddl = (DropDownList)Page.FindControl(controlname);
                        if (ddl != null && controlValue.ToLower().Trim().Replace("'", "") == ddl.SelectedItem.Text.ToLower().Trim().Replace("'", ""))
                            dtTemp = FunctionClassObj.FilterRecords(dtTemp, "Other_Field_Value='" + controlValue + "'");
                        else
                            dtTemp = FunctionClassObj.FilterRecords(dtTemp, "Other_Field_Value='' OR Other_Field_Value IS NULL");
                    }
                }
            }
            catch (Exception ex)
            {
                continue;
            }
        }
        for (int i = 0; dtTemp.Rows.Count > i; i++)
        {
            string emailTemplate = dtTemp.Rows[i]["Email_Content"].ToString();

            ////Up to 01/05/2013
            //int m = 0;
            //int startIndex = 0;
            //int endIndex = 0;
            ////Up to 01/05/2013

            emailTemplate = emailTemplate.Replace("##Phone_No##", Phone_No.Text.Replace("'", "").Trim());
            emailTemplate = emailTemplate.Replace("##Master_Id##", Master_Id.Text.Replace("'", "").Trim());
            DataTable dtBranchMaster = FunctionClassObj.GetData("SELECT [Branch_Name],[Contact_Person],[Branch_Address],[Branch_PhoneNo],[Branch_EmailId] FROM Branch_Master WHERE Branch_Id = '" + FunctionClassObj.StringToInt(SANBranch_Master.SelectedValue) + "'");
            if (dtBranchMaster.Rows.Count > 0)
            {
                emailTemplate = emailTemplate.Replace("##Branch_Name##", dtBranchMaster.Rows[0]["Branch_Name"].ToString());
                emailTemplate = emailTemplate.Replace("##Branch_Contact_Person##", dtBranchMaster.Rows[0]["Contact_Person"].ToString());
                emailTemplate = emailTemplate.Replace("##Branch_Address##", dtBranchMaster.Rows[0]["Branch_Address"].ToString());
                emailTemplate = emailTemplate.Replace("##Branch_PhoneNo##", dtBranchMaster.Rows[0]["Branch_PhoneNo"].ToString());
                emailTemplate = emailTemplate.Replace("##Branch_EmailId##", dtBranchMaster.Rows[0]["Branch_EmailId"].ToString());
            }

            //New Coding 01/05/2013
            string pattern = "##.*?.##";
            MatchCollection matches = Regex.Matches(emailTemplate, pattern);
            foreach (Match match in matches)
                sFields += "," + match.Value.Replace("##", "");
            //New Coding 01/05/2013

            ////Up to 01/05/2013
            //while (emailTemplate.Length > m)
            //{
            //    startIndex = emailTemplate.IndexOf("##", m);
            //    if (startIndex > 0)
            //    {
            //        startIndex = startIndex + 2;
            //        endIndex = emailTemplate.IndexOf("##", startIndex);
            //        if (endIndex > 0)
            //            sFields += "," + emailTemplate.Substring(startIndex, endIndex - startIndex);
            //    }
            //    if (startIndex == -1)
            //        break;
            //    m = endIndex + 2;
            //}            
            ////Up to 01/05/2013
            string[] checkField = sFields.Split(',');

            for (int j = 0; checkField.Length > j; j++)
            {
                check = false;
                dtMain = FunctionClassObj.GetData("SELECT Field_Name,Control_Type FROM Process_Master WHERE Pid = " + lblprocessid.Text + " AND Field_Name = '" + checkField[j] + "'");
                if (dtMain.Rows.Count > 0)
                {
                    check = true;
                    if (dtMain.Rows[0]["Control_Type"].ToString() == "Phone No")
                    {
                        TextBox1 = (TextBox)PlaceHolder_Master.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                        if (TextBox1 != null)
                            emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", TextBox1.Text.Trim().Replace("'", "''"));
                        else
                            emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", "");
                    }
                    else if (dtMain.Rows[0]["Control_Type"].ToString() == "Text Box")
                    {
                        TextBox1 = (TextBox)PlaceHolder_Master.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                        if (TextBox1 != null)
                            emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", TextBox1.Text.Trim().Replace("'", "''"));
                        else
                            emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", "");
                    }
                    else if (dtMain.Rows[0]["Control_Type"].ToString() == "Combo Box")
                    {
                        DropDownList1 = (DropDownList)PlaceHolder_Master.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                        if (DropDownList1 != null)
                            emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", DropDownList1.SelectedItem.Text);
                        else
                            emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", "");
                    }
                    else if (dtMain.Rows[0]["Control_Type"].ToString() == "List Box")
                    {
                        ListBox1 = (ListBox)PlaceHolder_Master.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                        if (ListBox1 != null)
                            emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", ListBox1.SelectedItem.Text);
                        else
                            emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", "");
                    }
                    else if (dtMain.Rows[0]["Control_Type"].ToString() == "Date Time Picker")
                    {
                        TextBox1 = (TextBox)PlaceHolder_Master.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                        if (TextBox1 != null)
                            emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", TextBox1.Text.Trim().Replace("'", "''"));
                        else
                            emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", "");
                    }
                }
                if (check == false)
                {
                    dtMain = FunctionClassObj.GetData("SELECT Field_Name,Control_Type FROM Process_Log WHERE Pid = " + lblprocessid.Text + " AND Field_Name = '" + checkField[j] + "'");
                    if (dtMain.Rows.Count > 0)
                    {
                        if (dtMain.Rows[0]["Control_Type"].ToString() == "Phone No")
                        {
                            TextBox1 = (TextBox)PlaceHolder_Log.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                            if (TextBox1 != null)
                                emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", TextBox1.Text.Trim().Replace("'", "''"));
                            else
                                emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", "");
                        }
                        else if (dtMain.Rows[0]["Control_Type"].ToString() == "Text Box")
                        {
                            TextBox1 = (TextBox)PlaceHolder_Log.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                            if (TextBox1 != null)
                                emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", TextBox1.Text.Trim().Replace("'", "''"));
                            else
                                emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", "");
                        }
                        else if (dtMain.Rows[0]["Control_Type"].ToString() == "Combo Box")
                        {
                            DropDownList1 = (DropDownList)PlaceHolder_Log.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                            if (DropDownList1 != null)
                                emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", DropDownList1.SelectedItem.Text);
                            else
                                emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", "");
                        }
                        else if (dtMain.Rows[0]["Control_Type"].ToString() == "List Box")
                        {
                            ListBox1 = (ListBox)PlaceHolder_Log.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                            if (ListBox1 != null)
                                emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", ListBox1.SelectedItem.Text);
                            else
                                emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", "");
                        }
                        else if (dtMain.Rows[0]["Control_Type"].ToString() == "Date Time Picker")
                        {
                            TextBox1 = (TextBox)PlaceHolder_Log.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                            if (TextBox1 != null)
                                emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", TextBox1.Text.Trim().Replace("'", "''"));
                            else
                                emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", "");
                        }
                    }
                }
            }
            string emailID;
            emailID = "";
            if (Convert.ToBoolean(dtTemp.Rows[i]["Send_To_Client"]) && dtTemp.Rows[i]["Default_Email_Field"].ToString() != "")
            {
                TextBox1 = (TextBox)PlaceHolder_Master.FindControl(dtTemp.Rows[i]["Default_Email_Field"].ToString());
                if (TextBox1 != null)
                    emailID = TextBox1.Text.Trim();
            }
            if (dtTemp.Rows[i]["Other_Email"].ToString() != "" && dtTemp.Rows[i]["Other_Email"] != DBNull.Value)
            {
                if (emailID != "")
                    emailID += ",";
                emailID += dtTemp.Rows[i]["Other_Email"].ToString();
            }
            if (Convert.ToBoolean(dtTemp.Rows[i]["Send_To_Branch"]))
            {
                string email = FunctionClassObj.ExecuteScalarString("SELECT Branch_EmailId FROM Branch_Master WHERE Branch_Id = '" + FunctionClassObj.StringToInt(SANBranch_Master.SelectedValue) + "'");
                if (email != "")
                {
                    if (emailID != "")
                        emailID += ",";
                    emailID += email;
                }
            }
            if (emailID != "")
                SendEmail(dtTemp.Rows[i]["Account_Id"].ToString(), emailID, dtTemp.Rows[i]["Email_Subject"].ToString(), Server.HtmlDecode(emailTemplate));
        }
    }
    public void SendDIDEmail()
    {
        bool check = false;
        string sFields = string.Empty;
        string emailTemplate = FunctionClassObj.ExecuteScalarString("SELECT Email_Content FROM Email_Template WHERE Email_Template_Id = " + lblEmailTemplate_Id.Text);
        emailTemplate = emailTemplate.Replace("##Phone_No##", Phone_No.Text.Replace("'", "").Trim());
        emailTemplate = emailTemplate.Replace("##Master_Id##", Master_Id.Text.Replace("'", "").Trim());
        int m = 0;
        int startIndex = 0;
        int endIndex = 0;
        while (emailTemplate.Length > m)
        {
            startIndex = emailTemplate.IndexOf("##", m);
            if (startIndex > 0)
            {
                startIndex = startIndex + 2;
                endIndex = emailTemplate.IndexOf("##", startIndex);
                if (endIndex > 0)
                    sFields += " " + emailTemplate.Substring(startIndex, endIndex - startIndex);
            }
            if (startIndex == -1)
                break;
            m = endIndex + 2;
        }
        string[] checkField = sFields.Split(' ');
        for (int j = 0; checkField.Length > j; j++)
        {
            check = false;
            dtMain = FunctionClassObj.GetData("SELECT Field_Name,Control_Type FROM Process_Master WHERE Pid = " + lblprocessid.Text + " AND Field_Name = '" + checkField[j] + "'");
            if (dtMain.Rows.Count > 0)
            {
                #region Process Master Fields
                check = true;
                if (dtMain.Rows[0]["Control_Type"].ToString() == "Phone No")
                {
                    TextBox1 = (TextBox)PlaceHolder_Master.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                    if (TextBox1 != null)
                        emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", TextBox1.Text.Trim().Replace("'", "''"));
                    else
                        emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", "");
                }
                else if (dtMain.Rows[0]["Control_Type"].ToString() == "Text Box")
                {
                    TextBox1 = (TextBox)PlaceHolder_Master.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                    if (TextBox1 != null)
                        emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", TextBox1.Text.Trim().Replace("'", "''"));
                    else
                        emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", "");
                }
                else if (dtMain.Rows[0]["Control_Type"].ToString() == "Combo Box")
                {
                    DropDownList1 = (DropDownList)PlaceHolder_Master.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                    if (DropDownList1 != null)
                        emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", DropDownList1.SelectedItem.Text);
                    else
                        emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", "");
                }
                else if (dtMain.Rows[0]["Control_Type"].ToString() == "List Box")
                {
                    ListBox1 = (ListBox)PlaceHolder_Master.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                    if (ListBox1 != null)
                        emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", ListBox1.SelectedItem.Text);
                    else
                        emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", "");
                }
                else if (dtMain.Rows[0]["Control_Type"].ToString() == "Date Time Picker")
                {
                    TextBox1 = (TextBox)PlaceHolder_Master.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                    if (TextBox1 != null)
                        emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", TextBox1.Text.Trim().Replace("'", "''"));
                    else
                        emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", "");
                }
                #endregion
            }
            if (check == false)
            {
                dtMain = FunctionClassObj.GetData("SELECT Field_Name,Control_Type FROM Process_Log WHERE Pid = " + lblprocessid.Text + " AND Field_Name = '" + checkField[j] + "'");
                if (dtMain.Rows.Count > 0)
                {
                    #region Process Log Fields
                    if (dtMain.Rows[0]["Control_Type"].ToString() == "Phone No")
                    {
                        TextBox1 = (TextBox)PlaceHolder_Log.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                        if (TextBox1 != null)
                            emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", TextBox1.Text.Trim().Replace("'", "''"));
                        else
                            emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", "");
                    }
                    else if (dtMain.Rows[0]["Control_Type"].ToString() == "Text Box")
                    {
                        TextBox1 = (TextBox)PlaceHolder_Log.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                        if (TextBox1 != null)
                            emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", TextBox1.Text.Trim().Replace("'", "''"));
                        else
                            emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", "");
                    }
                    else if (dtMain.Rows[0]["Control_Type"].ToString() == "Combo Box")
                    {
                        DropDownList1 = (DropDownList)PlaceHolder_Log.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                        if (DropDownList1 != null)
                            emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", DropDownList1.SelectedItem.Text);
                        else
                            emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", "");
                    }
                    else if (dtMain.Rows[0]["Control_Type"].ToString() == "List Box")
                    {
                        ListBox1 = (ListBox)PlaceHolder_Log.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                        if (ListBox1 != null)
                            emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", ListBox1.SelectedItem.Text);
                        else
                            emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", "");
                    }
                    else if (dtMain.Rows[0]["Control_Type"].ToString() == "Date Time Picker")
                    {
                        TextBox1 = (TextBox)PlaceHolder_Log.FindControl(dtMain.Rows[0]["Field_Name"].ToString());
                        if (TextBox1 != null)
                            emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", TextBox1.Text.Trim().Replace("'", "''"));
                        else
                            emailTemplate = emailTemplate.Replace("##" + dtMain.Rows[0]["Field_Name"].ToString() + "##", "");
                    }
                    #endregion
                }
            }
        }
        SendEmail(lblAccount_Id.Text, lblEmail_Id.Text, FunctionClassObj.ExecuteScalarString("SELECT Email_Subject FROM Email_Template WHERE Email_Template_Id = " + lblEmailTemplate_Id.Text), Server.HtmlDecode(emailTemplate));
    }
    public void SendEmail(string account_Id, string emailID, string Email_Subject, string emailTemplate)
    {
        dtMailDetail = FunctionClassObj.GetData("SELECT Email_Id,User_Name,Password,SMTP_Server,SMTP_IsSSl,SMTP_Port FROM Email_Accounts WHERE Account_Id = '" + FunctionClassObj.StringToInt(Convert.ToString(account_Id)) + "'");
        if (dtMailDetail.Rows.Count > 0)
        {
            string lblMessage = FunctionClassObj.SendMail(emailID, dtMailDetail.Rows[0]["Email_Id"].ToString(), Email_Subject, emailTemplate, dtMailDetail.Rows[0]["SMTP_Server"].ToString(), true, dtMailDetail.Rows[0]["User_Name"].ToString(), dtMailDetail.Rows[0]["Password"].ToString(), dtMailDetail.Rows[0]["SMTP_Port"].ToString(), Convert.ToBoolean(dtMailDetail.Rows[0]["SMTP_isSSL"].ToString()));
            FunctionClassObj.generateEMailLog(dtMailDetail.Rows[0]["EMail_Id"].ToString(), emailID, Email_Subject, emailTemplate, lblMessage, lblagentName.Text, account_Id);
        }
        else
            FunctionClassObj.generateEMailLog("", emailID, Email_Subject, emailTemplate, "Error sending email : no account is configured to send email from this processs.", lblagentName.Text, account_Id);
    }
    
    protected void Open_Click(object sender, EventArgs e)
    {
        try
        {
            Button btn = (Button)sender;
            TextBox1 = (TextBox)PlaceHolder_Master.FindControl(btn.ID.Substring(4));
            if (TextBox1 != null)
            {
                if (TextBox1.Text != "")
                {
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Open", "window.open('" + TextBox1.Text + "','Hyperlink1','channelmode=yes,resizable=yes,titlebar=yes,scrollbars=yes')", true);
                    //Response.Redirect(TextBox1.Text);
                }
            }
        }
        catch (Exception ex)
        {
            ShowError.Visible = true;
            ErrorMessage.Text = ex.Message;
        }
    }
    [System.Web.Services.WebMethod]
    public static string GetCRMState(string sExtentionNo)
    {
        FunciotnClass FunciotnClassObj = new FunciotnClass();
        //Timer1.Enabled = true;
        return FunciotnClassObj.ExecuteScalarString("SELECT Count(Extention_No) FROM Admin_Extention_Master WHERE CRM_State = 'Wrapup' AND Extention_No = '" + sExtentionNo + "'");
    }
    protected void btnAutoSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (savemycall())
            {
                UpdateCRMState("Idle");
                FunctionClassObj.ExecuteCommand("UPDATE Admin_Extention_Master SET SrNo = 0 WHERE Extention_No = '" + txtExtensionNo.Text + "'");
                Session["Phone_No"] = Session["SrNo"] = null;
                if (Request.QueryString["Log_Id"] == null)
                    Response.Redirect("CallWaiting.aspx", false);
                else
                    Response.Redirect("PreviewReport.aspx?recordPerPageQ=0", true);
            }
        }
        catch (Exception ex)
        {
            ShowError.Visible = true;
            ErrorMessage.Text = "Error Save " + ex.Message;
        }
    }
    protected void btnSendSMS_Click(object sender, EventArgs e)
    {
        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Script", "window.open('SendSMS.aspx?ProcessId=" + lblprocessid.Text + "&PhoneNo=" + Phone_No.Text + "','SendSMS','height=400,width=350,resizable=yes')", true);
    }
    protected void imgBtnSaveNext_Click(object sender, EventArgs e)
    {
        try
        {
            if (ddlCallStatus.SelectedIndex == 0 || ddlCallStatus.SelectedValue == "AutoSave")
            {
                DisplayMessage("Please Provide Call Disposition Status.");
                return;
            }
            else if (savemycall())
            {
                if (!string.IsNullOrEmpty(Save_Url.Text))
                {
                    ExecuteURL();
                    Session["Command"] = "SaveNextClick";
                    Timer1.Enabled = true;
                }
                else
                {
                    UpdateCRMState("Idle");
                    Session["Phone_No"] = Session["SrNo"] = Session["CallBackPhoneNo"] = Session["CallBackTime"] = Session["CallAgainType"] =
Session["dialerincoming"] = null;
                    FunctionClassObj.ExecuteCommand("UPDATE Admin_Extention_Master SET SrNo = 0 WHERE Extention_No = '" + txtExtensionNo.Text + "'");
                    string queryPhoneNo = "SELECT TOP 1 Master_Id,Phone_No,Call_Again_Time,Campaign_Id,Call_Again_PhoneNo,SrNo,Call_Again_Type FROM Process_" + lblprocessid.Text + "_Master t1"
                    + " JOIN Campaign_" + lblprocessid.Text + "_Mapping t2 ON t1.Master_Id = t2.Customer_Id JOIN File_Master t3 ON t2.File_Id = t3.File_Id WHERE isActive = 'True' AND Dialed = 'False' ";
                    if (dtProcess.Rows[0]["Callback_AgentMapping"].ToString() == "True")
                        queryPhoneNo += " AND Agent_Id = '" + lblagentName.Text + "'";
                    if (dtProcess.Rows[0]["Callback_FromAnyCampaign"].ToString() == "False")
                        queryPhoneNo += " AND Campaign_Id = " + lblCampaignId.Text;
                    dtProgressivedialing = FunctionClassObj.GetData(queryPhoneNo + " AND Call_Again_Time <= '" + DateTime.Now.ToString() + "' ORDER BY Call_Again_Time");
                    if (dtProgressivedialing.Rows.Count == 1 && (FunctionClassObj.ExecuteScalarString("SELECT Dial_Mode FROM Campaign_Master WHERE Campaign_Id = " + lblCampaignId.Text).ToLower() == "predictive"))
                    {
                        Session["CallBackPhoneNo"] = dtProgressivedialing.Rows[0]["Call_Again_PhoneNo"].ToString();
                        Session["CallBackTime"] = dtProgressivedialing.Rows[0]["Call_Again_Time"].ToString();
                        Session["CallAgainType"] = dtProgressivedialing.Rows[0]["Call_Again_Type"].ToString();
                        FunctionClassObj.ExecuteCommand("UPDATE Campaign_" + lblprocessid.Text + "_Mapping SET Dialed = 'True',Call_Again_Time = NULL,Call_Again_PhoneNo = NULL WHERE SrNo = " + dtProgressivedialing.Rows[0]["SrNo"].ToString());
                        Response.Redirect("CallTransfer.aspx?callmode=manualdialing&Caller_Id=" + FunctionClassObj.EncryptString(FunctionClassObj.StringToPhoneNo(dtProgressivedialing.Rows[0]["Call_Again_PhoneNo"].ToString())));
                    }
                    //if (FunctionClassObj.ExecuteScalarString("SELECT Dial_Mode FROM Campaign_Master WHERE Campaign_Id = " + lblCampaignId.Text).ToLower() == "preview")
                    //    Response.Redirect("PreviewDialing.aspx");
                    if (lblCallMode.Text == "previewdialing")
                        Response.Redirect("PreviewDialing.aspx", false);
                    Response.Redirect("CallTransfer.aspx", true);
                }
            }
        }
        catch (Exception ex)
        {
            ShowError.Visible = true;
            ErrorMessage.Text = "Error :" + ex.Message;
        }
    }
    protected void imgBtnNext_Click1(object sender, EventArgs e)
    {
        if (Session["Phone_No"] == null || lblCallMode.Text == "alternateno" || lblCallMode.Text == "preview")
        {
            Session["Phone_No"] = Session["SrNo"] = Session["CallBackPhoneNo"] = Session["CallBackTime"] = Session["CallAgainType"] =
Session["dialerincoming"] = null;
            FunctionClassObj.ExecuteCommand("UPDATE Admin_Extention_Master SET Caller_Id = NULL,Called_No = NULL,Unique_Id = NULL,SrNo = 0 WHERE Extention_No = '" + txtExtensionNo.Text + "'");
            Response.Redirect("CallTransfer.aspx", true);
        }
    }
    protected void imgBtnSave_Click1(object sender, EventArgs e)
    {
        try
        {
            if (imgBtnSave.Text == "Cancel")
            {
                Session["Phone_No"] = Session["SrNo"] = Session["CallBackPhoneNo"] = Session["CallBackTime"] = Session["CallAgainType"] = Session["LogId"] =
Session["dialerincoming"] = null;
                if (lblCallMode.Text == "previewdialing")
                    Response.Redirect("PreviewDialing.aspx", false);
                else
                    Response.Redirect("CallTransfer.aspx", false);
                //Response.Redirect("PreviewDialing.aspx", true);
            }
            else
            {
                if (ddlCallStatus.SelectedIndex == 0 || ddlCallStatus.SelectedValue == "AutoSave")
                {
                    DisplayMessage("Please Provide Call Disposition Status.");
                    return;
                }
                else if (savemycall())
                {
                    if (!string.IsNullOrEmpty(Save_Url.Text))
                    {
                        ExecuteURL();
                        Session["Command"] = "SaveClick";
                        Timer1.Enabled = true;
                    }
                    else
                    {
                        UpdateCRMState("Idle");
                        FunctionClassObj.ExecuteCommand("UPDATE Admin_Extention_Master SET SrNo = 0 WHERE Extention_No = '" + txtExtensionNo.Text + "'");
                        Session["Phone_No"] = Session["SrNo"] = Session["CallBackPhoneNo"] = Session["CallBackTime"] = Session["CallAgainType"] = Session["LogId"] =
Session["dialerincoming"] = null;
                        if (lblCallMode.Text == "previewdialing")
                            Response.Redirect("PreviewDialing.aspx", false);
                        //else if (FunctionClassObj.ExecuteScalarString("SELECT Dial_Mode FROM Campaign_Master WHERE Campaign_Id = " + lblCampaignId.Text).ToLower() == "preview")
                        //    Response.Redirect("PreviewDialing.aspx", false);
                        else if (Request.QueryString["Log_Id"] == null)
                            Response.Redirect("CallWaiting.aspx", false);
                        else
                            Response.Redirect("PreviewReport.aspx?recordPerPageQ=0", true);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            ShowError.Visible = true;
            ErrorMessage.Text = "Error Save " + ex.Message;
        }
    }
    public void SetAutoCallBack()
    {
        try
        {
            DataTable dtCallStatus = FunctionClassObj.GetData("SELECT AutoCallback_Days,AutoCallback_Hrs,AutoCallback_Mins FROM CallStatus WHERE (AutoCallback_Days > 0 OR AutoCallback_Hrs > 0 OR AutoCallback_Mins > 0) AND Pid = " + FunctionClassObj.StringToInt(lblprocessid.Text) + " AND Call_Status = '" + ddlCallStatus.SelectedValue + "'");
            if (dtCallStatus.Rows.Count > 0)
            {
                int iMin = (FunctionClassObj.StringToInt(dtCallStatus.Rows[0]["AutoCallback_Days"].ToString()) * 1440) + (FunctionClassObj.StringToInt(dtCallStatus.Rows[0]["AutoCallback_Hrs"].ToString()) * 60) + FunctionClassObj.StringToInt(dtCallStatus.Rows[0]["AutoCallback_Mins"].ToString());
                if (iMin > 0)
                {
                    txtCallBackDate.Text = DateTime.Now.AddMinutes(iMin).ToString("dd/MM/yyyy");
                    callbacktimeHr.SelectedValue = DateTime.Now.AddMinutes(iMin).ToString("HH");
                    callbacktimeMm.SelectedValue = DateTime.Now.AddMinutes(iMin).ToString("mm");
                }
            }
        }
        catch (Exception ex)
        {

        }
    }
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        dtProcessMaster = FunctionClassObj.GetData("SELECT * FROM Process_Master WHERE Pid = " + lblprocessid.Text + " AND Agent_Visible = 1 ORDER BY Order_No");
        if (SaveCheck(dtProcessMaster, PlaceHolder_Master) == false)
            return;
        SaveUpadteData(dtProcessMaster, PlaceHolder_Master, "Master");
        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Script", "window.open('TMS/NewTicket.aspx?CustomerId=" + Master_Id.Text + "','BranchDetails','height=400,width=500,resizable=yes')", true);
    }
    protected void LinkButton2_Click(object sender, EventArgs e)
    {
        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Script", "window.open('TMS/TMSSearchTickets.aspx?CustomerId=" + Master_Id.Text + "','BranchDetails','height=400,width=500,resizable=yes')", true);
    }
    protected void lnkAttachements_Click(object sender, EventArgs e)
    {
        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Script", "window.open('Attachements.aspx?ProcessId=" + lblprocessid.Text + "&MasterId=" + Master_Id.Text + "','Attachements','height=200,width=500,resizable=yes')", true);
    }
    protected void LinkButtonComplaints_Click(object sender, EventArgs e)
    {
        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Script", "window.open('ComplainMaster/ComplainRegister.aspx?Phone_No=" + lblPhoneNo.Text + "&Customer_Id=" + Master_Id.Text + "','ComplainRegister','height=300,width=800,resizable=yes')", true);
    }
    protected void ImgBtnEMail_Click(object sender, EventArgs e)
    {
        if (ViewState["dtProcessMaster"] != null)
            dtProcessMaster = (DataTable)ViewState["dtProcessMaster"];
        else
            dtProcessMaster = FunctionClassObj.GetData("SELECT * FROM Process_Master WHERE Pid = " + lblprocessid.Text + " AND Agent_Visible = 1 ORDER BY Order_No");
        string sEmailIds = string.Empty;
        foreach (DataRow dr in dtProcessMaster.Rows)
        {
            if (dr["Field_Type"].ToString().ToLower() == "email")
            {
                TextBox1 = (TextBox)Page.FindControl(dr["Field_Name"].ToString());
                if (TextBox1 != null)
                {
                    if (string.IsNullOrEmpty(sEmailIds))
                        sEmailIds = TextBox1.Text;
                    else
                        sEmailIds += "," + TextBox1.Text;
                }
            }
        }
        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Script12345", "window.open('EMail.aspx?ProcessId=" + lblprocessid.Text + "&EmailId=" + sEmailIds + "','SendEmail','height=500,width=700,resizable=yes')", true);
    }
    protected void LinkButton3_Click(object sender, EventArgs e)
    {
        string sLastDisposition = FunctionClassObj.ExecuteScalarString("SELECT TOP 1 CallStatus FROM Process_" + lblprocessid.Text + "_Log WHERE Master_Id = " + Master_Id.Text + " ORDER BY Log_Id DESC");
        Int32 iScriptId = FunctionClassObj.ExecuteScalar("SELECT ISNULL(Script_Id,0) FROM CallStatus WHERE Call_Status = '" + sLastDisposition + "'");
        if (FunctionClassObj.StringToInt(iScriptId.ToString()) == 0)
            iScriptId = FunctionClassObj.ExecuteScalar("SELECT Script_Id FROM Process WHERE Pid = " + lblprocessid.Text);
        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Script", "window.open('Script.aspx?ScriptId=" + iScriptId + "','Script123','height=400,width=500,resizable=yes')", true);
    }
    protected void Timer1_Tick(object sender, EventArgs e)
    {
        try
        {
            UpdateCRMState("Idle");
            Session["Phone_No"] = Session["SrNo"] = Session["CallBackPhoneNo"] = Session["CallBackTime"] = Session["CallAgainType"] = Session["LogId"] =
Session["dialerincoming"] = null;
            FunctionClassObj.ExecuteCommand("UPDATE Admin_Extention_Master SET SrNo = 0 WHERE Extention_No = '" + txtExtensionNo.Text + "'");

            if (Session["Command"] != null)
            {
                if (Session["Command"].ToString() == "SaveClick")
                {
                    if (Request.QueryString["Log_Id"] == null)
                        Response.Redirect("CallWaiting.aspx", false);
                    else
                        Response.Redirect("PreviewReport.aspx?recordPerPageQ=0", true);
                }
                else if (Session["Command"].ToString() == "SaveNextClick")
                {
                    string queryPhoneNo = "SELECT TOP 1 Master_Id,Phone_No,Call_Again_Time,Campaign_Id,Call_Again_PhoneNo,SrNo,Call_Again_Type FROM Process_" + lblprocessid.Text + "_Master t1"
                    + " JOIN Campaign_" + lblprocessid.Text + "_Mapping t2 ON t1.Master_Id = t2.Customer_Id JOIN File_Master t3 ON t2.File_Id = t3.File_Id WHERE isActive = 'True' AND Dialed = 'False' ";
                    if (dtProcess.Rows[0]["Callback_AgentMapping"].ToString() == "True")
                        queryPhoneNo += " AND Agent_Id = '" + lblagentName.Text + "'";
                    if (dtProcess.Rows[0]["Callback_FromAnyCampaign"].ToString() == "False")
                        queryPhoneNo += " AND Campaign_Id = " + lblCampaignId.Text;
                    dtProgressivedialing = FunctionClassObj.GetData(queryPhoneNo + " AND Call_Again_Time <= '" + DateTime.Now.ToString() + "' ORDER BY Call_Again_Time");
                    if (dtProgressivedialing.Rows.Count == 1 && (FunctionClassObj.ExecuteScalarString("SELECT Dial_Mode FROM Campaign_Master WHERE Campaign_Id = " + lblCampaignId.Text).ToLower() == "predictive"))
                    {
                        Session["CallBackPhoneNo"] = dtProgressivedialing.Rows[0]["Call_Again_PhoneNo"].ToString();
                        Session["CallBackTime"] = dtProgressivedialing.Rows[0]["Call_Again_Time"].ToString();
                        Session["CallAgainType"] = dtProgressivedialing.Rows[0]["Call_Again_Type"].ToString();
                        FunctionClassObj.ExecuteCommand("UPDATE Campaign_" + lblprocessid.Text + "_Mapping SET Dialed = 'True',Call_Again_Time = NULL,Call_Again_PhoneNo = NULL WHERE SrNo = " + dtProgressivedialing.Rows[0]["SrNo"].ToString());
                        Response.Redirect("CallTransfer.aspx?callmode=manualdialing&Caller_Id=" + FunctionClassObj.EncryptString(FunctionClassObj.StringToPhoneNo(dtProgressivedialing.Rows[0]["Call_Again_PhoneNo"].ToString())));
                    }
                    Response.Redirect("CallTransfer.aspx", true);
                }
            }
            Response.Redirect("CallWaiting.aspx", false);
        }
        catch (Exception ex)
        {
            //Response.Redirect("CallWaiting.aspx", false);
        }
    }
    protected void ImgBtnCallTransfer_Click(object sender, EventArgs e)
    {
        try
        {
            if (Call_Transfer.SelectedIndex > 0)
            {
                if (ddlCallStatus.SelectedIndex == 0 || ddlCallStatus.SelectedValue == "AutoSave")
                {
                    DisplayMessage("Please Provide Call Disposition Status.");
                    return;
                }
                else if (savemycall())
                {
                    UpdateCRMState("Idle");
                    FunctionClassObj.ExecuteCommand("UPDATE Admin_Extention_Master SET SrNo = 0,pbx_command = 'REDIRECT" + Call_Transfer.SelectedValue + "' WHERE Extention_No = '" + txtExtensionNo.Text + "'");
                    Session["Phone_No"] = Session["SrNo"] = Session["CallBackPhoneNo"] = Session["CallBackTime"] = Session["CallAgainType"] = Session["LogId"] =
Session["dialerincoming"] = null;
                    
                    if (lblCallMode.Text == "previewdialing")
                        Response.Redirect("PreviewDialing.aspx", false);
                    else if (Request.QueryString["Log_Id"] == null)
                        Response.Redirect("CallWaiting.aspx", false);
                    else
                        Response.Redirect("PreviewReport.aspx?recordPerPageQ=0", true);
                    //}
                }
            }
        }
        catch (Exception ex)
        {
            ShowError.Visible = true;
            ErrorMessage.Text = "Error Save " + ex.Message;
        }
    }
    protected void ImgBtnCallHangup_Click(object sender, EventArgs e)
    {
        FunctionClassObj.ExecuteCommand("UPDATE Admin_Extention_Master SET PBX_Command = 'HANGUP' WHERE Extention_No = '" + txtExtensionNo.Text + "'");
    }
    protected void DialManualNumber(string sPhoneNo, string sUniqueId, string sExtentionNo)
    {
        FunctionClassObj.ExecuteCommand("UPDATE Admin_Extention_Master SET Called_No = '" + sPhoneNo + "',Dial_Time = NULL,Unique_Id = '" + sUniqueId + "' WHERE Extention_No = '" + sExtentionNo + "'");
    }
    protected string FillSMSTemplateWithData(string smsTemplate)
    {
        bool check = false;
        string sFields = string.Empty;
        DataTable dtProcessDataMaster = FunctionClassObj.GetData("SELECT * FROM Process_" + lblprocessid.Text + "_Master WHERE Master_Id = '" + Master_Id.Text + "'");
        DataTable dtProcessLogMaster = FunctionClassObj.GetData("SELECT * FROM Process_" + lblprocessid.Text + "_Log WHERE Log_Id = '" + lblLogId.Text + "'");
        DataTable dtBranchMaster = FunctionClassObj.GetData("SELECT [Branch_Name],[Contact_Person],[Branch_Address],[Branch_PhoneNo],[Branch_EmailId] FROM Branch        _Master WHERE Branch_Id = '" + FunctionClassObj.StringToInt(SANBranch_Master.SelectedValue) + "'");
        if (dtBranchMaster.Rows.Count > 0)
        {
            smsTemplate = smsTemplate.Replace("<<Branch_Name>>", dtBranchMaster.Rows[0]["Branch_Name"].ToString());
            smsTemplate = smsTemplate.Replace("<<Branch_Contact_Person>>", dtBranchMaster.Rows[0]["Contact_Person"].ToString());
            smsTemplate = smsTemplate.Replace("<<Branch_Address>>", dtBranchMaster.Rows[0]["Branch_Address"].ToString());
            smsTemplate = smsTemplate.Replace("<<Branch_PhoneNo>>", dtBranchMaster.Rows[0]["Branch_PhoneNo"].ToString());
            smsTemplate = smsTemplate.Replace("<<Branch_EmailId>>", dtBranchMaster.Rows[0]["Branch_EmailId"].ToString());
        }        
        int m = 0;
        int startIndex = 0;
        int endIndex = 0;
        while (smsTemplate.Length > m)
        {
            startIndex = smsTemplate.IndexOf("<", m);
            if (startIndex > 0)
            {
                startIndex = startIndex + 2;
                endIndex = smsTemplate.IndexOf(">", startIndex);
                if (endIndex > 0)
                    sFields += " " + smsTemplate.Substring(startIndex, endIndex - startIndex);
            }
            if (startIndex == -1)
                break;
            m = endIndex + 2;
        }
        string[] checkField = sFields.Split(' ');
        check = false;
        for (int j = 0; checkField.Length > j; j++)
        {
            dtMain = FunctionClassObj.GetData("SELECT Field_Name,Control_Type FROM Process_Master WHERE Pid = " + lblprocessid.Text + " AND Field_Name = '" + checkField[j] + "'");
            if (dtMain.Rows.Count > 0)
            {
                check = true;
                smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", dtProcessDataMaster.Rows[0][dtMain.Rows[0]["Field_Name"].ToString()].ToString());
            }
            if (check == false)
            {
                dtMain = FunctionClassObj.GetData("SELECT Field_Name,Control_Type FROM Process_Log WHERE Pid =" + lblprocessid.Text + " AND Field_Name = '" + checkField[j] + "'");
                if (dtMain.Rows.Count > 0)
                    smsTemplate = smsTemplate.Replace("<<" + dtMain.Rows[0]["Field_Name"].ToString() + ">>", dtProcessLogMaster.Rows[0][dtMain.Rows[0]["Field_Name"].ToString()].ToString());
            }
        }
        #region Process Master
        for (int j = 0; j < dtProcessDataMaster.Columns.Count; j++)
            smsTemplate = smsTemplate.Replace("<<" + dtProcessDataMaster.Columns[j].ColumnName.ToString() + ">>", dtProcessDataMaster.Rows[0][dtProcessDataMaster.Columns[j].ColumnName.ToString()].ToString());
        #endregion
        #region Process Log
        for (int j = 0; j < dtProcessLogMaster.Columns.Count; j++)
            smsTemplate = smsTemplate.Replace("<<" + dtProcessLogMaster.Columns[j].ColumnName.ToString() + ">>", dtProcessLogMaster.Rows[0][dtProcessLogMaster.Columns[j].ColumnName.ToString()].ToString());
        #endregion

        smsTemplate = smsTemplate.Replace("<<Agent_Name>>", Session["Agent_Name"].ToString());

        return smsTemplate;
    }

}