using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.OracleClient;
//using NCBEAI.Adapters.Transport;
using System.Xml;
using System.Drawing;

public partial class Business_UpdateMerchant : System.Web.UI.Page
{
    protected string clLevel;
    protected string regCode;
    public static double Span_Fee_Limit = Convert.ToDouble(SystemParam.GetParamByID("551"));
    public static double Span_Fee_Limit_lower = Convert.ToDouble(SystemParam.GetParamByID("553"));
    public static double Span_Low_Usage_Cap_PerTerminal = Convert.ToDouble(SystemParam.GetParamByID("557"));

    //configurable through sys_param and re-set application required as its static
    public static double Span_Max_Pi_Cap = Convert.ToDouble(SystemParam.GetParamByID("500"));// Max CAP 80 SAR
    public static double Cost_Of_POS_Max_Cap = Convert.ToDouble(SystemParam.GetParamByID("601")); // Max 200 SAR 



    protected void Page_Load(object sender, EventArgs e)
    {
         
        if (!IsPostBack)
        {
            lblSpanFeeLimit.Text = Span_Fee_Limit.ToString();
            lblSpanFeeLimitLower.Text = Span_Fee_Limit_lower.ToString();
      
            loadVAT();// VAT_CR
            loadUpdateAction();
            loadClientLevel();
            loadLanguage();
            loadSrvTypes();//Said 20140726
            loadBusinessClass();
            loadCity();
            loadProductType();
            // POS Merchant Settlement Method changes 20210729
            loadsettlementMethod();
            loadpostingMethod();
            loadBusinessUnit();
            loadServices();
            loadTerminals();
            loadCurrancy();
            loadIncomeRange();
            loadRelationOfficer();  
            loadAddressCategory();
            loadTerminalStatus();
            loadChargeReason();
            loadComments();
            loadDynamicGroups();
            loadStaticGroups();
            loadFreeNewStatus();
            loadVendors();
            loadBranch(1);
            loadBranchAcc(1);
            LoadTTerminalBusinessType();
            LoadTerminalProvider();
            
            LoadDeliveryMethod();   // POS Merchant Settlement Method changes 20210729

            string clID = Request.QueryString["clID"];

            lblClientNo.Text = clID;
            loadMerchant(clID);
            clLevel = ddlClientLevel.SelectedValue.ToString();
            loadMerchantRegStatus(clID);
            loadMerchantAddresses(clID, Helper.gridSize(), 1);
            loadMerchantServices(clID, Helper.gridSize(), 1);
            loadMerchantTerminals(clID, Helper.gridSize(), 1);
            loadBUAcc(ddlBusinessUnit.SelectedValue);
            if (ddlClientLevel.SelectedValue.Equals("001"))
            {
                lblRetailerID.Visible = false;
                txtRetailerID.Visible = false;
                ddlSettlMethod.Enabled = false;
                ddlPostingMethod.Enabled = false;
                // POS Merchant Settlement Method changes 20210729
            }
            // POS Merchant Settlement Method changes 20210729
            if (ddlClientLevel.SelectedValue.Equals("003"))
            {
                ddlSettlMethod.Enabled = true;
            }
            // POS Merchant Settlement Method changes 20210729
            if (ddlClientLevel.SelectedValue.Equals("002"))
            {
                ddlSettlMethod.Enabled = false;
            }

            if (isBlackList("", txtAccNoGeneral.Text))
            {
                btnSave.Enabled = false;
                btnAccSer.Enabled = false;
                btnChangeAccount.Enabled = false;
                //btnCorrectInfo.Enabled = false;
                btnAddAddress.Enabled = false;
                btnAddServices.Enabled = false;
                btnAddTerminal.Enabled = false;
                btnAddTerminalBulk.Enabled = false;
                btnSubmit.Enabled = false;
                btnDuplicate.Enabled = false;
                lblError.Text = "This Merchant is Black Listed";
            }
            txtPercentB.Attributes.Add("OnBlur", "return total()");
            txtPercentM.Attributes.Add("OnBlur", "return total()");
        }
    }

    private void loadMerchantRegStatus(string ClID)
    {
        loadMerchRegStatus(ClID);

        if (txtRegCode.Text.ToString().Equals("000") || txtRegCode.Text.ToString().Equals("002") || txtRegCode.Text.ToString().Equals("004"))
        {
            txtRegStatus.BackColor = System.Drawing.Color.GreenYellow;
            txtRegStatus.ForeColor = System.Drawing.Color.Black;
        }
        if (txtRegCode.Text.ToString().Equals("001"))
        {
            txtRegStatus.BackColor = System.Drawing.Color.SkyBlue;
            txtRegStatus.ForeColor = System.Drawing.Color.Black;
        }
        if (txtRegCode.Text.ToString().Equals("003") || txtRegCode.Text.ToString().Equals("005"))
        {
            txtRegStatus.BackColor = System.Drawing.Color.Brown;
            txtRegStatus.ForeColor = System.Drawing.Color.White;
        }
        if (txtRegCode.Text.ToString().Equals("006") || txtRegCode.Text.ToString().Equals("007"))
        {
            txtRegStatus.BackColor = System.Drawing.Color.Tan;
            txtRegStatus.ForeColor = System.Drawing.Color.Black;
        }

    }
    private void loadMerchRegStatus(string ClntID)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "poslookup_getter.get_Merch_RegStatus";
        oracom.Parameters.Add("p_clientNo", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters["p_clientNo"].Value = ClntID;
        oracom.Parameters.Add("p_Merch_RegStatus", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_Merch_RegStatusDesc", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.ExecuteNonQuery();
        oracon.Close();

        txtRegCode.Text = oracom.Parameters["p_Merch_RegStatus"].Value.ToString();
        txtRegStatus.Text = oracom.Parameters["p_Merch_RegStatusDesc"].Value.ToString();

    }
    //irfan_mod VAT_CR
    private void loadVAT()
    {
        try
        {
            string DBConnection = Helper.dbConnection();

            OracleConnection oracon = new OracleConnection(DBConnection);
            oracon.Open();

            OracleCommand oracom = new OracleCommand();
            oracom.Connection = oracon;

            oracom.CommandType = CommandType.StoredProcedure;
            oracom.CommandText = "poslookup_getter.get_merch_vat";

            oracom.Parameters.Add("p_VAT", OracleType.Cursor).Direction = ParameterDirection.Output;

            OracleDataAdapter da = new OracleDataAdapter(oracom);
            DataSet ds = new DataSet();
            da.Fill(ds);

            ddlVat.DataSource = ds;
            ddlVat.DataBind();

            oracon.Close();
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex, "poslookup_getter.get_merch_vat", "", "loadVAT", "");
            //Response.Redirect("../ErrorPages/ErrorPage.aspx");
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (ddlBusinessClass.SelectedIndex != 0)
        {
            //ddlBusinessUnit.SelectedIndex = 0;
            if (txtRetailName.Text.Length == 0)
                lblError.Text = "Merchant Name cannot be empty";


            else if (true)
            {
                string error = "", ID = Request.QueryString["clID"];
                clLevel = ddlClientLevel.SelectedValue.ToString();
                bool saved = updateMerchant(ref error);
                if (saved)
                {
                    lblError.Text = "Merchant saved";
                    ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
                       "window.open('Comment.aspx?clID=" + ID + "&action=Update Merchant','MerchantComment','status=1,width=700,height=250')", true);
                }
                else
                {
                    if (Helper.OracleError(error))
                    {
                        lblError.Text = "Save Failed";
                        ExceptionUtility.LogException(9, "", "", "btnSave_Click", error);
                    }
                    else
                        lblError.Text = error;
                }
            }
            else
            {
                lblError.Text = "please complete all the mandatory fields in the screen.";
            }
        }
        else
        {
            lblError.Text = "Please choose a business class";
        }
    }

    private bool updateMerchant(ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "merchant_reg.update_merchant_info";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
   
        oracom.Parameters.Add("p_client_no", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_retailer_name", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_retailer_name_ar", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_registration_number", OracleType.VarChar).Direction = ParameterDirection.Input;
        //oracom.Parameters.Add("p_legal_form", OracleType.VarChar).Direction = ParameterDirection.Input;
        //oracom.Parameters.Add("p_client_language", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_business_class", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_city_code", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_street", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_posting_method", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_settlement_method", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_business_unit", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_manual_application_number", OracleType.Number).Direction = ParameterDirection.Input;
        //oracom.Parameters.Add("p_merchant_contact", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_registration_date", OracleType.VarChar).Direction = ParameterDirection.Input;
        //oracom.Parameters.Add("p_rental_percent", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_acct_number", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_fee_merchant_acc_no", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_index", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_fdr", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_relationship_officer", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_branch_cd", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.Parameters["p_client_no"].Value = Request.QueryString["clID"];
        oracom.Parameters["p_retailer_name"].Value = txtRetailName.Text;
        oracom.Parameters["p_retailer_name_ar"].Value = txtRetailNameAr.Text;
        oracom.Parameters["p_registration_number"].Value = txtRegNo.Text;
        //oracom.Parameters["p_legal_form"].Value = txtLegalForm.Text;
        //oracom.Parameters["p_client_language"].Value = ddlLang.SelectedValue;
        oracom.Parameters["p_business_class"].Value = ddlBusinessClass.SelectedValue;
        oracom.Parameters["p_city_code"].Value = ddlCity.SelectedValue;
        //oracom.Parameters["p_street"].Value = txtStreet.Text;        
        oracom.Parameters["p_posting_method"].Value = ddlPostingMethod.SelectedValue;

        // POS Merchant Settlement Method changes 20210729
        if (ddlClientLevel.SelectedValue.Equals("003"))
        {
            oracom.Parameters["p_settlement_method"].Value = ddlSettlMethod.SelectedValue;
        }
        else
        {
            oracom.Parameters["p_settlement_method"].Value = OracleString.Null;
        }

        oracom.Parameters["p_business_unit"].Value = "0";//ddlBusinessUnit.SelectedValue;

        //oracom.Parameters["p_manual_application_number"].Value = txtManualAppNo.Text;
        //oracom.Parameters["p_merchant_contact"].Value = txtMerchantContact.Text;
        oracom.Parameters["p_registration_date"].Value = dateRegDate.date;
        //oracom.Parameters["p_rental_percent"].Value = OracleNumber.Null;

        oracom.Parameters["p_acct_number"].Value = txtAccNoGeneral.Text.Replace(" ", "");

        oracom.Parameters["p_fee_merchant_acc_no"].Value = txtfeemerchantaccno.Text.Replace(" ", "");

        oracom.Parameters["p_index"].Value = txtIndexNumber.Text;
        //oracom.Parameters["p_fdr"].Value = txtFDR.Text;
        oracom.Parameters["p_relationship_officer"].Value = ddlRelationshipOfficer.SelectedValue;
        oracom.Parameters["p_branch_cd"].Value = ddlBranch.SelectedValue;

        // MM phase 2

        oracom.Parameters.Add("p_retailer_id", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters["p_retailer_id"].Value = txtRetailerID.Text.Trim() + txtRetailerID2.Text.Trim();

        if(txtRetailerID.Text.Length>=5 ) // Store FDR ID from Retailer ID  , "11"+Last 7 digit of retailer ID
            oracom.Parameters["p_fdr"].Value =  txtFDR.Text= "11" + txtRetailerID.Text.Trim().Substring(txtRetailerID.Text.Length-5) + txtRetailerID2.Text.Trim(); 
        else
          oracom.Parameters["p_fdr"].Value = txtFDR.Text; // JS filling
       
        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    private void loadMerchant(string ID)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "merchant_reg.get_merchant_by_id";

        oracom.Parameters.Add("p_client_number", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;

        oracom.Parameters["p_client_number"].Value = ID;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        oracon.Close();

        //set the data in the controls
        ddlClientLevel.SelectedValue = ds.Tables[0].Rows[0]["client_level"].ToString();
        if (ddlClientLevel.SelectedValue == "003")
        {
            btnRetailer.Visible = true;
           // POS Merchant Settlement Method changes 20210729
            ddlSettlMethod.Enabled = true;
        }
        ddlClientLevel.Enabled = false;
        if (ddlClientLevel.SelectedValue.Equals("001")) //Root
        {
            lblMerchantName.Text = "Merchant Name (English)";
            lblMerchantNameAr.Text = "Merchant Name (Arabic)";

            //CR Merchant
            //Disable RETAILERID if the merchant is root
            txtRetailerID.ReadOnly = true;
            btnRetailer.Visible = false;
           // ddlSettlMethod.Visible = false;

            rootrow.Visible = false;
        }
        else //Branch
        {
            lblMerchantName.Text = "Retailer Name (English)";
            lblMerchantNameAr.Text = "Retailer Name (Arabic)";

            //CR Merchant
            //Disable segment and relationship officer if the merchant is BRANCH
            //ddlIncomeRange.Enabled = false;
            ddlRelationshipOfficer.Enabled = true;
            //btnRetailer.Visible = true;
            //ddlSettlMethod.Visible = false;
            rootrow.Visible = true;
        }

        txtRetailName.Text = ds.Tables[0].Rows[0]["retailer_name"].ToString();
        txtRetailNameAr.Text = ds.Tables[0].Rows[0]["retailer_name_ar"].ToString();
        txtRegNo.Text = ds.Tables[0].Rows[0]["registration_number"].ToString();
        txtIndexNumber.Text = ds.Tables[0].Rows[0]["legal_form"].ToString();
        //ddlLang.SelectedValue = ds.Tables[0].Rows[0]["client_language"].ToString();
        ddlBusinessClass.SelectedValue = ds.Tables[0].Rows[0]["business_class"].ToString();

        ddlCity.SelectedValue = ds.Tables[0].Rows[0]["city_code"].ToString();
        if (ds.Tables[0].Rows[0]["city_code"].ToString().Length != 0)
            ddlAddressCity.SelectedValue = ds.Tables[0].Rows[0]["city_code"].ToString();
        // txtStreet.Text = ds.Tables[0].Rows[0]["street"].ToString();
        if (ds.Tables[0].Rows[0]["street"].ToString().Length != 0)
            txtEngAdd1.Text = ds.Tables[0].Rows[0]["street"].ToString();
        //ddlProductType.SelectedValue = ds.Tables[0].Rows[0]["product_type"].ToString();
        ddlPostingMethod.SelectedValue = ds.Tables[0].Rows[0]["posting_method"].ToString();

        // POS Merchant Settlement Method changes 20210729
        if (ddlClientLevel.SelectedValue.Equals("003"))
        {
            ddlSettlMethod.SelectedValue = ds.Tables[0].Rows[0]["settlement_method"].ToString();
            //ddlPostingMethod.SelectedValue = ds.Tables[0].Rows[0]["posting_method"].ToString();
        }  
        else
        {
            ddlSettlMethod.Items.Insert(0, "------ Select ------");
        }
            
        //ddlBusinessUnit.SelectedValue = ds.Tables[0].Rows[0]["business_unit"].ToString();
        ddlRelationshipOfficer.SelectedValue = ds.Tables[0].Rows[0]["relationship_officer"].ToString();
        txtRetailerID.Text = ds.Tables[0].Rows[0]["retailer_id"].ToString();
         if(txtRetailerID.Text.Length>=2)
         {
             txtRetailerID2.Text = txtRetailerID.Text.Substring(txtRetailerID.Text.Length - 2);
             txtRetailerID.Text = txtRetailerID.Text.Substring(0, txtRetailerID.Text.Length - 2);
         }
        //txtManualAppNo.Text = ds.Tables[0].Rows[0]["manual_application_number"].ToString();
        //CR Merchant
        //txtMerchantContact.Text = ds.Tables[0].Rows[0]["merchant_contact"].ToString();
        dateRegDate.date = ds.Tables[0].Rows[0]["registration_date"].ToString();

        txtRegDate.Text = ds.Tables[0].Rows[0]["registration_date"].ToString();
        //ddlIncomeRange.SelectedValue = ds.Tables[0].Rows[0]["income_range"].ToString();
        txtAccNoGeneral.Text = ds.Tables[0].Rows[0]["acct_number"].ToString();

        txtfeemerchantaccno.Text = ds.Tables[0].Rows[0]["fee_merchant_acct_number"].ToString();

        //txtBUAcc.Text = ds.Tables[0].Rows[0]["bu_acct"].ToString();

        lblRootName.Text = ds.Tables[0].Rows[0]["root_name"].ToString();
        lblRootNameAr.Text = ds.Tables[0].Rows[0]["root_name_ar"].ToString();

        //string dynamic = ds.Tables[0].Rows[0]["dynamic_group_code"].ToString();
        //string fixxed = ds.Tables[0].Rows[0]["fixed_group_code"].ToString();

        //if (dynamic.Length > 0)
        //{
        //    ddlDynamicG.SelectedValue = dynamic;
        //    rdDynamic.Checked = true;
        //}
        //else if (fixxed.Length > 0)
        //{
        //    ddlFixedG.SelectedValue = fixxed;
        //    rdFixed.Checked = true;
        //}

        ViewState["cat_com"] = ds.Tables[0].Rows[0]["cat_commision"].ToString();

        //**************************************************************************************************************************************************************************//
        //load the old values

        txtAccNoGeneralOld.Text = ds.Tables[0].Rows[0]["acct_number_old"].ToString();
        if (txtAccNoGeneralOld.Text == txtAccNoGeneral.Text)
            txtAccNoGeneralOld.Visible = false;
        else
            txtAccNoGeneralOld.Visible = true;

        txtRetailNameOld.Text = ds.Tables[0].Rows[0]["retailer_name_old"].ToString();
        if (txtRetailNameOld.Text == txtRetailName.Text)
            txtRetailNameOld.Visible = false;
        else
            txtRetailNameOld.Visible = true;

        txtRetailNameArOld.Text = ds.Tables[0].Rows[0]["retailer_name_ar_old"].ToString();
        if (txtRetailNameArOld.Text == txtRetailNameAr.Text)
            txtRetailNameArOld.Visible = false;
        else
            txtRetailNameArOld.Visible = true;

        //txtLegalFormOld.Text = ds.Tables[0].Rows[0]["legal_form_old"].ToString();
        //if (txtLegalFormOld.Text == txtLegalForm.Text)
        //    txtLegalFormOld.Visible = false;
        //else
        //    txtLegalFormOld.Visible = true;

        //txtLegalFormOld.Text = ds.Tables[0].Rows[0]["legal_form_old"].ToString();
        //if (txtLegalFormOld.Text == txtLegalForm.Text)
        //    txtLegalFormOld.Visible = false;
        //else
        //    txtLegalFormOld.Visible = true;

        //ddlLangOld.SelectedValue = ds.Tables[0].Rows[0]["client_language_old"].ToString();
        //if (ddlLangOld.SelectedIndex == ddlLang.SelectedIndex)
        //    ddlLangOld.Visible = false;
        //else
        //    ddlLangOld.Visible = true;

        ddlBusinessClassOld.SelectedValue = ds.Tables[0].Rows[0]["business_class_old"].ToString();
        if (ddlBusinessClassOld.SelectedIndex == ddlBusinessClass.SelectedIndex)
            ddlBusinessClassOld.Visible = false;
        else
            ddlBusinessClassOld.Visible = true;

        ddlCityOld.SelectedValue = ds.Tables[0].Rows[0]["city_code_old"].ToString();
        if (ddlCityOld.SelectedIndex == ddlCity.SelectedIndex)
            ddlCityOld.Visible = false;
        else
            ddlCityOld.Visible = true;

        //txtStreetOld.Text = ds.Tables[0].Rows[0]["street_old"].ToString();
        //if (txtStreetOld.Text == txtStreet.Text)
        //    txtStreetOld.Visible = false;
        //else
        //    txtStreetOld.Visible = true;

        //ddlProductTypeOld.SelectedValue = ds.Tables[0].Rows[0]["product_type_old"].ToString();
        //if (ddlProductTypeOld.SelectedIndex == ddlProductType.SelectedIndex)
        //    ddlProductTypeOld.Visible = false;
        //else
        //    ddlProductTypeOld.Visible = true;

        //ddlDynamicGOld.SelectedValue = ds.Tables[0].Rows[0]["dynamic_group_code_old"].ToString();
        //if (ddlDynamicGOld.SelectedIndex == ddlDynamicG.SelectedIndex)
        //    ddlDynamicGOld.Visible = false;
        //else
        //    ddlDynamicGOld.Visible = true;

        //ddlFixedGOld.SelectedValue = ds.Tables[0].Rows[0]["fixed_group_code_old"].ToString();
        //if (ddlFixedGOld.SelectedIndex == ddlFixedG.SelectedIndex)
        //    ddlFixedGOld.Visible = false;
        //else
        //    ddlFixedGOld.Visible = true;

        //ddlBusinessUnitOld.SelectedValue = ds.Tables[0].Rows[0]["business_unit_old"].ToString();
        //if (ddlBusinessUnitOld.SelectedIndex == ddlBusinessUnit.SelectedIndex)
        //    ddlBusinessUnitOld.Visible = false;
        //else
        //    ddlBusinessUnitOld.Visible = true;

        //ddlIncomeRangeOld.SelectedValue = ds.Tables[0].Rows[0]["income_range_old"].ToString();
        //if (ddlIncomeRangeOld.SelectedIndex == ddlIncomeRange.SelectedIndex)
        //    ddlIncomeRangeOld.Visible = false;
        //else
        //    ddlIncomeRangeOld.Visible = true;

        ddlRelationshipOfficerOld.SelectedValue = ds.Tables[0].Rows[0]["relationship_officer_old"].ToString();
        if (ddlRelationshipOfficerOld.SelectedIndex == ddlRelationshipOfficer.SelectedIndex)
            ddlRelationshipOfficerOld.Visible = false;
        else
            ddlRelationshipOfficerOld.Visible = true;
        // POS Merchant Settlement Method changes 20210729
        ddlSettlMethodOld.SelectedValue = ds.Tables[0].Rows[0]["settlement_method_old"].ToString();
        if (ddlSettlMethodOld.SelectedIndex == ddlSettlMethodOld.SelectedIndex)
            ddlSettlMethodOld.Visible = false;
        else
            ddlSettlMethodOld.Visible = true;
         

        //txtManualAppNoOld.Text = ds.Tables[0].Rows[0]["manual_application_number_old"].ToString();
        //if (txtManualAppNoOld.Text == txtManualAppNo.Text)
        //    txtManualAppNoOld.Visible = false;
        //else
        //    txtManualAppNoOld.Visible = true;

        //CR Merchant
        //txtMerchantContactOld.Text = ds.Tables[0].Rows[0]["merchant_contact_old"].ToString();
        //if (txtMerchantContactOld.Text == txtMerchantContact.Text)
        //    txtMerchantContactOld.Visible = false;
        //else
        //    txtMerchantContactOld.Visible = true;

        dateRegDateOld.Text = ds.Tables[0].Rows[0]["registration_date_old"].ToString();
        if (dateRegDateOld.Text == dateRegDate.FormatedDate)
            dateRegDateOld.Visible = false;
        else
            dateRegDateOld.Visible = true;

        txtRegNoOld.Text = ds.Tables[0].Rows[0]["registration_number_old"].ToString();
        if (txtRegNoOld.Text == txtRegNo.Text)
            txtRegNoOld.Visible = false;
        else
            txtRegNoOld.Visible = true;

        txtRetailerIDOld.Text = ds.Tables[0].Rows[0]["retailer_id_old"].ToString();
        if (txtRetailerIDOld.Text == txtRetailerID.Text + txtRetailerID2.Text)
            txtRetailerIDOld.Visible = false;
        else
            txtRetailerIDOld.Visible = true;

        string autoPayment = ds.Tables[0].Rows[0]["auto_payment"].ToString();
        txtFDR.Text = ds.Tables[0].Rows[0]["fdr_id"].ToString();

        ddlBranch.SelectedValue = ds.Tables[0].Rows[0]["branch_no"].ToString();
        //txtBranch.Text = ddlBranch.SelectedValue;
        loadBranch(2);
        //if (autoPayment=="1")
        //{
        //    chkAutoPayment.Checked = true;
        //}
        //else
        //{
        //    chkAutoPayment.Checked = false;
        //}
    }

    private void loadMerchantAddresses(string MerID, int pageSize, int pageNumber)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "MER_ADDRESS_EDITOR.Get_Merchant_Addresses";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_client_no", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_page_size", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_page_num", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_outputaddr", OracleType.Cursor).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_total_pages", OracleType.Number).Direction = ParameterDirection.Output;

        oracom.Parameters["p_client_no"].Value = MerID;

        oracom.Parameters["p_page_size"].Value = pageSize;
        oracom.Parameters["p_page_num"].Value = pageNumber;
        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        int nop = int.Parse(oracom.Parameters["p_total_pages"].Value.ToString());
        oracon.Close();

        gvAddresses.DataSource = ds;
        gvAddresses.DataBind();
    }

    private void loadMerchantServices(string MerID, int pageSize, int pageNumber)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "merchant_service.get_appl_service";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_client_no", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_page_size", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_page_num", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_total_pages", OracleType.Number).Direction = ParameterDirection.Output;

        oracom.Parameters["p_client_no"].Value = MerID;

        oracom.Parameters["p_page_size"].Value = pageSize;
        oracom.Parameters["p_page_num"].Value = pageNumber;
        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        int nop = int.Parse(oracom.Parameters["p_total_pages"].Value.ToString());
        oracon.Close();

        gvServices.DataSource = ds;
        gvServices.DataBind();
    }

    private void loadMerchantTerminals(string MerID, int pageSize, int pageNumber)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "MER_DEVICE_LINK_EDITOR.Get_Client_Device_Links";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_client_no", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_page_size", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_page_num", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_outputdevicelink", OracleType.Cursor).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_total_pages", OracleType.Number).Direction = ParameterDirection.Output;

        oracom.Parameters["p_client_no"].Value = MerID;

        oracom.Parameters["p_page_size"].Value = pageSize;
        oracom.Parameters["p_page_num"].Value = pageNumber;
        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);


        int nop = int.Parse(oracom.Parameters["p_total_pages"].Value.ToString());
        oracon.Close();

        gvTerminals.DataSource = ds;
        gvTerminals.DataBind();

        if (pageNumber == 1)
        {
            ddlPages.Items.Clear();
            for (int i = 1; i <= nop; i++)
            {
                ddlPages.Items.Add(i.ToString());
            }
        }
    }

    protected void ddlBusinessUnit_SelectedIndexChanged(object sender, EventArgs e)
    {
        clLevel = ddlClientLevel.SelectedValue.ToString();
        loadBUAcc(ddlBusinessUnit.SelectedValue);
    }
    protected void ddlVendor_SelectedIndexChanged(object sender, EventArgs e)
    {
        ddlTerminalType.Enabled = true;
        if (ddlVendor.SelectedIndex > 0)
            loadTerminalTypes();
    }
    private void loadBUAcc(string ID)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "poslookup_getter.Get_Business_Unit_Acct";

        oracom.Parameters.Add("p_bu_code", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;

        oracom.Parameters["p_bu_code"].Value = ID;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        oracon.Close();

        txtBUAcc.Text = ds.Tables[0].Rows[0][0].ToString();

    }

    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {

        loadMerchantTerminals(Request.QueryString["clID"], Helper.gridSize(), int.Parse(ddlPages.SelectedValue));
    }

    //CR Merchant
    //Correct Info button

    protected void btnCorrectInfo_Click(object sender, EventArgs e)
    {
        string error = "", ID = Request.QueryString["clID"];
        bool saved = correctInfo(ref error);
        if (saved)
        {
            lblError.Text = "Merchant saved";
            ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
               "window.open('Comment.aspx?clID=" + ID + "&action=Update Merchant (correct Information)','MerchantComment','status=1,width=700,height=250')", true);
        }
        else
        {
            if (Helper.OracleError(error))
            {
                lblError.Text = "Delete Failed";
                ExceptionUtility.LogException(9, "", "", "btnCorrectInfo_Click", error);
            }
            else
                lblError.Text = error;
        }
    }

    private bool correctInfo(ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "merchant_reg.correct_merchant_info";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_client_no", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_relationship_officer", OracleType.VarChar).Direction = ParameterDirection.Input;
        //oracom.Parameters.Add("p_income_range", OracleType.VarChar).Direction = ParameterDirection.Input;

        //oracom.Parameters.Add("p_DYNAMIC_GROUP_CODE", OracleType.VarChar).Direction = ParameterDirection.Input;
        //oracom.Parameters.Add("p_FIXED_GROUP_CODE", OracleType.VarChar).Direction = ParameterDirection.Input;


        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.Parameters["p_client_no"].Value = Request.QueryString["clID"];

        oracom.Parameters["p_relationship_officer"].Value = ddlRelationshipOfficer.SelectedValue;

        // POS Merchant Settlement Method changes 20210729
        if (ddlClientLevel.SelectedValue.Equals("003"))
        {
            oracom.Parameters["p_settlement_method"].Value = ddlSettlMethod.SelectedValue;
            oracom.Parameters["p_posting_method"].Value = ddlPostingMethod.SelectedValue;
        }
        else
        {
            oracom.Parameters["p_settlement_method"].Value = OracleString.Null;
            oracom.Parameters["p_posting_method"].Value = OracleString.Null;
        }
            
        //oracom.Parameters["p_income_range"].Value = ddlIncomeRange.SelectedValue;

        //if (rdDynamic.Checked)
        //{
        //    oracom.Parameters["p_DYNAMIC_GROUP_CODE"].Value = ddlDynamicG.SelectedValue;
        //    oracom.Parameters["p_FIXED_GROUP_CODE"].Value = OracleString.Null;//ddlFixedG.SelectedValue;
        //}
        //else
        //{
        //    oracom.Parameters["p_DYNAMIC_GROUP_CODE"].Value = OracleString.Null;
        //    oracom.Parameters["p_FIXED_GROUP_CODE"].Value = ddlFixedG.SelectedValue;
        //}

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    protected void btnRetailer_Click(object sender, EventArgs e)
    {
        btnRetailer.Visible = false;
        btnRetailerOk.Visible = true;
        btnRetailerCancel.Visible = true;
        ddlRetailerRegion.Visible = true;
        /*
        string error = "", ID = Request.QueryString["clID"];
        bool saved = correctRetailer(ref error);
        if (saved)
        {
            lblError.Text = "Merchant saved";
            ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
               "window.open('Comment.aspx?clID=" + ID + "&action=Update Merchant (correct Retailer)','MerchantComment','status=1,width=700,height=250')", true);
        }
        else
        {
            lblError.Text = error;
        }*/
    }

    private bool correctRetailer(string retailer, ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "merchant_reg.correct_retailer_id";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_client_no", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_retailer_id", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.Parameters["p_client_no"].Value = Request.QueryString["clID"];

        oracom.Parameters["p_retailer_id"].Value = retailer;

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    protected void btnAccSer_Click(object sender, EventArgs e)
    {
        string error = "", ID = Request.QueryString["clID"];
        bool saved = ApplyAccSer(ref error);
        if (saved)
        {
            lblError.Text = "Merchant saved";
            ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
               "window.open('Comment.aspx?clID=" + ID + "&action=Update Merchant (Apply to Service Accounts)','MerchantComment','status=1,width=700,height=250')", true);
        }
        else
        {
            if (Helper.OracleError(error))
            {
                lblError.Text = "Delete Failed";
                ExceptionUtility.LogException(9, "", "", "btnAccSer_Click", error);
            }
            else
                lblError.Text = error;
        }
    }

    private bool ApplyAccSer(ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "MERCHANT_SERVICE.Update_Srv_acct";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_client_no", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_mer_acct", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.Parameters["p_client_no"].Value = Request.QueryString["clID"];

        oracom.Parameters["p_mer_acct"].Value = txtAccNoGeneral.Text.Replace(" ", "");

        //oracom.Parameters["p_fee_mer_acct"].Value = txtfeemerchantaccno.Text.Replace(" ", "");

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }
    //********************************   loading the lookups lists   ********************************\\

    private void loadComments()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "MERCHANT_REG_NOTE_EDITOR.Display_Reg_Notes";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_client_no", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;

        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();
        oracom.Parameters["p_client_no"].Value = Request.QueryString["clID"];
        oracom.Parameters["p_lang"].Value = "EN";



        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        gvComments.DataSource = ds;
        gvComments.DataBind();

        oracon.Close();
    }

    private void loadDynamicGroups()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "poslookup_getter.Get_Dyn_Fee_Groups";

        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        //ddlDynamicG.DataSource = ds;
        //ddlDynamicG.DataBind();
        //ddlDynamicGOld.DataSource = ds;
        //ddlDynamicGOld.DataBind();

        oracon.Close();
    }

    private void loadStaticGroups()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "poslookup_getter.Get_Fixed_Fee_Groups";

        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        //ddlFixedG.DataSource = ds;
        //ddlFixedG.DataBind();
        //ddlFixedGOld.DataSource = ds;
        //ddlFixedGOld.DataBind();

        oracon.Close();
    }

    private void loadClientLevel()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "poslookup_getter.get_clientlevel";

        oracom.Parameters.Add("p_client_desc", OracleType.Cursor).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        ddlClientLevel.DataSource = ds;
        ddlClientLevel.DataBind();

        oracon.Close();
    }

    private void loadUpdateAction()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "poslookup_getter.get_update_action";

        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        ddlUpdateAction.DataSource = ds;
        ddlUpdateAction.DataBind();

        oracon.Close();
    }

    private void loadLanguage()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "poslookup_getter.get_language";

        oracom.Parameters.Add("p_lang", OracleType.Cursor).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        //ddlLang.DataSource = ds;
        //ddlLang.DataBind();

        //ddlLangOld.DataSource = ds;
        //ddlLangOld.DataBind();

        //Said 20141013
        //DropDownList1.DataSource = ds;
        //DropDownList1.DataBind();

        //Said 20141013
        //DropDownList1Old.DataSource = ds;
        //DropDownList1Old.DataBind();

        oracon.Close();
    }

    private void loadSrvTypes() //Said 20140726
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "poslookup_getter.get_term_srv_types";

        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        ddlSrvType.DataSource = ds;
        ddlSrvType.DataBind();

        ddlSrvTypeOld.DataSource = ds;
        ddlSrvTypeOld.DataBind();

        ddlServiceType.DataSource = ds;
        ddlServiceType.DataBind();

        oracon.Close();
    }
    private void loadTerminalTypes()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "poslookup_getter.get_terminal_types";

        oracom.Parameters.Add("p_vendor_code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;

        oracom.Parameters["p_vendor_code"].Value = ddlVendor.SelectedValue;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        ddlTerminalType.DataSource = ds;
        ddlTerminalType.DataBind();

        oracon.Close();
    }
    private void loadFreeNewStatus()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "poslookup_getter.get_free_new_status";

        oracom.Parameters.Add("c_terminal_status", OracleType.Cursor).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        ddlStatusBulk.DataSource = ds;
        ddlStatusBulk.DataBind();


        oracon.Close();
    }
    private void loadBusinessClass()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "poslookup_getter.get_Businessclass";

        oracom.Parameters.Add("p_Bclass", OracleType.Cursor).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        ddlBusinessClass.DataSource = ds;
        ddlBusinessClass.DataBind();

        ddlBusinessClassOld.DataSource = ds;
        ddlBusinessClassOld.DataBind();

        ddlBusinessClass.Items.Insert(0, "------ Select ------");
        ddlBusinessClassOld.Items.Insert(0, "------ Select ------");

        oracon.Close();
    }
    private void loadBranch(int type)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "bank_lkp_editor.get_branches";

        oracom.Parameters.Add("p_branch_cd", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;

        if (type == 1)
            oracom.Parameters["p_branch_cd"].Value = OracleString.Null;
        else
            oracom.Parameters["p_branch_cd"].Value = ddlBranch.SelectedValue;

        oracom.Parameters["p_lang"].Value = "EN";

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        if (type == 2)
            txtBranch.Text = ds.Tables[0].Rows[0]["a_nm"].ToString();
        else
        {
            ddlBranch.DataSource = ds;
            ddlBranch.DataBind();
        }

        oracon.Close();
    }
    private void loadBranchAcc(int type)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "bank_lkp_editor.get_branches";

        oracom.Parameters.Add("p_branch_cd", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;

        if (type == 1)
            oracom.Parameters["p_branch_cd"].Value = OracleString.Null;
        else
            oracom.Parameters["p_branch_cd"].Value = ddlBranchAcc.SelectedValue;

        oracom.Parameters["p_lang"].Value = "EN";

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        if (type == 2)
        {
            txtbranchAccName.Text = ds.Tables[0].Rows[0]["a_nm"].ToString();
            txtBrAccNo.Text = ds.Tables[0].Rows[0]["ACCT_NUMBER"].ToString();
        }
        else
        {
            ddlBranchAcc.DataSource = ds;
            ddlBranchAcc.DataBind();
        }

        oracon.Close();
    }
    private void loadCity()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "poslookup_getter.get_city";

        oracom.Parameters.Add("p_city_names", OracleType.Cursor).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        ddlCity.DataSource = ds;
        ddlCity.DataBind();

        ddlCityOld.DataSource = ds;
        ddlCityOld.DataBind();

        ddlAddressCity.DataSource = ds;
        ddlAddressCity.DataBind();

        ddlAddressCityOld.DataSource = ds;
        ddlAddressCityOld.DataBind();

        oracon.Close();
    }

    private void loadRegion()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "poslookup_getter.get_region";

        oracom.Parameters.Add("p_region_names", OracleType.Cursor).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        //ddlRegion1.DataSource = ds;
        //ddlRegion1.DataBind();


        oracon.Close();
    }

    private void loadProductType()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "poslookup_getter.get_Product_type";

        oracom.Parameters.Add("p_ptype", OracleType.Cursor).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        //ddlProductType.DataSource = ds;
        //ddlProductType.DataBind();
        //ddlProductTypeOld.DataSource = ds;
        //ddlProductTypeOld.DataBind();

        oracon.Close();
    }
    private void loadVendors()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "poslookup_getter.get_vendors_list";

        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        ddlVendor.DataSource = ds;
        ddlVendor.DataBind();
        ddlVendor.Items.Insert(0, "------ Vendors ------");

        oracon.Close();
    }

    private void loadsettlementMethod()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "poslookup_getter.get_Settl_method";

        oracom.Parameters.Add("p_smethod", OracleType.Cursor).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        ddlSettlMethod.DataSource = ds;
        ddlSettlMethod.DataBind();

        ddlSettlMethodOld.DataSource = ds;
        ddlSettlMethodOld.DataBind();

        oracon.Close();

        // ddlSettlMethod.Enabled = false;
    }

    private void loadpostingMethod()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "poslookup_getter.get_posting_method";

        oracom.Parameters.Add("p_pmethod", OracleType.Cursor).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        ddlPostingMethod.DataSource = ds;
        ddlPostingMethod.DataBind();

        oracon.Close();

        ddlPostingMethod.SelectedValue = "001";
        ddlPostingMethod.Enabled = false;
    }

    // POS Merchant Settlement Method changes 20210729
    private void LoadDeliveryMethod()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "poslookup_getter.get_Merch_Delivery_Method";

        oracom.Parameters.Add("p_Merch_DLMethod", OracleType.Cursor).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        ddlDeliveryMethod.DataSource = ds;
        ddlDeliveryMethod.DataBind();

        ddlDeliveryMethodOld.DataSource = ds;
        ddlDeliveryMethodOld.DataBind();

        oracon.Close();

         // ddlDeliveryMethod.Enabled = false;
    }
    private void loadBusinessUnit()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "poslookup_getter.Get_Business_Units";

        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        ddlBusinessUnit.DataSource = ds;
        ddlBusinessUnit.DataBind();
        ddlBusinessUnitOld.DataSource = ds;
        ddlBusinessUnitOld.DataBind();

        oracon.Close();
    }

    private void loadServices()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "poslookup_getter.Get_MerServices";

        oracom.Parameters.Add("p_ServiceName", OracleType.Cursor).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        ddlServices.DataSource = ds;
        ddlServices.DataBind();

        oracon.Close();

        string dgn = ConfigurationSettings.AppSettings["DGN"];
        if (!dgn.Equals("0"))
            ddlServices.Items.Remove(ddlServices.Items.FindByValue("007"));
    }

    private void loadTerminals()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "DEVICE_REPOSITORY_EDITOR.Get_Available_Device_List";

        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        ddlTerminals.DataSource = ds;
        ddlTerminals.DataBind();
 
        ddlTerminals.Items.Insert(0, "------ Select ------");

        oracon.Close();

        lblLowUsageCapLimit.Text = Span_Low_Usage_Cap_PerTerminal.ToString();


        lblCostOfPosCap.Text = Cost_Of_POS_Max_Cap.ToString();
        RangeValidatorCostOfPOS.MaximumValue = Cost_Of_POS_Max_Cap.ToString();
    }

    private void loadCurrancy()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "poslookup_getter.get_Merch_Currency";

        oracom.Parameters.Add("c_merchant_currency", OracleType.Cursor).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        ddlCurrancy.DataSource = ds;
        ddlCurrancy.DataBind();
        ddlCurrancyOld.DataSource = ds;
        ddlCurrancyOld.DataBind();

        oracon.Close();
    }

    private void loadIncomeRange()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "poslookup_getter.get_Income_range";

        oracom.Parameters.Add("c_Income_range", OracleType.Cursor).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        //ddlIncomeRange.DataSource = ds;
        //ddlIncomeRange.DataBind();
        //ddlIncomeRangeOld.DataSource = ds;
        //ddlIncomeRangeOld.DataBind();

        oracon.Close();
    }

    private void loadRelationOfficer()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "poslookup_getter.get_relationship_officer";

        oracom.Parameters.Add("c_relationship_officer", OracleType.Cursor).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        ddlRelationshipOfficer.DataSource = ds;
        ddlRelationshipOfficer.DataBind();
        ddlRelationshipOfficerOld.DataSource = ds;
        ddlRelationshipOfficerOld.DataBind();

        oracon.Close();
    }

    private void loadAddressCategory()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "poslookup_getter.get_address_category";

        oracom.Parameters.Add("c_address_category", OracleType.Cursor).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        ddlAddressCat.DataSource = ds;
        ddlAddressCat.DataBind();

        ddlAddressCatOld.DataSource = ds;
        ddlAddressCatOld.DataBind();

        oracon.Close();
    }

    private void loadTerminalStatus()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "poslookup_getter.get_terminal_status";

        oracom.Parameters.Add("c_terminal_status", OracleType.Cursor).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        ddlStatus.DataSource = ds;
        ddlStatus.DataBind();

        oracon.Close();
    }

    private void loadChargeReason()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "poslookup_getter.Get_Charge_Reasons";

        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        ddlReason.DataSource = ds;
        ddlReason.DataBind();

        oracon.Close();
    }

 
    //****************************************    Addresses   ****************************************\\

    protected void btnAddAddress_Click(object sender, EventArgs e)
    {
        pnlAddress.Visible = true;
        ViewState["mode"] = "a";

        txtContactnameOld.Visible = false;
        txtPOBoxOld.Visible = false;
        txtEngAdd1Old.Visible = false;
        txtEngAdd2Old.Visible = false;
        txtEngAdd3Old.Visible = false;
        txtArabAdd1Old.Visible = false;
        txtArabAdd2Old.Visible = false;
        txtArabAdd3Old.Visible = false;
        txtPostCodeOld.Visible = false;
        txtTelWorkOld.Visible = false;
        txtTelOtherOld.Visible = false;
        txtFaxOld.Visible = false;
        txtMobileOld.Visible = false;
        txtEmailOld.Visible = false;
        ddlAddressCityOld.Visible = false;
        ddlAddressCatOld.Visible = false;
        txtEmail2.Text = "";
        txtEmail3.Text = "";
        txtMobile2.Text = "";
        txtMobile3.Text = "";
    }

    protected void btnCancelAddress_Click(object sender, EventArgs e)
    {
        pnlAddress.Visible = false;
        ViewState["mode"] = null;
    }

    protected void btnSaveAddress_Click(object sender, EventArgs e)
    {
        try
        {
            string mode = ViewState["mode"].ToString();
            string error = "";
            if (mode.Equals("a"))
            {
                string clID = Request.QueryString["clID"];
                bool saved = addAddress(clID, ref error);
                if (saved)
                {
                    lblError.Text = "Address data Saved";
                    ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
                   "window.open('Comment.aspx?clID=" + clID + "&action=Add Address','MerchantComment','status=1,width=700,height=250')", true);
                }
                else
                {
                    if (Helper.OracleError(error))
                    {
                        lblError.Text = "Save Failed";
                        ExceptionUtility.LogException(9, "", "", "btnSaveAddress_Click", error);
                    }
                    else
                        lblError.Text = error;
                }
            }
            else if (mode.Equals("u"))
            {
                string clID = Request.QueryString["clID"];
                string Uid = ViewState["rowid"].ToString();
                bool saved = updateAddress(Uid, ref error);
 
                
                if (saved)
                {
                    lblError.Text = "Address data Saved";
                    ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
                   "window.open('Comment.aspx?clID=" + clID + "&action=Update Address','MerchantComment','status=1,width=700,height=250')", true);
                }
                else
                {
                    if (Helper.OracleError(error))
                    {
                        lblError.Text = "Save Failed";
                        ExceptionUtility.LogException(9, "", "", "btnSaveAddress_Click", error);
                    }
                    else
                        lblError.Text = error;
                }
            }
            loadMerchantAddresses(Request.QueryString["clID"], Helper.gridSize(), 1);
            ViewState["mode"] = null;
            ViewState["rowid"] = null;
            pnlAddress.Visible = false;
        }
        catch (Exception ex)
        {
        }
    }

    private bool addAddress(string clientNo, ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "MER_ADDRESS_EDITOR.Add_Merchant_Address";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_client_no", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_record_type", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_effective_date", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_address_category", OracleType.VarChar).Direction = ParameterDirection.Input;
        // POS Merchant Settlement Method changes 20210729
        oracom.Parameters.Add("p_delivery_Method", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_contact_name", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_po_box", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_english_address1", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_english_address2", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_english_address3", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_arabic_address1", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_arabic_address2", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_arabic_address3", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_post_code", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_city", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_country", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_tel_work", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_tel_other", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_fax", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_mobile", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_mobile_2", OracleType.VarChar).Direction = ParameterDirection.Input;//Amjath 20140824
        oracom.Parameters.Add("p_mobile_3", OracleType.VarChar).Direction = ParameterDirection.Input;//Amjath 20140824
        oracom.Parameters.Add("p_email_address", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_email_2", OracleType.VarChar).Direction = ParameterDirection.Input;//Amjath 20140824
        oracom.Parameters.Add("p_email_3", OracleType.VarChar).Direction = ParameterDirection.Input;//Amjath 20140824
        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.Parameters["p_client_no"].Value = clientNo;
        oracom.Parameters["p_record_type"].Value = "111";
        oracom.Parameters["p_effective_date"].Value = "090909";
        oracom.Parameters["p_address_category"].Value = ddlAddressCat.SelectedValue;

        // POS Merchant Settlement Method changes 20210729
        oracom.Parameters["p_delivery_Method"].Value = ddlDeliveryMethod.SelectedValue;

        oracom.Parameters["p_contact_name"].Value = txtContactname.Text;
        oracom.Parameters["p_po_box"].Value = txtPOBox.Text;
        oracom.Parameters["p_english_address1"].Value = txtEngAdd1.Text;
        oracom.Parameters["p_english_address2"].Value = txtEngAdd2.Text;
        oracom.Parameters["p_english_address3"].Value = txtEngAdd3.Text;
        oracom.Parameters["p_arabic_address1"].Value = txtArabAdd1.Text;
        oracom.Parameters["p_arabic_address2"].Value = txtArabAdd2.Text;
        oracom.Parameters["p_arabic_address3"].Value = txtArabAdd3.Text;
        oracom.Parameters["p_post_code"].Value = txtPostCode.Text;
        oracom.Parameters["p_city"].Value = ddlAddressCity.SelectedValue;
        oracom.Parameters["p_country"].Value = "682";
        oracom.Parameters["p_tel_work"].Value = txtTelWork.Text;
        oracom.Parameters["p_tel_other"].Value = txtTelOther.Text;
        oracom.Parameters["p_fax"].Value = txtFax.Text;
        oracom.Parameters["p_mobile"].Value = txtMobile.Text;
        oracom.Parameters["p_mobile_2"].Value = txtMobile2.Text;//Amjath 20140824
        oracom.Parameters["p_mobile_3"].Value = txtMobile3.Text;//Amjath 20140824
        oracom.Parameters["p_email_address"].Value = txtEmail.Text;
        oracom.Parameters["p_email_2"].Value = txtEmail2.Text;//Amjath 20140824
        oracom.Parameters["p_email_3"].Value = txtEmail3.Text;//Amjath 20140824
        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    private bool updateAddress(string clientNo, ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "MER_ADDRESS_EDITOR.Update_Merchant_Address";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_ma_code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_record_type", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_effective_date", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_address_category", OracleType.VarChar).Direction = ParameterDirection.Input;
        // POS Merchant Settlement Method changes 20210729
        oracom.Parameters.Add("p_delivery_Method", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_contact_name", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_po_box", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_english_address1", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_english_address2", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_english_address3", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_arabic_address1", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_arabic_address2", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_arabic_address3", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_post_code", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_city", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_country", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_tel_work", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_tel_other", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_fax", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_mobile", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_mobile_2", OracleType.VarChar).Direction = ParameterDirection.Input;//Amjath 20140824
        oracom.Parameters.Add("p_mobile_3", OracleType.VarChar).Direction = ParameterDirection.Input;//Amjath 20140824
        oracom.Parameters.Add("p_email_address", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_email_2", OracleType.VarChar).Direction = ParameterDirection.Input;//Amjath 20140824
        oracom.Parameters.Add("p_email_3", OracleType.VarChar).Direction = ParameterDirection.Input;//Amjath 20140824
        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.Parameters["p_ma_code"].Value = clientNo;
        oracom.Parameters["p_record_type"].Value = "111";
        oracom.Parameters["p_effective_date"].Value = "090909";
        oracom.Parameters["p_address_category"].Value = ddlAddressCat.SelectedValue;

        // POS Merchant Settlement Method changes 20210729
        oracom.Parameters["p_delivery_Method"].Value = ddlDeliveryMethod.SelectedValue;

        oracom.Parameters["p_contact_name"].Value = txtContactname.Text;
        oracom.Parameters["p_po_box"].Value = txtPOBox.Text;
        oracom.Parameters["p_english_address1"].Value = txtEngAdd1.Text;
        oracom.Parameters["p_english_address2"].Value = txtEngAdd2.Text;
        oracom.Parameters["p_english_address3"].Value = txtEngAdd3.Text;
        oracom.Parameters["p_arabic_address1"].Value = txtArabAdd1.Text;
        oracom.Parameters["p_arabic_address2"].Value = txtArabAdd2.Text;
        oracom.Parameters["p_arabic_address3"].Value = txtArabAdd3.Text;
        oracom.Parameters["p_post_code"].Value = txtPostCode.Text;
        oracom.Parameters["p_city"].Value = ddlAddressCity.SelectedValue;
        oracom.Parameters["p_country"].Value = "682";
        oracom.Parameters["p_tel_work"].Value = txtTelWork.Text;
        oracom.Parameters["p_tel_other"].Value = txtTelOther.Text;
        oracom.Parameters["p_fax"].Value = txtFax.Text;
        oracom.Parameters["p_mobile"].Value = txtMobile.Text;
        oracom.Parameters["p_mobile_2"].Value = txtMobile2.Text;//Amjath 20140824
        oracom.Parameters["p_mobile_3"].Value = txtMobile3.Text;//Amjath 20140824
        oracom.Parameters["p_email_address"].Value = txtEmail.Text;
        oracom.Parameters["p_email_2"].Value = txtEmail2.Text;//Amjath 20140824
        oracom.Parameters["p_email_3"].Value = txtEmail3.Text;//Amjath 20140824

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    private void loadAddressByID(string addressID)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "MER_ADDRESS_EDITOR.Get_Merchant_Address_by_id";

        oracom.Parameters.Add("p_ma_code", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;

        oracom.Parameters["p_ma_code"].Value = addressID;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        oracon.Close();

        //set the data in the controls
        txtContactname.Text = ds.Tables[0].Rows[0]["contact_name"].ToString();
        txtPOBox.Text = ds.Tables[0].Rows[0]["po_box"].ToString();
        txtEngAdd1.Text = ds.Tables[0].Rows[0]["english_address1"].ToString();
        txtEngAdd2.Text = ds.Tables[0].Rows[0]["english_address2"].ToString();
        txtEngAdd3.Text = ds.Tables[0].Rows[0]["english_address3"].ToString();
        txtArabAdd1.Text = ds.Tables[0].Rows[0]["arabic_address1"].ToString();
        txtArabAdd2.Text = ds.Tables[0].Rows[0]["arabic_address2"].ToString();
        txtArabAdd3.Text = ds.Tables[0].Rows[0]["arabic_address3"].ToString();
        txtPostCode.Text = ds.Tables[0].Rows[0]["post_code"].ToString();
        ddlAddressCity.SelectedValue = ds.Tables[0].Rows[0]["city"].ToString();
        txtTelWork.Text = ds.Tables[0].Rows[0]["tel_work"].ToString();
        txtTelOther.Text = ds.Tables[0].Rows[0]["tel_other"].ToString();
        txtFax.Text = ds.Tables[0].Rows[0]["fax"].ToString();
        txtMobile.Text = ds.Tables[0].Rows[0]["mobile"].ToString();
        txtMobile2.Text = ds.Tables[0].Rows[0]["mobile_2"].ToString();
        txtMobile3.Text = ds.Tables[0].Rows[0]["mobile_3"].ToString();
        txtEmail.Text = ds.Tables[0].Rows[0]["email_address"].ToString();
        txtEmail2.Text = ds.Tables[0].Rows[0]["email_2"].ToString();
        txtEmail3.Text = ds.Tables[0].Rows[0]["email_3"].ToString();
        ddlAddressCat.SelectedValue = ds.Tables[0].Rows[0]["address_category"].ToString();
        // POS Merchant Settlement Method changes 20210729
        ddlDeliveryMethod.SelectedValue = ds.Tables[0].Rows[0]["Delivery_Method"].ToString();
        pnlAddress.Visible = true;

        //load the old values
        txtContactnameOld.Text = ds.Tables[0].Rows[0]["contact_name_old"].ToString();
        if (txtContactnameOld.Text == txtContactname.Text)
            txtContactnameOld.Visible = false;
        else
            txtContactnameOld.Visible = true;

        txtPOBoxOld.Text = ds.Tables[0].Rows[0]["po_box_old"].ToString();
        if (txtPOBoxOld.Text == txtPOBox.Text)
            txtPOBoxOld.Visible = false;
        else
            txtPOBoxOld.Visible = true;

        txtEngAdd1Old.Text = ds.Tables[0].Rows[0]["english_address1_old"].ToString();
        if (txtEngAdd1Old.Text == txtEngAdd1.Text)
            txtEngAdd1Old.Visible = false;
        else
            txtEngAdd1Old.Visible = true;

        txtEngAdd2Old.Text = ds.Tables[0].Rows[0]["english_address2_old"].ToString();
        if (txtEngAdd2Old.Text == txtEngAdd2.Text)
            txtEngAdd2Old.Visible = false;
        else
            txtEngAdd2Old.Visible = true;

        txtEngAdd3Old.Text = ds.Tables[0].Rows[0]["english_address3_old"].ToString();
        if (txtEngAdd3Old.Text == txtEngAdd3.Text)
            txtEngAdd3Old.Visible = false;
        else
            txtEngAdd3Old.Visible = true;

        txtArabAdd1Old.Text = ds.Tables[0].Rows[0]["arabic_address1_old"].ToString();
        if (txtArabAdd1Old.Text == txtArabAdd1.Text)
            txtArabAdd1Old.Visible = false;
        else
            txtArabAdd1Old.Visible = true;

        txtArabAdd2Old.Text = ds.Tables[0].Rows[0]["arabic_address2_old"].ToString();
        if (txtArabAdd2Old.Text == txtArabAdd2.Text)
            txtArabAdd2Old.Visible = false;
        else
            txtArabAdd2Old.Visible = true;

        txtArabAdd3Old.Text = ds.Tables[0].Rows[0]["arabic_address3_old"].ToString();
        if (txtArabAdd3Old.Text == txtArabAdd3.Text)
            txtArabAdd3Old.Visible = false;
        else
            txtArabAdd3Old.Visible = true;



        txtPostCodeOld.Text = ds.Tables[0].Rows[0]["post_code_old"].ToString();
        if (txtPostCodeOld.Text == txtPostCode.Text)
            txtPostCodeOld.Visible = false;
        else
            txtPostCodeOld.Visible = true;

        txtTelWorkOld.Text = ds.Tables[0].Rows[0]["tel_work_old"].ToString();
        if (txtTelWorkOld.Text == txtTelWork.Text)
            txtTelWorkOld.Visible = false;
        else
            txtTelWorkOld.Visible = true;

        txtTelOtherOld.Text = ds.Tables[0].Rows[0]["tel_other_old"].ToString();
        if (txtTelOtherOld.Text == txtTelOther.Text)
            txtTelOtherOld.Visible = false;
        else
            txtTelOtherOld.Visible = true;

        txtFaxOld.Text = ds.Tables[0].Rows[0]["fax"].ToString();
        if (txtFaxOld.Text == txtFax.Text)
            txtFaxOld.Visible = false;
        else
            txtFaxOld.Visible = true;

        txtMobileOld.Text = ds.Tables[0].Rows[0]["mobile_old"].ToString();
        if (txtMobileOld.Text == txtMobile.Text)
            txtMobileOld.Visible = false;
        else
            txtMobileOld.Visible = true;

        txtEmailOld.Text = ds.Tables[0].Rows[0]["email_address_old"].ToString();
        if (txtEmailOld.Text == txtEmail.Text)
            txtEmailOld.Visible = false;
        else
            txtEmailOld.Visible = true;

        ddlAddressCityOld.SelectedValue = ds.Tables[0].Rows[0]["city_old"].ToString();
        if (ddlAddressCityOld.SelectedIndex == ddlAddressCity.SelectedIndex)
            ddlAddressCityOld.Visible = false;
        else
            ddlAddressCityOld.Visible = true;

        ddlAddressCatOld.SelectedValue = ds.Tables[0].Rows[0]["address_category_old"].ToString();
        if (ddlAddressCatOld.SelectedIndex == ddlAddressCat.SelectedIndex)
            ddlAddressCatOld.Visible = false;
        else
            ddlAddressCatOld.Visible = true;

    }

    private bool deleteAddress(string addressID, ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "MER_ADDRESS_EDITOR.Delete_Merchant_Address";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_client_no", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_ma_code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_ma_code"].Value = addressID;
        oracom.Parameters["p_client_no"].Value = Request.QueryString["clID"];

        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    protected void gvAddresses_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("u"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = gvAddresses.DataKeys[index].Value.ToString();
            loadAddressByID(rowID);

           
            ViewState["mode"] = "u";
            ViewState["rowid"] = rowID;

        }
        if (e.CommandName.Equals("h"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = gvAddresses.DataKeys[index].Value.ToString();
            ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
                    "window.open('../Reports/Default.aspx?rpt=106&p1=" + rowID + "','Report')", true);
        }
        else if (e.CommandName.Equals("d"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = gvAddresses.DataKeys[index].Value.ToString();
            string error = "";
            bool saved = deleteAddress(rowID, ref error);
            if (saved)
            {
                lblError.Text = "Address deleted";
            }
            else
            {
                if (Helper.OracleError(error))
                {
                    lblError.Text = "Delete Failed";
                    ExceptionUtility.LogException(9, "", "", "GridView1_RowCommand.Delete", error);
                }
                else
                    lblError.Text = error;
            }
            loadMerchantAddresses(Request.QueryString["clID"], Helper.gridSize(), 1);
        }
        else if (e.CommandName.Equals("ca"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = gvAddresses.DataKeys[index].Value.ToString();

            DataSet ds = Helper.getReportEvent(10); //Change Address
            string action = ds.Tables[0].Rows[0]["event_desc_en"].ToString();
            string actionName = ds.Tables[0].Rows[0]["event_name"].ToString();
            string addressChange = loadAddressHistory(rowID);
            action = action.Replace("{0}", addressChange);
            string windows = "";
            if (addressChange.Length > 0)
            {
                if (ds.Tables[0].Rows[0]["base24"].ToString() == "1")
                {
                    windows += ";window.open('../Reports/Default.aspx?rpt=601&p1=" + lblClientNo.Text + "','Report1')";
                }
                if (ds.Tables[0].Rows[0]["visa"].ToString() == "1")
                {
                    windows += ";window.open('../Reports/Default.aspx?rpt=603&p1=" + lblClientNo.Text + "','Report2')";
                }
                if (ds.Tables[0].Rows[0]["sama"].ToString() == "1")
                {
                    windows += ";window.open('../Reports/Default.aspx?rpt=605&p1=" + lblClientNo.Text + "','Report3')";
                }
                if (windows.Length > 0)
                {
                    windows = windows.TrimStart(';');

                    Session["601"] = action;
                    Session["603"] = action;
                    Session["605_1"] = actionName;
                    Session["605_2"] = action;
                    ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window", windows, true);
                }
            }
            else
            {
                lblError.Text = "No changes found related to this address.";
            }
        }
    }

    private string loadAddressHistory(string addressID)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "MER_ADDRESS_EDITOR.View_Mer_Address_History";

        oracom.Parameters.Add("p_ma_code", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;

        oracom.Parameters["p_ma_code"].Value = addressID;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        oracon.Close();

        string address_eng_flag = ds.Tables[0].Rows[0]["ENGLISH_ADDRESS1_FLAG"].ToString();
        string address_ar_flag = ds.Tables[0].Rows[0]["ARABIC_ADDRESS1_FLAG"].ToString();
        string city_flag = ds.Tables[0].Rows[0]["CITY_FLAG"].ToString();
        string phone_flag = ds.Tables[0].Rows[0]["TEL_WORK_FLAG"].ToString();

        string address_eng = ds.Tables[0].Rows[0]["ENGLISH_ADDRESS1"].ToString();
        string address_ar = ds.Tables[0].Rows[0]["ARABIC_ADDRESS1"].ToString();
        string city_eng = ds.Tables[0].Rows[0]["CITY"].ToString();
        string city_ar = ds.Tables[0].Rows[0]["CITY_AR"].ToString();
        string phone = ds.Tables[0].Rows[0]["TEL_WORK"].ToString();


        //set the data in the controls
        string reason = "";
        if (address_eng_flag.ToLower().Equals("y"))
            reason += "\n " + address_eng;

        if (address_ar_flag.ToLower().Equals("y"))
            reason += "\n " + address_ar;

        if (city_flag.ToLower().Equals("y"))
            reason += "\n " + city_eng;

        if (city_flag.ToLower().Equals("y"))
            reason += " " + city_ar;

        if (phone_flag.ToLower().Equals("y"))
            reason += "\n " + phone;

        return reason;
    }

    protected void gvAddresses_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        // searching through the rows
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            int rec = int.Parse(DataBinder.Eval(e.Row.DataItem, "rec_flag").ToString());
            int status = int.Parse(DataBinder.Eval(e.Row.DataItem, "status").ToString());
            if (rec == 1)
                if (status == 1)
                    e.Row.BackColor = Color.Tan; // is a "new" row
                else
                    e.Row.BackColor = Color.SkyBlue; // is a "new" row
        }
    }

    protected void gvAddresses_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[7].Visible = false;
            e.Row.Cells[8].Visible = false;
        }
    }

    //****************************************    Services   ****************************************\\

    public static double GetMaxPiCapacity_MCC(string MCC)
    {
        double max_pi_capacity = 0.0;
        DataTable dtRes = new DataTable();

        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);

        OracleCommand oraCom = new OracleCommand();
        oraCom.CommandText = " select max_pi_capacity from lkp_business_type  where MCC ='" + MCC + "'";
        oraCom.Connection = oracon;
        OracleDataAdapter da = new OracleDataAdapter(oraCom);

        da.Fill(dtRes);

        if (dtRes.Rows.Count >= 1)
            Double.TryParse(dtRes.Rows[0]["max_pi_capacity"].ToString(), out max_pi_capacity);

        return max_pi_capacity;
    }

    protected void SetFeeByBusinsessClass(string MCC)
    {
        if (MCC == "0")
            return;

        var Span_Max_Pi_Cap_MCC = GetMaxPiCapacity_MCC(MCC);

        if (Span_Max_Pi_Cap_MCC > 0)
        {
            txtPercentB_lower.Text = "0";
            txtPercentM_lower.Text = "0";
           
            txtPICapacityBank.Text = "0";
            txtPercentM.Text = "0";
            txtPercentB.Text = "0";
            txtPICapacity.Text = Span_Max_Pi_Cap_MCC.ToString();
           // Revert MMS Phase2 Change
          // txtPICapacityBank.Enabled = false;
            txtPercentB_lower.Enabled = false;
            txtPercentM_lower.Enabled = false;
            txtPercentM.Enabled = false;
            txtPercentB.Enabled = false;

            lblPercent.Text = "0";
            lblPercent_lower.Text = "0";
            
        }
        else // Normal Flow
        {
            txtPercentB_lower.Enabled = true;
            txtPercentM_lower.Enabled = true; ;
           // Revert MMS Phase2 Change
           // txtPICapacityBank.Enabled = true;
            txtPercentM.Enabled = true;
            txtPercentB.Enabled = true;

        }

    }
    protected void btnAddServices_Click(object sender, EventArgs e)
    {
        pnlServices.Visible = true;
        ViewState["mode"] = "a";
        txtAccNo.Text = txtAccNoGeneral.Text.Replace(" ", "");
        txtPercentB.Text = "0";
        lblPercent.Text = txtPercentM.Text;
        if (ddlServices.SelectedValue == "001") // SPAN
        {
            txtPercentM.Text = "0";
            lblPercent.Text = txtPercentM.Text;

            //MM_CR
            txtPercentB_lower.Text = "0";
            txtPercentM_lower.Text = "0";
            rowSPAN1.Visible = true;
            rowSPAN2.Visible = true;
            rowSPAN3.Visible = true;
            // Revert MMS Phase2 Change
           // txtPICapacityBank.Enabled = true;
            txtPercentB_lower.Enabled = true;
            txtPercentM_lower.Enabled = true;
            txtPercentB.Enabled = true;
            txtPercentM.Enabled = true;

        }
        else
        {
            txtPercentM.Text = ViewState["cat_com"].ToString();
            //MM_CR
            rowSPAN1.Visible = false;
            rowSPAN2.Visible = false;
            rowSPAN3.Visible = false;
        }
        lblPercent.Text = txtPercentM.Text;
        ddlServices.Enabled = true;

        //hide the old version
        ddlCurrancyOld.Visible = false;
        txtPercentMOld.Visible = false;
        txtPercentBOld.Visible = false;
        txtPercentM_lowerOld.Visible = false;
        txtPercentB_lowerOld.Visible = false;

        txtAccNoOld.Visible = false;
        txtBrAccNoOld.Visible = false;
        chkKeyEntryOld.Visible = false;

        if (ddlServices.SelectedValue == "001")
        {
            getFeesMax();
            SetFeeByBusinsessClass(ddlBusinessClass.SelectedValue);
        }
        else if (ddlServices.SelectedValue == "006")
        {
            // getFeesMax();
            getFeesMaxGCC();
        }

    }

    protected void ddlServices_SelectedIndexChanged(object sender, EventArgs e)
    {
        rowSPAN1.Visible = false;
        rowSPAN2.Visible = false;
        rowSPAN3.Visible = false;
        lblPICapacity.Visible = false;
        txtPICapacity.Visible = false;
        lblSettledBy.Visible = false;
        ddlSettledBy.Visible = false;
        if (ddlServices.SelectedValue == "001")
        {
            //txtPercentM.Text = "0";
            PIRow.Visible = false;
            lblPICapacity.Visible = true;
            //lblPIWaive.Visible = true;
            //chkPIWaive.Visible = true;
            //txtPICapacityOld.Visible = true;
            txtPICapacity.Visible = true;

             // MM Phase 2
             // lblPICapacityBank.Visible = true;
            // txtPICapacityBank.Visible = true;
           // Revert MMS Phase2 Change
              lblPICapacityBank.Visible = false;
              txtPICapacityBank.Visible = false;

            if (ViewState["mode"].ToString().Equals("a"))
            {
                getFeesMax();
                SetFeeByBusinsessClass(ddlBusinessClass.SelectedValue);
            }
            //MM_CR
            txtPercentB_lower.Text = "0";
            txtPercentM_lower.Text = "0";
            rowSPAN1.Visible = true;
            rowSPAN2.Visible = true;
            rowSPAN3.Visible = true;
        }
        else if (ddlServices.SelectedValue == "006")
        {
            //txtPercentM.Text = "0";
            PIRow.Visible = false;
            lblPICapacity.Visible = true;
            //lblPIWaive.Visible = true;
            //chkPIWaive.Visible = true;
            //txtPICapacityOld.Visible = true;
            txtPICapacity.Visible = true;

            // MM Phase 2
            //  lblPICapacityBank.Visible = true;
            //  txtPICapacityBank.Visible = true;
            // Revert MMS Phase2 Change
            lblPICapacityBank.Visible = false;
            txtPICapacityBank.Visible = false;
            if (ViewState["mode"].ToString().Equals("a"))
            {
                // getFeesMax();
                getFeesMaxGCC();
            }
        }
        else if (ddlServices.SelectedValue == "007")
        {
            //txtPercentM.Text = "0";
            lblSettledBy.Visible = true;
            //lblPIWaive.Visible = true;
            //chkPIWaive.Visible = true;
            //txtPICapacityOld.Visible = true;
            ddlSettledBy.Visible = true;
               
            // MM Phase 2
            //  lblPICapacityBank.Visible = true;
            //  txtPICapacityBank.Visible = true;
            // Revert MMS Phase2 Change
            lblPICapacityBank.Visible = false;
            txtPICapacityBank.Visible = false;
            if (ViewState["mode"].ToString().Equals("a"))
            {
                // getFeesMax();
                getFeesMaxGCC();
            }
        }

        else
        {
            txtPercentM.Text = ViewState["cat_com"].ToString();
            PIRow.Visible = true;
            lblPICapacity.Visible = false;
            //lblPIWaive.Visible = false;
            //chkPIWaive.Visible = false;
            //txtPICapacityOld.Visible = false;
            txtPICapacity.Visible = false;

            // MM Phase 2
            lblPICapacityBank.Visible = false;
            txtPICapacityBank.Visible = false;

        }

        lblPercent.Text = txtPercentM.Text;
    }

    protected void btnCancelService_Click(object sender, EventArgs e)
    {
        lblError.Text = "";
        pnlServices.Visible = false;
        ViewState["mode"] = null;
    }

    protected void btnSaveService_Click(object sender, EventArgs e)
    {
        try
        {
            string mode = ViewState["mode"].ToString();
            string error = "";

            if (ddlServices.SelectedValue == "001")
            {


                lblError.Text = "";

                if (txtPercentM.Text.Trim().Length == 0)
                {
                    lblError.Text = "Please enter the 'Fee Percentage (merchant)' field";
                    return;
                }

                if (txtPercentB.Text.Trim().Length == 0)
                {
                    lblError.Text = "Please enter the 'Fee Percentage (bank)' field";
                    return;
                }

                if (txtPercentM_lower.Text.Trim().Length == 0)
                {
                    lblError.Text = "Please enter the 'Fee Percentage lower (merchant)' field";
                    return;
                }

                if (txtPercentB_lower.Text.Trim().Length == 0)
                {
                    lblError.Text = "Please enter the 'Fee Percentage lower (bank)' field";
                    return;
                }
                // Revert MMS Phase2 Change
                //if (txtPICapacity.Text.Trim().Length == 0 || txtPICapacityBank.Text.Trim().Length == 0)
                //{
                //    lblError.Text = "Please enter the 'Fee Capacity' fields";
                //    return;
                //}
                if (Convert.ToDouble(txtPercentM.Text) + Convert.ToDouble(txtPercentB.Text) > Span_Fee_Limit || Convert.ToDouble(txtPercentM_lower.Text) + Convert.ToDouble(txtPercentB_lower.Text) > Span_Fee_Limit_lower)
                {
                    lblError.Text = "Sum of branch and Merchant fee % cannot be more than cap value";
                    return;
                }

                // Revert MMS Phase2 Change
                //if (Convert.ToDouble(txtPICapacityBank.Text) + Convert.ToDouble(txtPICapacity.Text) > Span_Max_Pi_Cap || Convert.ToDouble(txtPercentM_lower.Text) + Convert.ToDouble(txtPercentB_lower.Text) > Span_Fee_Limit_lower)
                //{
                //    lblError.Text = "Sum of Bank and Merchant Fee Capicity cannot be more than Max. Fee Cap value: " + Span_Max_Pi_Cap;
                //    return;
                //}

                if  (Convert.ToDouble(txtPICapacity.Text) > Span_Max_Pi_Cap)
                {
                    lblError.Text = "Merchant Fee Capicity should not be more than Max. Fee Cap value: " + Span_Max_Pi_Cap;
                    return;
                }

                if (Convert.ToDouble(txtPercentM_lower.Text) + Convert.ToDouble(txtPercentB_lower.Text) > Span_Fee_Limit_lower)
                {
                    lblError.Text = "Sum of Merchant and Bank Lower Percent should not be more than Max. Fee Percent value: " + Span_Fee_Limit_lower;
                    return;
                }

                if (txtPercentM.Enabled == false) // Disable To charge Flat Fee based on MCC
                {
                    var Span_Max_Pi_Cap_MCC = GetMaxPiCapacity_MCC(ddlBusinessClass.SelectedValue);
                    if (Convert.ToDouble(txtPICapacity.Text) > Span_Max_Pi_Cap_MCC)
                    {
                        lblError.Text = "MCC:" + ddlBusinessClass.SelectedValue + " has Max. Merchant Fee Cap value: " + Span_Max_Pi_Cap_MCC;
                        return;
                    }
                }

            }

            if (mode.Equals("a"))
            {
                string clID = Request.QueryString["clID"];
                bool saved = addService(clID, ref error);
                if (saved)
                {
                    if (ddlServices.SelectedValue == "002")
                    {
                        addDuplicateService(clID, ref error);
                    }
                    lblError.Text = "Service data Saved";
                }
                else
                {
                    if (Helper.OracleError(error))
                    {
                        lblError.Text = "Save Failed";
                        ExceptionUtility.LogException(9, "", "", "btnSaveService_Click", error);
                    }
                    else
                        lblError.Text = error;
                }
            }
            else if (mode.Equals("u"))
            {
                string Uid = ViewState["rowid"].ToString();
                bool saved = updateService(Uid, ref error);
                if (saved)
                {
                    lblError.Text = "Service data Saved";
                }
                else
                {
                    if (Helper.OracleError(error))
                    {
                        lblError.Text = "Save Failed";
                        ExceptionUtility.LogException(9, "", "", "btnSaveService_Click", error);
                    }
                    else
                        lblError.Text = error;
                }
            }
            loadMerchantServices(Request.QueryString["clID"], Helper.gridSize(), 1);
            ViewState["mode"] = null;
            ViewState["rowid"] = null;
            pnlServices.Visible = false;
        }
        catch (Exception ex)
        {
        }
    }

    private bool addService(string clientNo, ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "merchant_service.add_merchant_appl_service";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_client_no", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_service_id", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_fees_percent", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_fee_base", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_fee_curr", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_fee_rule", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_bank_fee_percent", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_acct_number", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_br_acct_number", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_key_entry", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_waive_ncb_cards", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_pi_cap", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_settledby", OracleType.VarChar).Direction = ParameterDirection.Input;

        //oracom.Parameters.Add("p_FIXEDFEEORPERCENT_FLAG", OracleType.VarChar).Direction = ParameterDirection.Input;
        //oracom.Parameters.Add("p_MERCH_FIXEDFEES", OracleType.Number).Direction = ParameterDirection.Input;
        //oracom.Parameters.Add("p_BANK_FIXEDFEES", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;


        //MM_CR 
        oracom.Parameters.Add("p_fees_percent_lower", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_bank_fee_percent_lower", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters["p_fees_percent_lower"].Value = txtPercentM_lower.Text.Length >= 1 ? txtPercentM_lower.Text : "0";
        oracom.Parameters["p_bank_fee_percent_lower"].Value = txtPercentB_lower.Text.Length >= 1 ? txtPercentB_lower.Text : "0";

        //MM_CR 

        // VAT_CR
        oracom.Parameters.Add("p_vat_code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_br_code", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters["p_vat_code"].Value = ddlVat.SelectedValue; // VAT Phase 2
        oracom.Parameters["p_br_code"].Value = ddlBranchAcc.SelectedValue;
        // VAT_CR
        // MR CR Phase 2
        oracom.Parameters.Add("p_bank_pi_cap", OracleType.Number).Direction = ParameterDirection.Input;
       
        //if (txtPICapacityBank.Text.Trim().Length == 0)
        //    oracom.Parameters["p_bank_pi_cap"].Value = OracleNumber.Null;
        //else
        //    oracom.Parameters["p_bank_pi_cap"].Value = txtPICapacityBank.Text;
        // Revert MMS Phase2 Change
        oracom.Parameters["p_bank_pi_cap"].Value = OracleNumber.Null;
        //
        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.Parameters["p_client_no"].Value = clientNo;

        oracom.Parameters["p_service_id"].Value = ddlServices.SelectedValue;
        oracom.Parameters["p_fees_percent"].Value = txtPercentM.Text;
        oracom.Parameters["p_bank_fee_percent"].Value = txtPercentB.Text;

        //oracom.Parameters["p_MERCH_FIXEDFEES"].Value = txtFixedFeesMerchant.Text;
        //oracom.Parameters["p_BANK_FIXEDFEES"].Value = txtFixedFeesBranch.Text;
        //if(rdFixed.Checked)
        //    oracom.Parameters["p_FIXEDFEEORPERCENT_FLAG"].Value = "n";
        //else
        //    oracom.Parameters["p_FIXEDFEEORPERCENT_FLAG"].Value = "y";



        oracom.Parameters["p_fee_base"].Value = "1";
        oracom.Parameters["p_fee_curr"].Value = ddlCurrancy.SelectedValue;//txtCurrancy.Text;
        oracom.Parameters["p_fee_rule"].Value = "1";
        oracom.Parameters["p_acct_number"].Value = txtAccNo.Text;
        oracom.Parameters["p_br_acct_number"].Value = txtBrAccNo.Text;
        if (chkKeyEntry.Checked)
            oracom.Parameters["p_key_entry"].Value = "1";
        else
            oracom.Parameters["p_key_entry"].Value = "0";

        if (txtPICapacity.Text.Trim().Length == 0)
            oracom.Parameters["p_pi_cap"].Value = OracleNumber.Null;
        else
            oracom.Parameters["p_pi_cap"].Value = txtPICapacity.Text;

        //using p_waive_ncb_cards to store the delay dropdown
        //if (chkPIWaive.Checked)
        //    oracom.Parameters["p_waive_ncb_cards"].Value = "1";
        //else
        //    oracom.Parameters["p_waive_ncb_cards"].Value = "0";

        oracom.Parameters["p_waive_ncb_cards"].Value = ddlPayDelay.SelectedValue;

        oracom.Parameters["p_settledby"].Value = ddlSettledBy.SelectedValue;


        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    private bool addDuplicateService(string clientNo, ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "merchant_service.add_merchant_appl_service";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_client_no", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_service_id", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_fees_percent", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_fee_base", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_fee_curr", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_fee_rule", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_bank_fee_percent", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_acct_number", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_br_acct_number", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_key_entry", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_waive_ncb_cards", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_pi_cap", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_settledby", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;


        //MM_CR 
        oracom.Parameters.Add("p_fees_percent_lower", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_bank_fee_percent_lower", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters["p_fees_percent_lower"].Value = txtPercentM_lower.Text.Length >= 1 ? txtPercentM_lower.Text : "0";
        oracom.Parameters["p_bank_fee_percent_lower"].Value = txtPercentB_lower.Text.Length >= 1 ? txtPercentB_lower.Text : "0";
        //MM_CR 

        // VAT_CR
        oracom.Parameters.Add("p_vat_code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_br_code", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters["p_vat_code"].Value = ddlVat.SelectedValue;
        oracom.Parameters["p_br_code"].Value = ddlBranchAcc.SelectedValue;
        // VAT_CR
        // MR CR Phase 2
        
        oracom.Parameters.Add("p_bank_pi_cap", OracleType.Number).Direction = ParameterDirection.Input;
        
        //if (txtPICapacityBank.Text.Trim().Length == 0)
        //    oracom.Parameters["p_bank_pi_cap"].Value = OracleNumber.Null;
        //else
        //    oracom.Parameters["p_bank_pi_cap"].Value = txtPICapacityBank.Text;
        // Revert MMS Phase2 Change
        oracom.Parameters["p_bank_pi_cap"].Value = OracleNumber.Null;
        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.Parameters["p_client_no"].Value = clientNo;

        oracom.Parameters["p_service_id"].Value = "003";
        oracom.Parameters["p_fees_percent"].Value = txtPercentM.Text;
        oracom.Parameters["p_bank_fee_percent"].Value = txtPercentB.Text;
        oracom.Parameters["p_fee_base"].Value = "1";
        oracom.Parameters["p_fee_curr"].Value = ddlCurrancy.SelectedValue;//txtCurrancy.Text;
        oracom.Parameters["p_fee_rule"].Value = "1";
        oracom.Parameters["p_acct_number"].Value = txtAccNo.Text;
        oracom.Parameters["p_br_acct_number"].Value = txtBrAccNo.Text;
        if (chkKeyEntry.Checked)
            oracom.Parameters["p_key_entry"].Value = "1";
        else
            oracom.Parameters["p_key_entry"].Value = "0";

        if (txtPICapacity.Text.Trim().Length == 0)
            oracom.Parameters["p_pi_cap"].Value = OracleNumber.Null;
        else
            oracom.Parameters["p_pi_cap"].Value = txtPICapacity.Text;

        //using p_waive_ncb_cards to store the delay dropdown
        //if (chkPIWaive.Checked)
        //    oracom.Parameters["p_waive_ncb_cards"].Value = "1";
        //else
        //    oracom.Parameters["p_waive_ncb_cards"].Value = "0";

        oracom.Parameters["p_waive_ncb_cards"].Value = ddlPayDelay.SelectedValue;
        oracom.Parameters["p_settledby"].Value = ddlSettledBy.SelectedValue;

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    private bool updateService(string serviceID, ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "merchant_service.update_appl_service";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_as_code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_fee_percent", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_bank_fee_percent", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_fee_base", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_fee_curr", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_fee_rule", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_acct_number", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_br_acct_number", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_key_entry", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_waive_ncb_cards", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_pi_cap", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_settledby", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_FIXEDFEEORPERCENT_FLAG", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_MERCH_FIXEDFEES", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_BANK_FIXEDFEES", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        //MM_CR 
        oracom.Parameters.Add("p_fees_percent_lower", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_bank_fee_percent_lower", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters["p_fees_percent_lower"].Value = txtPercentM_lower.Text.Length >= 1 ? txtPercentM_lower.Text : "0";
        oracom.Parameters["p_bank_fee_percent_lower"].Value = txtPercentB_lower.Text.Length >= 1 ? txtPercentB_lower.Text : "0";

        //MM_CR 

        // VAT_CR
        oracom.Parameters.Add("p_vat_code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_br_code", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters["p_vat_code"].Value = ddlVat.SelectedValue;
        oracom.Parameters["p_br_code"].Value = ddlBranchAcc.SelectedValue;
        // VAT_CR

        // MR CR Phase 2
        oracom.Parameters.Add("p_bank_pi_cap", OracleType.Number).Direction = ParameterDirection.Input;

        //if (txtPICapacityBank.Text.Trim().Length == 0)  
        //    oracom.Parameters["p_bank_pi_cap"].Value = OracleNumber.Null;
        //else
        //    oracom.Parameters["p_bank_pi_cap"].Value = txtPICapacityBank.Text;
        // Revert MMS Phase2 Change
        oracom.Parameters["p_bank_pi_cap"].Value = OracleNumber.Null;
        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.Parameters["p_as_code"].Value = serviceID;
        oracom.Parameters["p_fee_percent"].Value = txtPercentM.Text;
        oracom.Parameters["p_bank_fee_percent"].Value = txtPercentB.Text;
        oracom.Parameters["p_fee_base"].Value = "1";
        oracom.Parameters["p_fee_curr"].Value = ddlCurrancy.SelectedValue;//txtCurrancy.Text;
        oracom.Parameters["p_fee_rule"].Value = "1";
        oracom.Parameters["p_acct_number"].Value = txtAccNo.Text;
        oracom.Parameters["p_br_acct_number"].Value = txtBrAccNo.Text;
        if (chkKeyEntry.Checked)
            oracom.Parameters["p_key_entry"].Value = "1";
        else
            oracom.Parameters["p_key_entry"].Value = "0";

        oracom.Parameters["p_MERCH_FIXEDFEES"].Value = OracleNumber.Null;//txtFixedFeesMerchant.Text;
        oracom.Parameters["p_BANK_FIXEDFEES"].Value = OracleNumber.Null;//txtFixedFeesBranch.Text;
        if (rdFixed.Checked)
            oracom.Parameters["p_FIXEDFEEORPERCENT_FLAG"].Value = "n";
        else
            oracom.Parameters["p_FIXEDFEEORPERCENT_FLAG"].Value = "y";

        if (txtPICapacity.Text.Trim().Length == 0)
            oracom.Parameters["p_pi_cap"].Value = OracleNumber.Null;
        else
            oracom.Parameters["p_pi_cap"].Value = txtPICapacity.Text;

        //using p_waive_ncb_cards to store the delay dropdown
        //if (chkPIWaive.Checked)
        //    oracom.Parameters["p_waive_ncb_cards"].Value = "1";
        //else
        //    oracom.Parameters["p_waive_ncb_cards"].Value = "0";

        oracom.Parameters["p_waive_ncb_cards"].Value = ddlPayDelay.SelectedValue;
        oracom.Parameters["p_settledby"].Value = ddlSettledBy.SelectedValue;

        oracom.ExecuteNonQuery();
        oracon.Close();
        ddlServices.Enabled = false;
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    private void loadServiceByID(string serviceID)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "merchant_service.get_appl_serv_by_id";

        oracom.Parameters.Add("p_as_code", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;

        oracom.Parameters["p_as_code"].Value = serviceID;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        oracon.Close();

        if (ds.Tables[0].Rows.Count < 1)
        {
            lblError.Text = "Data Not Found against Service ID " + serviceID;
            return;
        }
        else
            lblError.Text = "";

        //set the data in the controls
        ddlServices.SelectedValue = ds.Tables[0].Rows[0]["service_id"].ToString();
        txtPercentM.Text = ds.Tables[0].Rows[0]["fee_percent"].ToString();
        txtPercentB.Text = ds.Tables[0].Rows[0]["bank_fee_percent"].ToString();
        // MM CR
        txtPercentM_lower.Text = ds.Tables[0].Rows[0]["fee_percent_lower"].ToString();
        txtPercentB_lower.Text = ds.Tables[0].Rows[0]["bank_fee_percent_lower"].ToString();
        //
        // VAT_CR
        ddlVat.SelectedValue = ds.Tables[0].Rows[0]["vat_fee_code"].ToString();
        //VAT_PH2_CR

        ddlBranchAcc.SelectedValue = ds.Tables[0].Rows[0]["branch"].ToString();
        loadBranchAcc(2);
        //
        try
        {
            decimal m = decimal.Parse(txtPercentM.Text);
            decimal b = decimal.Parse(txtPercentB.Text);
            lblPercent.Text = (m + b).ToString();
            //MM CR
            m = decimal.Parse(txtPercentM_lower.Text);
            b = decimal.Parse(txtPercentB_lower.Text);
            lblPercent_lower.Text = (m + b).ToString();
            //MM CR
        }
        catch (Exception ex)
        {

        }

        ddlCurrancy.SelectedValue = ds.Tables[0].Rows[0]["fee_curr"].ToString();
        txtAccNo.Text = ds.Tables[0].Rows[0]["acct_number"].ToString();
        txtBrAccNo.Text = ds.Tables[0].Rows[0]["br_acct_number"].ToString();


        if (ds.Tables[0].Rows[0]["key_entry_service"].ToString().Equals("1"))
            chkKeyEntry.Checked = true;

        txtPICapacity.Text = ds.Tables[0].Rows[0]["PI_CAPACITY"].ToString();
        //if (ds.Tables[0].Rows[0]["WAIVE_NCB_CARD"].ToString().Equals("1"))
        //    chkPIWaive.Checked = true;

        pnlServices.Visible = true;

        //load the old version
        ddlCurrancyOld.SelectedValue = ds.Tables[0].Rows[0]["fee_curr_old"].ToString();
        if (ddlCurrancy.SelectedIndex == ddlCurrancyOld.SelectedIndex)
            ddlCurrancyOld.Visible = false;
        else
            ddlCurrancyOld.Visible = true;

        txtPercentMOld.Text = ds.Tables[0].Rows[0]["fee_percent_old"].ToString();
        if (txtPercentMOld.Text == txtPercentM.Text)
            txtPercentMOld.Visible = false;
        else
            txtPercentMOld.Visible = true;

        txtPercentBOld.Text = ds.Tables[0].Rows[0]["bank_fee_percent_old"].ToString();
        if (txtPercentBOld.Text == txtPercentB.Text)
            txtPercentBOld.Visible = false;
        else
            txtPercentBOld.Visible = true;

        // MM CR
        txtPercentB_lowerOld.Text = ds.Tables[0].Rows[0]["bank_fee_percent_lower_old"].ToString();
        if (txtPercentB_lowerOld.Text == txtPercentB_lower.Text)
            txtPercentB_lowerOld.Visible = false;
        else
            txtPercentB_lowerOld.Visible = true;


        txtPercentM_lowerOld.Text = ds.Tables[0].Rows[0]["fee_percent_lower_old"].ToString();
        if (txtPercentM_lowerOld.Text == txtPercentM_lower.Text)
            txtPercentM_lowerOld.Visible = false;
        else
            txtPercentM_lowerOld.Visible = true;

        // MM CR

        txtAccNoOld.Text = ds.Tables[0].Rows[0]["acct_number_old"].ToString();
        if (txtAccNoOld.Text == txtAccNo.Text)
            txtAccNoOld.Visible = false;
        else
            txtAccNoOld.Visible = true;

        if (ds.Tables[0].Rows[0]["key_entry_service_old"].ToString().Equals("1"))
            chkKeyEntryOld.Checked = true;

        if (ds.Tables[0].Rows[0]["key_entry_service_old"].ToString() == ds.Tables[0].Rows[0]["key_entry_service"].ToString())
            chkKeyEntryOld.Visible = false;
        else
            chkKeyEntryOld.Visible = true;


        txtPICapacityOld.Text = ds.Tables[0].Rows[0]["PI_CAPACITY_old"].ToString();
        if (txtPICapacityOld.Text == txtPICapacity.Text || txtPICapacityOld.Text == "")
            txtPICapacityOld.Visible = false;
        else
            txtPICapacityOld.Visible = true;

        // MM Phase 2 CR
        
        txtPICapacityBank.Text = ds.Tables[0].Rows[0]["Bank_PI_CAPACITY"].ToString();

        txtPICapacityBankOld.Text = ds.Tables[0].Rows[0]["Bank_PI_CAPACITY_old"].ToString();

        //if (txtPICapacityBankOld.Text == txtPICapacityBank.Text || txtPICapacityBankOld.Text == "")
        //    txtPICapacityBankOld.Visible = false;
        //else
        //    txtPICapacityBankOld.Visible = true;
        //
       // Revert MMS Phase2 Change
           txtPICapacityBank.Visible = false;
           txtPICapacityBankOld.Visible = false;

        //if (ds.Tables[0].Rows[0]["WAIVE_NCB_CARD_old"].ToString().Equals("1"))
        //    chkPIWaive.Checked = true;

        //if (ds.Tables[0].Rows[0]["WAIVE_NCB_CARD_old"].ToString() == ds.Tables[0].Rows[0]["WAIVE_NCB_CARD"].ToString())
        //    chkPIWaive.Visible = false;
        //else
        //    chkPIWaive.Visible = true;

        PIRow.Visible = false;
        lblPICapacity.Visible = true;
        //lblPIWaive.Visible = true;
        //chkPIWaive.Visible = true;
        txtPICapacity.Visible = true;

        //MM_CR
        rowSPAN1.Visible = true;
        rowSPAN2.Visible = true;
        rowSPAN3.Visible = true;

        if (ddlServices.SelectedValue != "001")
        {
            PIRow.Visible = true;
            lblPICapacity.Visible = false;
            txtPICapacity.Visible = false;
            lblPIWaive.Visible = false;
            chkPIWaive.Visible = false;

            //MR CR
            rowSPAN1.Visible = false;
            rowSPAN2.Visible = false;
            rowSPAN3.Visible = false;
            tr8.Visible = false;
            tr9.Visible = false;
        }
        else
        {
            //tr8.Visible = true;
            //tr9.Visible = true;
            //txtFixedFeesMerchant.Text = ds.Tables[0].Rows[0]["MERCH_FIXEDFEES"].ToString();
            //txtFixedFeesBranch.Text = ds.Tables[0].Rows[0]["BANK_FIXEDFEES"].ToString();
            //string flag = ds.Tables[0].Rows[0]["FIXEDFEEORPERCENT_FLAG"].ToString();
            //if (flag.ToLower().Equals("y"))
            //    rdPercentage.Checked = true;
            //else
            //    rdFixed.Checked = true;

            //lblFixedFlag.Text = GetMaxPiCapacity_MCC(ddlBusinessClass.SelectedValue).ToString();
        }

        if (ddlServices.SelectedValue == "006")
        {
            PIRow.Visible = true;
            lblPICapacity.Visible = true;
            txtPICapacity.Visible = true;
            lblPIWaive.Visible = false;
            chkPIWaive.Visible = false;
        }

        if (ddlServices.SelectedValue == "007")
        {
            lblSettledBy.Visible = true;
            ddlSettledBy.Visible = true;
            ddlSettledBy.SelectedValue = ds.Tables[0].Rows[0]["merch_service_settledby"].ToString();
        }
    }

    protected void gvServices_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("u"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = gvServices.DataKeys[index].Value.ToString();
            loadServiceByID(rowID);

            ViewState["mode"] = "u";
            ViewState["rowid"] = rowID;
            ddlServices.Enabled = false;
     
        }
        else if (e.CommandName.Equals("ar"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = gvServices.DataKeys[index].Value.ToString();
            /*
            ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
                    "window.open('../Reports/Default.aspx?rpt=107&p1=" + rowID + "','Report')", true);*/

            DataSet ds = Helper.getReportEvent(1); //add service
            string action = ds.Tables[0].Rows[0]["event_desc_en"].ToString();
            string actionName = ds.Tables[0].Rows[0]["event_name"].ToString();
            string serviceName = gvServices.Rows[index].Cells[0].Text;
            action = action.Replace("{0}", serviceName);
            string windows = "";

            if (ds.Tables[0].Rows[0]["base24"].ToString() == "1")
            {
                windows += ";window.open('../Reports/Default.aspx?rpt=601&p1=" + lblClientNo.Text + "','Report1')";
            }
            if (ds.Tables[0].Rows[0]["visa"].ToString() == "1")
            {
                windows += ";window.open('../Reports/Default.aspx?rpt=603&p1=" + lblClientNo.Text + "','Report2')";
            }
            if (ds.Tables[0].Rows[0]["sama"].ToString() == "1")
            {
                windows += ";window.open('../Reports/Default.aspx?rpt=605&p1=" + lblClientNo.Text + "','Report3')";
            }
            if (windows.Length > 0)
            {
                windows = windows.TrimStart(';');

                Session["601"] = action;
                Session["603"] = action;
                Session["605_1"] = actionName;
                Session["605_2"] = action;
                ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window", windows, true);
            }
        }
        else if (e.CommandName.Equals("dr"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = gvServices.DataKeys[index].Value.ToString();

            string rec = gvServices.Rows[index].Cells[10].Text;
            string status = gvServices.Rows[index].Cells[11].Text;
            if (rec == "1" && status == "0")
            {

                DataSet ds = Helper.getReportEvent(2); //delete service
                string action = ds.Tables[0].Rows[0]["event_desc_en"].ToString();
                string actionName = ds.Tables[0].Rows[0]["event_name"].ToString();
                string serviceName = gvServices.Rows[index].Cells[0].Text;
                action = action.Replace("{0}", serviceName);
                string windows = "";

                if (ds.Tables[0].Rows[0]["base24"].ToString() == "1")
                {
                    windows += ";window.open('../Reports/Default.aspx?rpt=601&p1=" + lblClientNo.Text + "','Report1')";
                }
                if (ds.Tables[0].Rows[0]["visa"].ToString() == "1")
                {
                    windows += ";window.open('../Reports/Default.aspx?rpt=603&p1=" + lblClientNo.Text + "','Report2')";
                }
                if (ds.Tables[0].Rows[0]["sama"].ToString() == "1")
                {
                    windows += ";window.open('../Reports/Default.aspx?rpt=605&p1=" + lblClientNo.Text + "','Report3')";
                }
                if (windows.Length > 0)
                {
                    windows = windows.TrimStart(';');

                    Session["601"] = action;
                    Session["603"] = action;
                    Session["605_1"] = actionName;
                    Session["605_2"] = action;
                    ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window", windows, true);
                }
            }
            else
            {
                lblError.Text = "Can't generate delete report for this service";
            }
        }
        else if (e.CommandName.Equals("car"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = gvServices.DataKeys[index].Value.ToString();


            DataSet ds1 = getServiceHistory(rowID);

            if (ds1.Tables[0].Rows.Count > 1)
            {
                string toAcct = ds1.Tables[0].Rows[0]["acct_number"].ToString();
                string fromAcct = "";
                for (int i = 0; i < ds1.Tables[0].Rows.Count; i++)
                {
                    if (ds1.Tables[0].Rows[i]["acct_number"].ToString() != toAcct)
                    {
                        fromAcct = ds1.Tables[0].Rows[i]["acct_number"].ToString();
                        break;
                    }
                }

                if (fromAcct.Length > 0)
                {

                    DataSet ds = Helper.getReportEvent(3); //Change Account

                    string action = ds.Tables[0].Rows[0]["event_desc_en"].ToString();
                    string actionName = ds.Tables[0].Rows[0]["event_name"].ToString();
                    action = action.Replace("{0}", fromAcct);
                    action = action.Replace("{1}", toAcct);
                    string windows = "";

                    if (ds.Tables[0].Rows[0]["base24"].ToString() == "1")
                    {
                        windows += ";window.open('../Reports/Default.aspx?rpt=601&p1=" + lblClientNo.Text + "','Report1')";
                    }
                    if (ds.Tables[0].Rows[0]["visa"].ToString() == "1")
                    {
                        windows += ";window.open('../Reports/Default.aspx?rpt=603&p1=" + lblClientNo.Text + "','Report2')";
                    }
                    if (ds.Tables[0].Rows[0]["sama"].ToString() == "1")
                    {
                        windows += ";window.open('../Reports/Default.aspx?rpt=605&p1=" + lblClientNo.Text + "','Report3')";
                    }
                    if (windows.Length > 0)
                    {
                        windows = windows.TrimStart(';');

                        Session["601"] = action;
                        Session["603"] = action;
                        Session["605_1"] = actionName;
                        Session["605_2"] = action;
                        ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window", windows, true);
                    }
                }

            }
            else
            {
                lblError.Text = "There are no changes made to this service account.";
            }
        }
        else if (e.CommandName.Equals("d"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = gvServices.DataKeys[index].Value.ToString();
            string error = "";
            string servicename = gvServices.Rows[index].Cells[0].Text.Trim().ToLower();
            if (servicename.Equals("span"))
                lblError.Text = "SPAN service can't be deleted";
            else
            {
                bool saved = deleteService(rowID, ref error);
                if (saved)
                {
                    lblError.Text = "Service disabled";
                }
                else
                {
                    if (Helper.OracleError(error))
                    {
                        lblError.Text = "An error occured!";
                        ExceptionUtility.LogException(9, "", "", "gvServices_RowCommand.Disable", error);
                    }
                    else
                        lblError.Text = error;
                }
                loadMerchantServices(Request.QueryString["clID"], Helper.gridSize(), 1);
            }
        }
    }

    private bool deleteService(string serviceID, ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "merchant_service.Disable_appl_service";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_as_code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_as_code"].Value = serviceID;

        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    protected void gvServices_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        // searching through the rows
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            int rec = int.Parse(DataBinder.Eval(e.Row.DataItem, "rec_flag").ToString());
            int status = int.Parse(DataBinder.Eval(e.Row.DataItem, "status").ToString());
            if (rec == 1)
                if (status == 1)
                    e.Row.BackColor = Color.Tan; // is a "new" row
                else
                    e.Row.BackColor = Color.SkyBlue; // is a "new" row
        }
    }

    protected void gvServices_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[10].Visible = false;
            e.Row.Cells[11].Visible = false;
        }
    }

    private void getFeesMax() // this is span i.e. Service 001
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "merchant_service.get_fees_max";

        oracom.Parameters.Add("p_cap_max", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_per_max", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        txtPercentM.Text = oracom.Parameters["p_per_max"].Value.ToString();
        txtPICapacity.Text = oracom.Parameters["p_cap_max"].Value.ToString();
        txtPICapacityBank.Text = "0";
        oracon.Close();

    }

    private void getFeesMaxGCC()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "merchant_service.get_fees_max_gcc";
        oracom.Parameters.Add("p_cap_max", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_per_max", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        txtPercentM.Text = oracom.Parameters["p_per_max"].Value.ToString();

        txtPICapacity.Text = oracom.Parameters["p_cap_max"].Value.ToString();

        oracon.Close();

    }

    private DataSet getServiceHistory(string srvID)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "merchant_service.View_Service_Acct_History";

        oracom.Parameters.Add("p_as_code", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;

        oracom.Parameters["p_as_code"].Value = srvID;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        oracon.Close();

        return ds;

    }


    //****************************************    Terminals   ****************************************\\

    protected void btnAddTerminal_Click(object sender, EventArgs e)
    {
        btnCancelTerminalBulk_Click(sender, e);
        pnlTerminals.Visible = true;
        ddlTerminalBusinessType_SelectedIndexChanged(null, null);

        btnCorrectIdentity.Visible = false;
        ViewState["mode"] = "a";

        firstrow.Visible = true;
        //dateInstallation.date = getDayofMonth(DateTime.Now.Day);
        //dateSamaConfirm.date  = getDayofMonth(DateTime.Now.Day);

        ddlStatus.SelectedValue = "001";
        loadTerminals();
        if (ddlTerminals.Items.Count > 0)
            ddlTerminals_SelectedIndexChanged(this, e);
        else
            txtSRNumber.Text = "";
        rowVendor.Visible = false;

        txtTerminalLocationOld.Visible = false;
        txtPrimHostAccOld.Visible = false;
        txtAltHostAccOld.Visible = false;
        txtPrimPhoneNoOld.Visible = false;
        txtReplacementTerminalOld.Visible = false;
        //DropDownList1Old.Visible = false; //Said 20141013
        ddlSrvTypeOld.Visible = false; //Said 20140726

        txtVendor.Text = "";

        txtLowUsageChargesPerTermnial.Text = SystemParam.GetParamByID("565"); ;// ANB Speciial Requirement Span_Low_Usage_Default_MerchantValue_PerTerminal
        txtLowUsageChargesPerTermnialBranch.Text = "0"; //MM CR

        dtReInstall.date = ""; // MM Phase 2
    }

    protected void btnCancelTerminal_Click(object sender, EventArgs e)
    {
        pnlTerminals.Visible = false;
        ViewState["mode"] = null;
        lblError.Text = "";
    }

    protected void btnSaveTerminal_Click(object sender, EventArgs e)
    {
        try
        {
            if (!Page.IsValid)
            {
                lblError.Text = "One or more Validation Failed";
                return;
            }

            if(String.IsNullOrWhiteSpace(txtCostOfPOS.Text) )
                lblError.Text = "Cost of POS Field cannot be Empty";

            //if (txtPrimPhoneNo2.Text.Length > 0 && txtPrimPhoneNo2.Text.Length != 2)
            if (txtPrimPhoneNo2.Text.Length > 0 && txtPrimPhoneNo2.Text.Length < 2)
                lblError.Text = "Primary Phone Number (Area Code) must be at least 2 digits";
            else if (txtPrimPhoneNo.Text.Length > 0 && txtPrimPhoneNo.Text.Length != 7)
                lblError.Text = "Primary Phone Number must be at least 7 digits";
            else if (txtSRNumber.Text.Length == 0)
                lblError.Text = "SR Number is required";

            else if (txtLowUsageChargesPerTermnial.Text.Trim().Length < 1 || txtLowUsageChargesPerTermnialBranch.Text.Trim().Length < 1)
                lblError.Text = "Please Enter Low Usage Charges ";
            else if (Convert.ToDouble(txtLowUsageChargesPerTermnial.Text) + Convert.ToDouble(txtLowUsageChargesPerTermnialBranch.Text)
                > Span_Low_Usage_Cap_PerTerminal) // MM CR
            {
                lblError.Text = "Sum of Low Usage Charges(Branch and Merchant) per Terminal should not be more than cap value " + Span_Low_Usage_Cap_PerTerminal;
            }

            else
            {
                string mode = ViewState["mode"].ToString();
                string error = "";
                if (mode.Equals("a"))
                {

                    if (ddlTerminals.Items.Count > 0)
                    {
                        string clID = Request.QueryString["clID"];
                        bool saved = addTerminal(clID, ref error);
                        if (saved)
                        {
                            lblError.Text = "Terminal data Saved";
                            ExceptionUtility.LogException(0, "MER_DEVICE_LINK_EDITOR.Add_Client_Device_Link", "", "btnSaveTerminal_Click", " Client No: " + clID);
                        }
                        else
                        {
                            if (Helper.OracleError(error))
                            {
                                lblError.Text = "Save Failed";
                                ExceptionUtility.LogException(9, "", "", "btnSaveTerminal_Click", error);
                            }
                            else
                                lblError.Text = error;
                        }
                    }
                    else
                        lblError.Text = "No Terminals Available Now";
                }
                else if (mode.Equals("u"))
                {
                    string Uid = ViewState["rowid"].ToString();
                    bool saved = updateTerminal(Uid, ref error);
                    if (saved)
                    {
                        lblError.Text = "Terminal data Saved";
                        ExceptionUtility.LogException(0, "MER_DEVICE_LINK_EDITOR.Update_Client_Device_Link", "", "btnSaveTerminal_Click", " terminalID : " + Uid);
                    }
                    else
                    {
                        if (Helper.OracleError(error))
                        {
                            lblError.Text = "Save Failed";
                            ExceptionUtility.LogException(9, "", "", "btnSaveTerminal_Click", error);
                        }
                        else
                            lblError.Text = error;
                    }
                }
                loadMerchantTerminals(Request.QueryString["clID"], Helper.gridSize(), 1);
                ViewState["mode"] = null;
                ViewState["rowid"] = null;
                pnlTerminals.Visible = false;
            }
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex, "btnSaveTerminal_Click", "btnSaveTerminal_Click", "btnSaveTerminal_Click", "");
        }
    }

    private bool addTerminal(string clientNo, ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "MER_DEVICE_LINK_EDITOR.Add_Client_Device_Link";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_client_no", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_terminal_id", OracleType.VarChar).Direction = ParameterDirection.Input;
        //oracom.Parameters.Add("p_region", OracleType.VarChar).Direction = ParameterDirection.Input;
        //oracom.Parameters.Add("p_language", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_terminal_location", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_primary_host_access", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_alternative_host_access", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_primary_phone_number", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_srv_type", OracleType.VarChar).Direction = ParameterDirection.Input; //Said 20140726
        oracom.Parameters.Add("p_sr_number", OracleType.VarChar).Direction = ParameterDirection.Input;//Amjath 20140823
        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_lang"].Value = "EN";

        // MM CR
        oracom.Parameters.Add("p_SpanPOS_lowUsageCharges", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_SpanPOS_lowUsageChargesBr", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters["p_SpanPOS_lowUsageCharges"].Value = txtLowUsageChargesPerTermnial.Text.Trim();
        oracom.Parameters["p_SpanPOS_lowUsageChargesBr"].Value = txtLowUsageChargesPerTermnialBranch.Text.Trim();

        // MM CR
        // MM Phase 2
        oracom.Parameters.Add("p_installed_date", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters["p_installed_date"].Value = dtInstall.date;

        oracom.Parameters.Add("p_re_installed_date", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters["p_re_installed_date"].Value = dtReInstall.date;

        oracom.Parameters.Add("p_COST_of_POS", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters["p_COST_of_POS"].Value = Convert.ToDecimal(txtCostOfPOS.Text); ;


        oracom.Parameters.Add("p_Terminal_business_type_ID", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_Terminal_Provider_ID", OracleType.Number).Direction = ParameterDirection.Input;

       oracom.Parameters["p_Terminal_business_type_ID"].Value = ddlTerminalBusinessType.SelectedIndex != 0 ? ddlTerminalBusinessType.SelectedValue : "0";
       oracom.Parameters["p_Terminal_Provider_ID"].Value = ddlTerminalProvider.SelectedIndex != 0 ?ddlTerminalProvider.SelectedValue:"0";
      

    

        //

        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.Parameters["p_client_no"].Value = clientNo;

        oracom.Parameters["p_terminal_id"].Value = ddlTerminals.SelectedValue;
        //oracom.Parameters["p_region"].Value = ddlRegion.SelectedValue;
        //oracom.Parameters["p_language"].Value = DropDownList1.SelectedValue;
        oracom.Parameters["p_terminal_location"].Value = txtTerminalLocation.Text;
        oracom.Parameters["p_primary_host_access"].Value = ddlUpdateAction.SelectedValue;
        oracom.Parameters["p_alternative_host_access"].Value = txtAltHostAcc.Text;
        oracom.Parameters["p_srv_type"].Value = ddlSrvType.SelectedValue; //Said 20140726
        oracom.Parameters["p_sr_number"].Value = txtSRNumber.Text;//Amjath 20140823
        if (txtPrimPhoneNo2.Text.Length == 2)
        {
            txtPrimPhoneNo2.Text = txtPrimPhoneNo2.Text + " ";
        }
        oracom.Parameters["p_primary_phone_number"].Value = txtPrimPhoneNo2.Text + txtPrimPhoneNo.Text; //area code + phone number





        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }
    private bool addTerminalBulk(string clientNo, ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "MER_DEVICE_LINK_EDITOR.add_bulk_device_link";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_client_no", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_vendor", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_term_type", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_srv_type", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_free_new", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_sr_number", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_term_count", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();
        oracom.Parameters["p_client_no"].Value = clientNo;
        oracom.Parameters["p_vendor"].Value = ddlVendor.SelectedValue;
        oracom.Parameters["p_term_type"].Value = ddlTerminalType.SelectedValue;
        oracom.Parameters["p_srv_type"].Value = ddlServiceType.SelectedValue;
        oracom.Parameters["p_free_new"].Value = ddlStatusBulk.SelectedValue;
        oracom.Parameters["p_sr_number"].Value = txtSRNumberBulk.Text;
        oracom.Parameters["p_term_count"].Value = txtNoTerminals.Text;

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }
    private bool updateTerminal(string terminalID, ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "MER_DEVICE_LINK_EDITOR.Update_Client_Device_Link";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_dvl_code", OracleType.Number).Direction = ParameterDirection.Input;


        //oracom.Parameters.Add("p_language", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_terminal_location", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_primary_host_access", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_alternative_host_access", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_primary_phone_number", OracleType.VarChar).Direction = ParameterDirection.Input;
        //oracom.Parameters.Add("p_srv_type", OracleType.VarChar).Direction = ParameterDirection.Input;//Said 20140726
        oracom.Parameters.Add("p_sr_number", OracleType.VarChar).Direction = ParameterDirection.Input;//Amjath 20140823
        oracom.Parameters.Add("p_replace_term_id", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.Parameters["p_dvl_code"].Value = terminalID;

        //oracom.Parameters["p_language"].Value = DropDownList1.SelectedValue;
        oracom.Parameters["p_terminal_location"].Value = txtTerminalLocation.Text;
        oracom.Parameters["p_primary_host_access"].Value = ddlUpdateAction.SelectedValue;
        oracom.Parameters["p_alternative_host_access"].Value = txtAltHostAcc.Text;
        //oracom.Parameters["p_srv_type"].Value = ddlSrvType.SelectedValue;//Said 20140726
        oracom.Parameters["p_sr_number"].Value = txtSRNumber.Text;//Amjath 20140823
        if (txtPrimPhoneNo2.Text.Length == 2)
        {
            txtPrimPhoneNo2.Text = txtPrimPhoneNo2.Text + " ";
        }
        oracom.Parameters["p_primary_phone_number"].Value = txtPrimPhoneNo2.Text + txtPrimPhoneNo.Text;
        oracom.Parameters["p_replace_term_id"].Value = txtReplacementTerminal.Text;

        //oracom.Parameters["p_tfr_code"].Value = OracleNumber.Null;
        //oracom.Parameters["p_rental_amount"].Value = OracleNumber.Null;

        // MM CR
        oracom.Parameters.Add("p_SpanPOS_lowUsageCharges", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_SpanPOS_lowUsageChargesBr", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters["p_SpanPOS_lowUsageCharges"].Value = txtLowUsageChargesPerTermnial.Text.Trim();

        oracom.Parameters["p_SpanPOS_lowUsageChargesBr"].Value = txtLowUsageChargesPerTermnialBranch.Text.Trim();


        // MM CR
        oracom.Parameters.Add("p_installed_date", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters["p_installed_date"].Value = dtInstall.date;

        // MM 2 CR
        oracom.Parameters.Add("p_re_installed_date", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters["p_re_installed_date"].Value = dtReInstall.date;

        oracom.Parameters.Add("p_COST_of_POS", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters["p_COST_of_POS"].Value = Convert.ToDecimal(txtCostOfPOS.Text);


        oracom.Parameters.Add("p_Terminal_business_type_ID", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_Terminal_Provider_ID", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters["p_Terminal_business_type_ID"].Value = ddlTerminalBusinessType.SelectedIndex != 0 ? ddlTerminalBusinessType.SelectedValue : "0";
        oracom.Parameters["p_Terminal_Provider_ID"].Value = ddlTerminalProvider.SelectedIndex != 0 ? ddlTerminalProvider.SelectedValue : "0";
    
        
        //
        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    private void loadTerminalByID(string terminalID)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "MER_DEVICE_LINK_EDITOR.get_device_link_by_id";

        oracom.Parameters.Add("p_dvl_code", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;

        oracom.Parameters["p_dvl_code"].Value = terminalID;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        oracon.Close();

        if (ds.Tables[0].Rows.Count < 1)
        {  
            lblError.Text="No Data Found for dvl_code"+terminalID;
             return ;
        }
        // MM CR
        txtLowUsageChargesPerTermnial.Text = ds.Tables[0].Rows[0]["SpanPOS_lowUsageCharges"].ToString();
        txtLowUsageChargesPerTermnialBranch.Text = ds.Tables[0].Rows[0]["SpanPOS_lowUsageChargesBr"].ToString();
        if (String.IsNullOrWhiteSpace(txtLowUsageChargesPerTermnial.Text))
            txtLowUsageChargesPerTermnial.Text = "0";
        if (String.IsNullOrWhiteSpace(txtLowUsageChargesPerTermnialBranch.Text))
            txtLowUsageChargesPerTermnialBranch.Text = "0";
        //

        //set the data in the controls
        //ddlTerminals.SelectedValue = ds.Tables[0].Rows[0]["service_id"].ToString();
        // MM 2
        //lblInstall.Text = ds.Tables[0].Rows[0]["installed_date"].ToString();
        dtInstall.date = ds.Tables[0].Rows[0]["installed_date"].ToString();
        // MM 2
        dtReInstall.date = ds.Tables[0].Rows[0]["re_installed_date"].ToString();

        txtCostOfPOS.Text = ds.Tables[0].Rows[0]["COST_OF_POS"].ToString();
        if (String.IsNullOrWhiteSpace(txtCostOfPOS.Text))
            txtCostOfPOS.Text = "0";

        if (!String.IsNullOrWhiteSpace(ds.Tables[0].Rows[0]["terminal_business_type_id"].ToString()))
            ddlTerminalBusinessType.SelectedValue = ds.Tables[0].Rows[0]["terminal_business_type_id"].ToString();
        else
            ddlTerminalBusinessType.SelectedIndex = 0;//Select

        if (!String.IsNullOrWhiteSpace(ds.Tables[0].Rows[0]["terminal_provider_id"].ToString()))
            ddlTerminalProvider.SelectedValue = ds.Tables[0].Rows[0]["terminal_provider_id"].ToString();
        else
            ddlTerminalProvider.SelectedIndex = 0;//Select

        //MM 2 Ends

        lblTermCost.Text = ds.Tables[0].Rows[0]["term_cost"].ToString(); //Said 20140726
        lblTermRevenue.Text = ds.Tables[0].Rows[0]["term_revenue"].ToString();//Said 20140726
        try
        {
        ddlSrvType.SelectedValue = ds.Tables[0].Rows[0]["term_srv_type"].ToString(); //Said 20140726
        }
        catch (Exception eeee) { }
        txtSRNumber.Text = ds.Tables[0].Rows[0]["sr_number"].ToString();//Amjath 20140823
        dateSamaConfirm.date = ds.Tables[0].Rows[0]["sama_confirm_date"].ToString();
        txtTerminalIdentityData.Text = ds.Tables[0].Rows[0]["terminal_identity_data"].ToString();
        //DropDownList1.SelectedValue = ds.Tables[0].Rows[0]["LANGUAGE"].ToString();//Said 20141013
        txtTerminalLocation.Text = ds.Tables[0].Rows[0]["terminal_location"].ToString();
        //txtPrimHostAcc.Text = ds.Tables[0].Rows[0]["primary_host_access"].ToString();
        txtAltHostAcc.Text = ds.Tables[0].Rows[0]["alternative_host_access"].ToString();
        txtVendor.Text = ds.Tables[0].Rows[0]["Vendor"].ToString();
        txtTRSM.Text = ds.Tables[0].Rows[0]["TRSM"].ToString();
        txtVendorNote.Text = ds.Tables[0].Rows[0]["vndr_rsp_note"].ToString();
        try
        {
            ddlUpdateAction.SelectedValue = ds.Tables[0].Rows[0]["primary_host_access"].ToString();
        }
        catch (Exception eeee) { }
        //Said 20140726
        //string srvSent = ds.Tables[0].Rows[0]["srv_sent"].ToString();
        //if (srvSent.Equals("Y")) ddlSrvType.Enabled = false;
        //else ddlSrvType.Enabled = true;
        //Said 20140726


        //Merchant CR Modified By Nashaat
        if (ds.Tables[0].Rows[0]["primary_phone_number"].ToString().Length > 0)
        {
            txtPrimPhoneNo.Text = ds.Tables[0].Rows[0]["primary_phone_number"].ToString().Substring(3); //phone number
            txtPrimPhoneNo2.Text = ds.Tables[0].Rows[0]["primary_phone_number"].ToString().Substring(0, 3).Trim();//area code

        }


        ddlStatus.SelectedValue = ds.Tables[0].Rows[0]["status"].ToString();
        txtoldClientID.Text = ds.Tables[0].Rows[0]["old_client_number"].ToString();
        txtReplacementTerminal.Text = ds.Tables[0].Rows[0]["replacement_term_id"].ToString();
        txtNotifyDate.Text = ds.Tables[0].Rows[0]["vndr_notif_dt"].ToString();
        txtResponseDate.Text = ds.Tables[0].Rows[0]["vndr_resp_dt"].ToString();
        rowVendor.Visible = true;
        oldclientrow.Visible = true;
        pnlTerminals.Visible = true;
        ddlTerminalBusinessType_SelectedIndexChanged(null, null);

        //load the old values

        txtTerminalLocationOld.Text = ds.Tables[0].Rows[0]["terminal_location_old"].ToString();
        if (txtTerminalLocationOld.Text == txtTerminalLocation.Text)
            txtTerminalLocationOld.Visible = false;
        else
            txtTerminalLocationOld.Visible = true;

        txtPrimHostAccOld.Text = ds.Tables[0].Rows[0]["primary_host_access_old"].ToString();
        if (txtPrimHostAccOld.Text == txtPrimHostAcc.Text)
            txtPrimHostAccOld.Visible = false;
        else
            txtPrimHostAccOld.Visible = true;

        txtAltHostAccOld.Text = ds.Tables[0].Rows[0]["alternative_host_access_old"].ToString();
        if (txtAltHostAccOld.Text == txtAltHostAcc.Text)
            txtAltHostAccOld.Visible = false;
        else
            txtAltHostAccOld.Visible = true;

        if (ds.Tables[0].Rows[0]["primary_phone_number_old"].ToString().Length > 0)
        {
            txtPrimPhoneNoOld.Text = ds.Tables[0].Rows[0]["primary_phone_number_old"].ToString().Substring(2);
            txtPrimPhoneNoOld2.Text = ds.Tables[0].Rows[0]["primary_phone_number_old"].ToString().Substring(0, 2);
            //Merchant CR: modified by Mohamed Said 21-Jan-2012 
            if (txtPrimPhoneNoOld2.Text + txtPrimPhoneNoOld.Text == txtPrimPhoneNo2.Text + txtPrimPhoneNo.Text)
            {
                txtPrimPhoneNoOld.Visible = false;
                txtPrimPhoneNoOld2.Visible = false;
            }
            else
            {
                txtPrimPhoneNoOld2.Visible = true;
                txtPrimPhoneNoOld.Visible = true;
            }

        }


        txtReplacementTerminalOld.Text = ds.Tables[0].Rows[0]["replacement_term_id_old"].ToString();
        if (txtReplacementTerminalOld.Text == txtReplacementTerminal.Text)
            txtReplacementTerminalOld.Visible = false;
        else
            txtReplacementTerminalOld.Visible = true;

        // Said 20141013
        //DropDownList1Old.SelectedValue = ds.Tables[0].Rows[0]["LANGUAGE_old"].ToString();
        //if (DropDownList1Old.SelectedIndex == DropDownList1.SelectedIndex)
        //    DropDownList1Old.Visible = false;
        //else
        //    DropDownList1Old.Visible = true;

        //Said 20140726 start
        if (ds.Tables[0].Rows[0]["term_srv_type_old"].ToString() != "")//Amjath 20140824
            try
            {
                ddlSrvTypeOld.SelectedValue = ds.Tables[0].Rows[0]["term_srv_type_old"].ToString();//Amjath 20140824
            }
            catch (Exception eeee) { }
        if (ddlSrvTypeOld.SelectedIndex == ddlSrvType.SelectedIndex)
            ddlSrvTypeOld.Visible = false;
        else
            ddlSrvTypeOld.Visible = true;
        //Said 20140726 end

        txtTerminalIdentityDataOld.Text = ds.Tables[0].Rows[0]["terminal_identity_data_old"].ToString();
        if (txtTerminalIdentityDataOld.Text == txtTerminalIdentityData.Text)
            txtTerminalIdentityDataOld.Visible = false;
        else
            txtTerminalIdentityDataOld.Visible = true;
    }

    protected void gvTerminals_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("u"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = gvTerminals.DataKeys[index].Value.ToString();
            loadTerminalByID(rowID);
            ViewState["mode"] = "u";
            ViewState["rowid"] = rowID;

            firstrow.Visible = false;
            btnCorrectIdentity.Visible = true;
        }
        if (e.CommandName.Equals("h"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = gvTerminals.DataKeys[index].Value.ToString();
            ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
                    "window.open('../Reports/Default.aspx?rpt=108&p1=" + rowID + "','Report')", true);
        }
        else if (e.CommandName.Equals("d"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = gvTerminals.DataKeys[index].Value.ToString();

            ViewState["rowid"] = rowID;
            pnlCancel.Visible = true;
            //string error = "";

        }
        else if (e.CommandName.Equals("r"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = gvTerminals.DataKeys[index].Value.ToString();

            string error = "";
            bool saved = reset(rowID, ref error);
            if (saved)
            {
                lblError.Text = "reset ok";
                loadMerchantTerminals(Request.QueryString["clID"], Helper.gridSize(), 1);
                ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
                   "window.open('Comment.aspx?clID=" + Request.QueryString["clID"] + "&action=reset ','MerchantComment','status=1,width=700,height=250')", true);
            }
            else
            {
                if (Helper.OracleError(error))
                {
                    lblError.Text = "Reset Failed";
                    ExceptionUtility.LogException(9, "", "", "gvTerminals_RowCommand.Reset", error);
                }
                else
                    lblError.Text = error;
            }
        }
        else if (e.CommandName.Equals("asama"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = gvTerminals.DataKeys[index].Value.ToString();

            string error = "";
            bool saved = ApproveSama(rowID, ref error);
            if (saved)
            {
                lblError.Text = "Sama Approved";
                loadMerchantTerminals(Request.QueryString["clID"], Helper.gridSize(), 1);
                ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
                   "window.open('Comment.aspx?clID=" + Request.QueryString["clID"] + "&action=Sama Approved Terminal','MerchantComment','status=1,width=700,height=250')", true);
            }
            else
            {
                if (Helper.OracleError(error))
                {
                    lblError.Text = "Approve Failed";
                    ExceptionUtility.LogException(9, "", "", "gvTerminals_RowCommand.Approve", error);
                }
                else
                    lblError.Text = error;
            }
        }
        else if (e.CommandName.Equals("dsama"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = gvTerminals.DataKeys[index].Value.ToString();

            string error = "";
            bool saved = DeclineSama(rowID, ref error);
            if (saved)
            {
                lblError.Text = "Sama Declined";
                loadMerchantTerminals(Request.QueryString["clID"], Helper.gridSize(), 1);
                ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
                   "window.open('Comment.aspx?clID=" + Request.QueryString["clID"] + "&action=Sama Rejected Terminal','MerchantComment','status=1,width=700,height=250')", true);
            }
            else
            {
                if (Helper.OracleError(error))
                {
                    lblError.Text = "Decline Failed";
                    ExceptionUtility.LogException(9, "", "", "gvTerminals_RowCommand.Decline", error);
                }
                else
                    lblError.Text = error;
            }
        }
        else if (e.CommandName.Equals("asup"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = gvTerminals.DataKeys[index].Value.ToString();
            ViewState["rowid"] = rowID;
            pnlVendor.Visible = true;
        }
        else if (e.CommandName.Equals("dsup"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = gvTerminals.DataKeys[index].Value.ToString();

            string error = "";
            bool saved = DeclineSupport(rowID, ref error);
            if (saved)
            {
                lblError.Text = "Support Declined";
                loadMerchantTerminals(Request.QueryString["clID"], Helper.gridSize(), 1);
                ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
                   "window.open('Comment.aspx?clID=" + Request.QueryString["clID"] + "&action=Support Rejected Terminal','MerchantComment','status=1,width=700,height=250')", true);
            }
            else
            {
                if (Helper.OracleError(error))
                {
                    lblError.Text = "Approve Failed";
                    ExceptionUtility.LogException(9, "", "", "gvTerminals_RowCommand.Approve", error);
                }
                else
                    lblError.Text = error;
            }
        }
        else if (e.CommandName.Equals("v"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = gvTerminals.DataKeys[index].Value.ToString();
            loadTerminalCharges(rowID);
            ViewState["rowid"] = rowID;
        }
        else if (e.CommandName.Equals("t"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = gvTerminals.DataKeys[index].Value.ToString();
            ViewState["rowid"] = rowID;
            pnlTransfer.Visible = true;
        }
        else if (e.CommandName.Equals("dt"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = gvTerminals.DataKeys[index].Value.ToString();

            DataSet ds = Helper.getReportEvent(4); //disable terminal
            string action = ds.Tables[0].Rows[0]["event_desc_en"].ToString();
            string actionName = ds.Tables[0].Rows[0]["event_name"].ToString();
            string terminalID = gvTerminals.Rows[index].Cells[0].Text;
            action = action.Replace("{0}", terminalID);
            string windows = "";

            if (ds.Tables[0].Rows[0]["base24"].ToString() == "1")
            {
                windows += ";window.open('../Reports/Default.aspx?rpt=601&p1=" + lblClientNo.Text + "','Report1')";
            }
            if (ds.Tables[0].Rows[0]["visa"].ToString() == "1")
            {
                windows += ";window.open('../Reports/Default.aspx?rpt=603&p1=" + lblClientNo.Text + "','Report2')";
            }
            if (ds.Tables[0].Rows[0]["sama"].ToString() == "1")
            {
                windows += ";window.open('../Reports/Default.aspx?rpt=605&p1=" + lblClientNo.Text + "','Report3')";
            }
            if (windows.Length > 0)
            {
                windows = windows.TrimStart(';');

                Session["601"] = action;
                Session["603"] = action;
                Session["605_1"] = actionName;
                Session["605_2"] = action;
                ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window", windows, true);
            }
        }
        else if (e.CommandName.Equals("rt"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = gvTerminals.DataKeys[index].Value.ToString();
            DataSet ds1 = getCanceledterminals(lblClientNo.Text);
            if (ds1.Tables[0].Rows.Count > 0)
            {
                DataSet ds = Helper.getReportEvent(9); //replace terminal
                string action = ds.Tables[0].Rows[0]["event_desc_en"].ToString();
                string actionName = ds.Tables[0].Rows[0]["event_name"].ToString();
                string terminalID = ds1.Tables[0].Rows[0]["term_id"].ToString().Substring(0, 8);
                action = action.Replace("{0}", terminalID);
                string windows = "";

                if (ds.Tables[0].Rows[0]["base24"].ToString() == "1")
                {
                    windows += ";window.open('../Reports/Default.aspx?rpt=601&p1=" + lblClientNo.Text + "','Report1')";
                }
                if (ds.Tables[0].Rows[0]["visa"].ToString() == "1")
                {
                    windows += ";window.open('../Reports/Default.aspx?rpt=603&p1=" + lblClientNo.Text + "','Report2')";
                }
                if (ds.Tables[0].Rows[0]["sama"].ToString() == "1")
                {
                    windows += ";window.open('../Reports/Default.aspx?rpt=605&p1=" + lblClientNo.Text + "','Report3')";
                }
                if (windows.Length > 0)
                {
                    windows = windows.TrimStart(';');

                    Session["601"] = action;
                    Session["603"] = action;
                    Session["605_1"] = actionName;
                    Session["605_2"] = action;
                    ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window", windows, true);
                }
            }
            else
            {
                lblError.Text = "There are no canceled terminals attached to this retailer";
            }
        }
    }

    private DataSet getCanceledterminals(string clientNumber)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "MER_DEVICE_LINK_EDITOR.get_canceled_terminal";

        oracom.Parameters.Add("p_client_no", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;

        oracom.Parameters["p_client_no"].Value = clientNumber;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        oracon.Close();

        return ds;
    }

    protected void gvTerminals_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[15].Visible = false;
            e.Row.Cells[16].Visible = false;
        }
    }

    private bool ApproveSama(string index, ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "MER_DEVICE_LINK_EDITOR.approve_sama";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_dvl_code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_dvl_code"].Value = index;

        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    private bool reset(string index, ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "MER_DEVICE_LINK_EDITOR.reset_client_device_link";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_dvl_code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_dvl_code"].Value = index;

        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    private bool DeclineSama(string index, ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "MER_DEVICE_LINK_EDITOR.decline_sama";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_dvl_code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_dvl_code"].Value = index;

        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    private bool ApproveSupport(string index, ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "MER_DEVICE_LINK_EDITOR.approve_support";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_dvl_code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_dvl_code"].Value = index;

        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    private bool DeclineSupport(string index, ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "MER_DEVICE_LINK_EDITOR.decline_support";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_dvl_code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_dvl_code"].Value = index;

        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    private bool cancelTerminal(string index, ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "MER_DEVICE_LINK_EDITOR.Cancel_Client_Device_Link";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_dvl_code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_replace_term", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_dvl_code"].Value = index;
        oracom.Parameters["p_replace_term"].Value = txtNewTerminalID.Text;

        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    private void loadTerminalCharges(string ID)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "MER_DEVICE_LINK_EDITOR.Display_Term_Charges";

        oracom.Parameters.Add("p_dvl_code", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;

        oracom.Parameters["p_dvl_code"].Value = ID;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        oracon.Close();

        gvTerminalCharges.DataSource = ds.Tables[0];
        gvTerminalCharges.DataBind();
        pnlChanrges.Visible = true;
    }

    protected void btnCancelTerminalCharge_Click(object sender, EventArgs e)
    {
        pnlChanrges.Visible = false;
        ViewState["mode"] = null;
    }

    protected void btnSaveTerminalCharge_Click(object sender, EventArgs e)
    {
        string error = "";
        string clID = ViewState["rowid"].ToString();
        bool saved = addTerminalCharge(clID, ref error);
        if (saved)
        {
            lblError.Text = "Terminal Charge Saved";
            ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
                   "window.open('Comment.aspx?clID=" + Request.QueryString["clID"] + "&action=Terminal Charge Added','MerchantComment','status=1,width=700,height=250')", true);
        }
        else
        {
            if (Helper.OracleError(error))
            {
                lblError.Text = "An Error Occured!";
                ExceptionUtility.LogException(9, "", "", "btnSaveTerminalCharge_Click", error);
            }
            else
                lblError.Text = error;
        }
        loadTerminalCharges(clID);
    }

    private bool addTerminalCharge(string terID, ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "MER_DEVICE_LINK_EDITOR.Add_Term_Charge";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_dvl_code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_chg_amt", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_chg_reason", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.Parameters["p_dvl_code"].Value = terID;

        oracom.Parameters["p_chg_amt"].Value = txtChargeAmount.Text;
        oracom.Parameters["p_chg_reason"].Value = ddlReason.SelectedValue;

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    protected void btnCancelTransfer_Click(object sender, EventArgs e)
    {
        pnlTransfer.Visible = false;
        ViewState["mode"] = null;
    }

    protected void btnSaveTransfer_Click(object sender, EventArgs e)
    {
        string error = "";
        string clID = ViewState["rowid"].ToString();
        bool saved = transferTerminal(clID, ref error);
        if (saved)
        {
            lblError.Text = "Terminal Transfer is submitted to Supervisor for approval.";
            ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
                   "window.open('Comment.aspx?clID=" + Request.QueryString["clID"] + "&action=Transfering Terminal','MerchantComment','status=1,width=700,height=250')", true);
        }
        else
        {
            if (Helper.OracleError(error))
            {
                lblError.Text = "An Error Occured!";
                ExceptionUtility.LogException(9, "", "", "btnSaveTransfer_Click", error);
            }
            else
                lblError.Text = error;
        }
        pnlTransfer.Visible = false;
    }

    private bool transferTerminal(string terID, ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "MER_DEVICE_LINK_EDITOR.Transfer_Client_Device_Link";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_dvl_code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_new_retailed_id", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.Parameters["p_dvl_code"].Value = terID;

        oracom.Parameters["p_new_retailed_id"].Value = txtNewClientNo.Text;

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    protected void btnCancelReplace_Click(object sender, EventArgs e)
    {
        pnlCancel.Visible = false;
        ViewState["mode"] = null;
    }

    protected void btnSaveReplace_Click(object sender, EventArgs e)
    {
        string error = "";
        string clID = ViewState["rowid"].ToString();
        bool saved = cancelTerminal(clID, ref error);
        if (saved)
        {
            lblError.Text = "Terminal Canceled";
            loadMerchantTerminals(Request.QueryString["clID"], Helper.gridSize(), 1);
            ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
               "window.open('Comment.aspx?clID=" + Request.QueryString["clID"] + "&action=Cancel Terminal','MerchantComment','status=1,width=700,height=250')", true);
        }
        else
        {
            if (Helper.OracleError(error))
            {
                lblError.Text = "An Error Occured!";
                ExceptionUtility.LogException(9, "", "", "btnSaveReplace_Click", error);
            }
            else
                lblError.Text = error;
        }
        pnlCancel.Visible = false;
    }

    protected void btnSaveResponse_Click(object sender, EventArgs e)
    {
        string error = "", ID = "";
        ID = ViewState["rowid"].ToString();
        bool saved = UpdateVendorResponse(ID, ref error);
        if (saved)
        {
            lblError.Text = "Data saved";
            loadMerchantTerminals(Request.QueryString["clID"], Helper.gridSize(), 1);
            ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
               "window.open('Comment.aspx?clID=" + Request.QueryString["clID"] + "&action=Support Approved Terminal','MerchantComment','status=1,width=700,height=250')", true);
        }
        else
        {
            if (Helper.OracleError(error))
            {
                lblError.Text = "An Error Occured!";
                ExceptionUtility.LogException(9, "", "", "btnSaveResponse_Click", error);
            }
            else
                lblError.Text = error;
        }
        pnlVendor.Visible = false;
    }

    protected void btnCancelResponse_Click(object sender, EventArgs e)
    {
        pnlVendor.Visible = false;
    }

    private bool UpdateVendorResponse(string ID, ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "DEVICE_VENDOR_NOTIFIER.Update_vendor_response";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_dvl_code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_date", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_time", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.Parameters["p_dvl_code"].Value = ID;
        oracom.Parameters["p_date"].Value = dateVendorResponse.date;
        oracom.Parameters["p_time"].Value = txtTimeResponse.Text;

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    protected void gvTerminals_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        // searching through the rows
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            int rec = int.Parse(DataBinder.Eval(e.Row.DataItem, "rec_flag").ToString());
            string status = DataBinder.Eval(e.Row.DataItem, "status").ToString();
            if (rec == 1 && status == "001")
                e.Row.BackColor = Color.Tan; // is a "new" row
        }
    }

    protected void btnCorrectIdentity_Click(object sender, EventArgs e)
    {
        if (txtTerminalIdentityData.Text.Length > 0 && txtTerminalIdentityData.Text.Length == 8)
        {
            string error = "", ID = Request.QueryString["clID"];
            bool saved = CorrectIdentity(ref error);
            if (saved)
            {
                lblError.Text = "Correct Identity Status: " + error;
                ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
                   "window.open('Comment.aspx?clID=" + ID + "&action=Update Merchant (Correct Identity)','MerchantComment','status=1,width=700,height=250')", true);
            }
            else
            {
                if (Helper.OracleError(error))
                {
                    lblError.Text = "An Error Occured!";
                    ExceptionUtility.LogException(9, "", "", "btnCorrectIdentity_Click", error);
                }
                else
                    lblError.Text = error;
            }
        }
        else
            lblError.Text = "Terminal Identity Data must be at least 8 digits";
    }

    private bool CorrectIdentity(ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "MER_DEVICE_LINK_EDITOR.CORRECT_TERMINAL_IDENTITY";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_dvl_code", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_terminal_identity", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.Parameters["p_dvl_code"].Value = ViewState["rowid"].ToString();

        oracom.Parameters["p_terminal_identity"].Value = txtTerminalIdentityData.Text;

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    protected void ddlTerminals_SelectedIndexChanged(object sender, EventArgs e)
    {
        string termID = ddlTerminals.SelectedValue;
        string cnt;

        if (termID != "------ Select ------")  // MM Phase 2
        {

            DataSet ds = loadResult(termID);
            lblError.Text = "";
            if (ds.Tables[0].Rows.Count > 0)

                txtSRNumber.Text = ds.Tables[0].Rows[0]["serial_number"].ToString();
                
            //  lblInstall.Text = ds.Tables[0].Rows[0]["Installed_Date"].ToString();  // MM Phase 2
                dtInstall.date = ds.Tables[0].Rows[0]["Installed_Date"].ToString();

                cnt = ds.Tables[0].Rows[0]["Installed_Date_Cnt"].ToString().Trim();

                if ((!cnt.Equals("0")) && (dtInstall.date.Equals(DateTime.Now.ToString("yyMMdd"))))
                {
                    dtInstall.date = getDayofMonth(DateTime.Now.Day);
                    lblError.ForeColor = System.Drawing.Color.DarkBlue;
                    lblError.BackColor = System.Drawing.Color.Yellow;

                    lblError.Text = "Installation Date was empty for the previous Installed terminal " + termID ;
                }
                else
                {
                    lblError.Text = "";
                }

            if (txtSRNumber.Text.Trim().Length == 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                    txtSRNumber.Text = ds.Tables[0].Rows[0]["trms"].ToString();
            }
            dtReInstall.date = ds.Tables[0].Rows[0]["ReInstalled_Date"].ToString();
        }  // MM Phase 2
        else
        {
            lblError.Text = "";
            dtInstall.date = getDayofMonth(DateTime.Now.Day);
            dateSamaConfirm.date = "";
            dtReInstall.date = "";
            txtTerminalLocation.Text = "";
            txtPrimPhoneNo.Text = "";
            txtSRNumber.Text = "";
             
            txtTerminalIdentityData.Text = "";
            txtCostOfPOS.Enabled = true;
            txtCostOfPOS.Text = "0";
            ddlTerminalBusinessType.SelectedIndex = 0;
            ddlTerminalProvider.SelectedIndex = 0;
            ddlTerminalProvider.Enabled = false;

        }
    }
    private DataSet loadResult(string termID)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "DEVICE_REPOSITORY_EDITOR.Get_Device_List";


        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_merchant_no", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_client_no", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_terminal_status", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_terminal_id", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_vendor_code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_term_type", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_page_size", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_page_num", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_total_pages", OracleType.Number).Direction = ParameterDirection.Output;

        oracom.Parameters["p_vendor_code"].Value = OracleNumber.Null;
        oracom.Parameters["p_term_type"].Value = OracleNumber.Null;

        oracom.Parameters["p_merchant_no"].Value = OracleNumber.Null;
        oracom.Parameters["p_client_no"].Value = OracleNumber.Null;
        oracom.Parameters["p_terminal_status"].Value = OracleString.Null;
        oracom.Parameters["p_terminal_id"].Value = termID;
        oracom.Parameters["p_page_size"].Value = 10;
        oracom.Parameters["p_page_num"].Value = 1;
        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        int nop = int.Parse(oracom.Parameters["p_total_pages"].Value.ToString());
        oracon.Close();

        return ds;
    }

    //***************************************   Submit   ********************************************\\

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string error = "";
        clLevel = ddlClientLevel.SelectedValue;
        string clID = Request.QueryString["clID"];
        bool saved = submit(clID, ref error);
        if (saved)
        {
            loadMerchantRegStatus(clID);
            lblError.Text = "Merchant Submitted";
            ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
                   "window.open('Comment.aspx?clID=" + clID + "&action=Submit Merchant','MerchantComment','status=1,width=700,height=250')", true);
        }
        else
        {
            if (Helper.OracleError(error))
            {
                lblError.Text = "An Error Occured!";
                ExceptionUtility.LogException(9, "", "", "btnSubmit_Click", error);
            }
            else
                lblError.Text = error;
        }
    }

    private bool submit(string clientNo, ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "merchant_reg.Validate_Mer_Submit";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_client_number", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.Parameters["p_client_number"].Value = clientNo;

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    private string getDayofMonth(int pDay)
    {
        string day = "", month = "", year = "";
        if (pDay < 10)
            day = "0" + pDay.ToString();
        else
            day = pDay.ToString();
        if (DateTime.Now.Month < 10)
            month = "0" + DateTime.Now.Month.ToString();
        else
            month = DateTime.Now.Month.ToString();
        year = DateTime.Now.Year.ToString();
        string date = day + "-" + month + "-" + year;
        return date;
    }

    protected void btnDuplicate_Click(object sender, EventArgs e)
    {
        clLevel = ddlClientLevel.SelectedValue;
        pnlDuplicate.Visible = true;
    }

    protected void btnSaveDuplicate_Click(object sender, EventArgs e)
    {
        if (txtNewAcctNo.Text.Length > 0)
        {
            string error = "", newCID = "";
            string clID = Request.QueryString["clID"];
            bool saved = duplicate(clID, ref newCID, ref error);
            if (saved)
            {
                lblError.Text = "Merchant Submitted";
                Response.Redirect("updateMerchant.aspx?clID=" + newCID);
            }
            else
            {
                if (Helper.OracleError(error))
                {
                    lblError.Text = "An Error Occured!";
                    ExceptionUtility.LogException(9, "", "", "btnSaveDuplicate_Click", error);
                }
                else
                    lblError.Text = error;
            }
        }
        else
            lblError.Text = "You have to enter the new Account No";
    }

    protected void btnCancelDuplicate_Click(object sender, EventArgs e)
    {
        pnlDuplicate.Visible = false;
    }

    private bool duplicate(string clientNo, ref string cID, ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "merchant_reg.Duplicate_Merchant";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_client_number", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_new_acct_no", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_new_client_no", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.Parameters["p_client_number"].Value = clientNo;
        oracom.Parameters["p_new_acct_no"].Value = txtNewAcctNo.Text;

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        cID = oracom.Parameters["p_new_client_no"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    protected void btnHistory_Click(object sender, EventArgs e)
    {
        clLevel = ddlClientLevel.SelectedValue;
        string clID = Request.QueryString["clID"];
        ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
                    "window.open('../Reports/Default.aspx?rpt=105&p1=" + clID + "','Report')", true);
        //ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",


        //            "window.open('../Reports/report.aspx?cid=" + clID + "','Report')", true);
    }
    protected void btnAccHistory_Click(object sender, EventArgs e)
    {
        clLevel = ddlClientLevel.SelectedValue;
        string clID = Request.QueryString["clID"];
        ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
                    "window.open('../Reports/Default.aspx?rpt=109&p1=" + clID + "','Report')", true);
    }

    protected void gvTerminals_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    protected void btnAddTerminalBulk_Click(object sender, EventArgs e)
    {
        btnCancelTerminal_Click(sender, e);
        PnlTerminalBulk.Visible = true;
        ddlVendor.SelectedIndex = 0;
        ddlTerminalType.Enabled = false;
        ddlServiceType.SelectedIndex = 0;
        ddlStatusBulk.SelectedIndex = 0;
        txtSRNumberBulk.Text = "";
        txtNoTerminals.Text = "";
    }
    protected void btnSaveTerminalBulk_Click(object sender, EventArgs e)
    {
        if (ddlVendor.SelectedIndex == 0)
            lblError.Text = "Please select vendor";
        else if (txtSRNumberBulk.Text.Length == 0)
            lblError.Text = "Please enter the SR Number";
        else if (txtNoTerminals.Text.Length == 0)
            lblError.Text = "Please enter the No.of Terminals";
        else
        {
            string error = "";
            string clID = Request.QueryString["clID"];
            bool saved = addTerminalBulk(clID, ref error);
            if (saved)
            {
                lblError.Text = "Terminal Bulk data Saved";

            }
            else
            {
                if (Helper.OracleError(error))
                {
                    lblError.Text = "An Error Occured!";
                    ExceptionUtility.LogException(9, "", "", "btnSaveTerminalBulk_Click", error);
                }
                else
                    lblError.Text = error;
            }
            loadMerchantTerminals(Request.QueryString["clID"], Helper.gridSize(), 1);
            PnlTerminalBulk.Visible = false;
        }
    }
    protected void btnCancelTerminalBulk_Click(object sender, EventArgs e)
    {
        PnlTerminalBulk.Visible = false;
    }
    //protected void txtStreet_TextChanged(object sender, EventArgs e)
    //{
    //    txtEngAdd1.Text = txtStreet.Text;
    //}
    protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
    {
        ddlAddressCity.SelectedValue = ddlCity.SelectedValue;
    }


    //*********************** Change Account and handle black list *******************************//

    protected void btnChangeAccount_Click(object sender, EventArgs e)
    {
        txtAccNoGeneral.ReadOnly = false;
        txtfeemerchantaccno.ReadOnly = false;
        btnChangeAccount.Visible = false;
        btnVerifyAcc.Visible = true;
        btnCancelAcc.Visible = true;
        btnAccSer.Visible = false;
        btnSave.Enabled = false;
        ViewState["acctchng"] = txtAccNoGeneral.Text;
    }
    protected void btnCancelAcc_Click(object sender, EventArgs e)
    {
        txtAccNoGeneral.ReadOnly = true;
        txtfeemerchantaccno.ReadOnly = true;
        btnChangeAccount.Visible = true;
        btnVerifyAcc.Visible = false;
        btnCancelAcc.Visible = false;
        btnAccSer.Visible = true;
        btnSave.Enabled = true;
        txtAccNoGeneral.Text = ViewState["acctchng"].ToString();
    }
    protected void btnVerifyAcc_Click(object sender, EventArgs e)
    {
        txtAccNoGeneral.Text = txtAccNoGeneral.Text.Replace(" ", "");
        txtfeemerchantaccno.Text = txtfeemerchantaccno.Text.Replace(" ", "");
        if (checkCCR())
        {
            lblError.Text = "Account Verification Done...";
            txtAccNoGeneral.ReadOnly = true;
            txtfeemerchantaccno.ReadOnly = true;
            btnChangeAccount.Visible = true;
            btnVerifyAcc.Visible = false;
            btnCancelAcc.Visible = false;
            btnAccSer.Visible = true;
            btnSave.Enabled = true;
            btnSave.Enabled = true;
        }
        else
        {
            lblError.Text = ViewState["MESSAGE"].ToString();
        }
    }

    private bool isBlackList(string CRN, string account)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "MERCHANT_BLACKLIST_EDITOR.Is_BlackListed";

        oracom.Parameters.Add("p_mer_crn", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_mer_Acct", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_mer_crn"].Value = CRN;
        oracom.Parameters["p_mer_Acct"].Value = account;
        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res"].Value.ToString();
        //error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "Y")
            return true;
        else
            return false;
    }

    private bool checkCCR()
    {
        //string Directory = ConfigurationSettings.AppSettings["MWCertificate"];
        //string XmlMessage = "";
        //string XmlResponse = "";
        //string TransportVia = "I";
        //string TransportMethod = "Synch";
        //string LangItem = "1";

        //string CCRUser = ConfigurationSettings.AppSettings["CCRUser"];
        //string CCRSession = ConfigurationSettings.AppSettings["CCRSession"];
        //string CCRChannel = ConfigurationSettings.AppSettings["CCRChannel"];
        //string CCRTerminal = ConfigurationSettings.AppSettings["CCRTerminal"];

        //NCBEAI.Adapters.Transport.Message Request = new Message(Directory);

        ////XmlMessage = "<AccID>" + txtAccNo.Text + "</AccID>";
        //XmlMessage = "<GetPartyReq tcod=\"GetPartyInformation\"><MSGHDR><MsgDateTime>25/12/2013</MsgDateTime><SessionId>" + CCRSession + "</SessionId><ChannelId>" + CCRChannel + "</ChannelId><FunctionId>0400</FunctionId><UserId>" + CCRUser + "</UserId><Lang>AR</Lang><TerminalId>" + CCRTerminal + "</TerminalId><Reserved1>CCR044C</Reserved1></MSGHDR><MSGBDY><CTRL><InquiryMode>S</InquiryMode><RMNotes>N</RMNotes><RelationInfo>N</RelationInfo><StatisticalInfo>N</StatisticalInfo><RiskRatingInf>N</RiskRatingInf><LimitsInfo>N</LimitsInfo><SegmentHistoryInfo>N</SegmentHistoryInfo><ProgramDetailsInfo>N</ProgramDetailsInfo><PtyPrdExpInfo>N</PtyPrdExpInfo><PtyInvAsstCurrInfo>N</PtyInvAsstCurrInfo><RelationBasicInfo>Y</RelationBasicInfo><RelationTypes /><PtyNotificationInfo /><PtyInvInfo /><FltrPtyAcctAddr>Y</FltrPtyAcctAddr><FltrPtyCont>Y</FltrPtyCont><FltrPtyIds>Y</FltrPtyIds><ReverseRelationFlg>N</ReverseRelationFlg><FltrNCBCCont>Y</FltrNCBCCont></CTRL><PTY><EcnId></EcnId><PartyId /></PTY><ACCT><AcctNo>" + txtAccNoGeneral.Text + "</AcctNo></ACCT><PTYSYSLNK><SysCustUsrNo /></PTYSYSLNK></MSGBDY></GetPartyReq>";
        //Request.TCod = "";
        //int finalError = Request.PrepareMessage(XmlMessage, LangItem, Directory, TransportVia, TransportMethod, out XmlResponse);

        //if (XmlResponse.Contains("OK"))
        //{
        //    XmlDocument doc = new XmlDocument();
        //    doc.LoadXml(XmlResponse);
        //    XmlNode node = doc.SelectSingleNode("/OK/MSGBDY/BASIC/EcnId");
        //    if (node == null)
        //    {
        //        ViewState["MESSAGE"] = "There is no customer with the entered account";
        //        return false;
        //    }
        //    string ECN = node.InnerText;

        //    node = doc.SelectSingleNode("/OK/MSGBDY/BASIC/IdNumber");
        //    string crn = node.InnerText;
        //    //call blacklist
        //    if (isBlackList(crn, txtAccNoGeneral.Text))
        //    {
        //        ViewState["MESSAGE"] = "This merchant is black listed";
        //        return false;
        //    }
        //    return true;
        //}
        //else if (XmlResponse.Contains("ERR"))
        //{
        //    XmlDocument doc = new XmlDocument();
        //    doc.LoadXml(XmlResponse);
        //    XmlNode node = doc.SelectSingleNode("/ERR");
        //    string temp = node.Attributes["Desc"].InnerText;
        //    string temp1 = node.Attributes["NativeErr"].InnerText;
        //    string temp2 = node.Attributes["NativeDesc"].InnerText;

        //    ViewState["MESSAGE"] = temp + " " + temp1 + " " + temp2;
        //    return false;
        //}

        return true;
    }


    protected void btnAutoPayment_Click(object sender, EventArgs e)
    {
        string error = "";
        clLevel = ddlClientLevel.SelectedValue;
        bool saved = updateAutoPayment(ref error);
        if (saved)
            lblError.Text = "AutoPayment flag updated.";
        else
        {
            if (Helper.OracleError(error))
            {
                lblError.Text = "An Error Occured!";
                ExceptionUtility.LogException(9, "", "", "btnAutoPayment_Click", error);
            }
            else
                lblError.Text = error;
        }
    }

    private bool updateAutoPayment(ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "merchant_reg.update_autopayment";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_mt_code", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_value", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_mt_code"].Value = Request.QueryString["clID"];

        //if (chkAutoPayment.Checked)
        //    oracom.Parameters["p_value"].Value = "1";
        //else
        oracom.Parameters["p_value"].Value = "0";

        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }
    protected void btnUpdateSrvType_Click(object sender, EventArgs e)
    {
        string error = "", ID = Request.QueryString["clID"];
        bool saved = updateSrvType(ref error);
        if (saved)
        {
            lblError.Text = "Update Service Type Status: " + error;
            ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
               "window.open('Comment.aspx?clID=" + ID + "&action=Update Merchant (Update Service Type)','MerchantComment','status=1,width=700,height=250')", true);
        }
        else
        {
            if (Helper.OracleError(error))
            {
                lblError.Text = "An Error Occured!";
                ExceptionUtility.LogException(9, "", "", "btnUpdateSrvType_Click", error);
            }
            else
                lblError.Text = error;
        }
    }

    private bool updateSrvType(ref string error)
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "MER_DEVICE_LINK_EDITOR.UPDATE_SERVICE_TYPE";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_dvl_code", OracleType.Number).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_srv_type", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.Parameters["p_dvl_code"].Value = ViewState["rowid"].ToString();

        oracom.Parameters["p_srv_type"].Value = ddlSrvType.SelectedValue;

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    protected void ddlBranch_SelectedIndexChanged(object sender, EventArgs e)
    {
        loadBranch(2);
    }
    protected void ddlBranchAcc_SelectedIndexChanged(object sender, EventArgs e)
    {
        loadBranchAcc(2);
    }


    protected void btnRetailerCancel_Click(object sender, EventArgs e)
    {
        btnRetailer.Visible = true;
        btnRetailerOk.Visible = false;
        btnRetailerCancel.Visible = false;
        ddlRetailerRegion.Visible = false;
    }
    protected void btnRetailerOk_Click(object sender, EventArgs e)
    {
        string retailer = txtRetailerID.Text;
        string newRetailer = retailer.Substring(0, 2) + ddlRetailerRegion.SelectedValue + retailer.Substring(3);
        string error = "";
        bool saved = correctRetailer(newRetailer, ref error);
        if (saved)
        {
            lblError.Text = "Retailer ID Changed";
            btnRetailer.Visible = true;
            btnRetailerOk.Visible = false;
            btnRetailerCancel.Visible = false;
            ddlRetailerRegion.Visible = false;
            txtRetailerID.Text = newRetailer;
            ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window",
               "window.open('Comment.aspx?clID=" + ID + "&action=Update Merchant (correct Retailer)','MerchantComment','status=1,width=700,height=250')", true);
        }
        else
        {
            if (Helper.OracleError(error))
            {
                lblError.Text = "An Error Occured!";
                ExceptionUtility.LogException(9, "", "", "btnRetailerOk_Click", error);
            }
            else
                lblError.Text = error;
        }
    }
    protected void ddlTerminalBusinessType_SelectedIndexChanged(object sender, EventArgs e)
    {

        if (ddlTerminalBusinessType.SelectedItem.Text.Equals("Aggregator"))
        {
            txtCostOfPOS.Text = "0";
            txtCostOfPOS.Enabled = false;
            ddlTerminalProvider.Enabled = true;
            ddlTerminalProvider.SelectedIndex = 1;
           
        }
        else
        {
            txtCostOfPOS.Enabled = true;
            ddlTerminalProvider.SelectedIndex = 0;
            ddlTerminalProvider.Enabled = false;
            
        }

    }
    private void LoadTTerminalBusinessType()
    {


        ddlTerminalBusinessType.DataSource = Helper.GetLookup("lkp_terminal_business_type"); ;
        ddlTerminalBusinessType.DataBind();
        ListItem li = new ListItem();
        li.Text = "------ Select ------";
        li.Value = "0";
        ddlTerminalBusinessType.Items.Insert(0, li);
    }

    private void LoadTerminalProvider()
    {


        ddlTerminalProvider.DataSource = Helper.GetLookup("LKP_Terminal_Provider"); ;
        ddlTerminalProvider.DataBind();
        ListItem li = new ListItem();
        li.Text = "------ Select ------";
        li.Value = "0";
        ddlTerminalProvider.Items.Insert(0,li);
    }


    protected void bttnUpdateFeeByMCC_Click(object sender, EventArgs e)
    {


        if (ddlServices.SelectedValue == "001")
        {
            SetFeeByBusinsessClass(ddlBusinessClass.SelectedValue);
        }
    }
}
