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 UpdateMerchantECOM : System.Web.UI.Page
{
    protected string clLevel;
    protected void Page_Load(object sender, EventArgs e)
    {
        
        
        if (!IsPostBack)
        {
            loadVAT();// VAT_CR
            loadLanguage();
            loadBusinessClass();
            loadCity();
            loadProductType();
            loadsettlementMethod();
            loadpostingMethod();
            loadBusinessUnit();
            loadServices();
            loadCurrancy();
            loadIncomeRange();
            loadRelationOfficer();
            loadBranch(1);
            loadBranchAcc(1);
            
            string clID         = Request.QueryString["clID"];

            lblClientNo.Text = clID;
            loadMerchant(clID);
            loadMerchantServices(clID, Helper.gridSize(), 1);
            // Add Ecom Terminals 
            loadeComMerchantTerminals(clID, Helper.gridSize(), 1);
            
            loadBUAcc(ddlBusinessUnit.SelectedValue);
              
            if (isBlackList("", txtAccNoGeneral.Text))
            {
                btnSave.Enabled = false;
                btnAccSer.Enabled = false;
                btnChangeAccount.Enabled = false;
                //btnCorrectInfo.Enabled = false;
                btnAddServices.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()");
        }
    }

    
    //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 = "Ecom_Merchant_Reg.Update_Merchant_Info";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_registration_date", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_client_no", 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_merchant_no", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_client_level", OracleType.VarChar).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_business_class", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_relationship_officer", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_business_unit", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_branch_cd", OracleType.VarChar).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;
        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_code", 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;
        oracom.Parameters.Add("p_mobile_3", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_email_address", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_email_2", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_email_3", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_posting_method", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_serial_number", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_purchase_date", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_model_number", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_manufacturer", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_software_version", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_terminal_id", 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.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_sr_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_no"].Value = Request.QueryString["clID"];

        oracom.Parameters["p_registration_date"].Value = dateRegDate.date;
        oracom.Parameters["p_acct_number"].Value = txtAccNoGeneral.Text;
        
        oracom.Parameters["p_merchant_no"].Value = OracleNumber.Null;
        oracom.Parameters["p_client_level"].Value = OracleString.Null;
        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_business_class"].Value = ddlBusinessClass.SelectedValue;
        oracom.Parameters["p_relationship_officer"].Value = ddlRelationshipOfficer.SelectedValue;
        oracom.Parameters["p_business_unit"].Value = ddlBusinessUnit.SelectedValue;
        oracom.Parameters["p_branch_cd"].Value = ddlBranch.SelectedValue;
        oracom.Parameters["p_record_type"].Value = OracleString.Null;
        oracom.Parameters["p_effective_date"].Value = dateRegDate.date;
        oracom.Parameters["p_address_category"].Value = OracleString.Null;
        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 = OracleString.Null;
        oracom.Parameters["p_arabic_address2"].Value = OracleString.Null;
        oracom.Parameters["p_arabic_address3"].Value = OracleString.Null;
        oracom.Parameters["p_post_code"].Value = txtPostCode.Text;
        oracom.Parameters["p_city_code"].Value = ddlAddressCity.SelectedValue;
        oracom.Parameters["p_country"].Value = ddlAddressCountry.SelectedValue;
        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;
        oracom.Parameters["p_mobile_3"].Value = txtMobile3.Text;
        oracom.Parameters["p_email_address"].Value = txtEmail.Text;
        oracom.Parameters["p_email_2"].Value = txtEmail2.Text;
        oracom.Parameters["p_email_3"].Value = txtEmail3.Text;
        oracom.Parameters["p_posting_method"].Value = ddlPostingMethod.SelectedValue;
        oracom.Parameters["p_serial_number"].Value = OracleString.Null;
        oracom.Parameters["p_purchase_date"].Value = OracleString.Null;
        oracom.Parameters["p_model_number"].Value = OracleString.Null;
        oracom.Parameters["p_manufacturer"].Value = OracleString.Null;
        oracom.Parameters["p_software_version"].Value = OracleString.Null;
        oracom.Parameters["p_terminal_id"].Value = txtTerminalID.Text;
        oracom.Parameters["p_terminal_location"].Value = txtTerminalLocation.Text;
        oracom.Parameters["p_primary_host_access"].Value = OracleString.Null;
        oracom.Parameters["p_alternative_host_access"].Value = OracleString.Null;
        oracom.Parameters["p_primary_phone_number"].Value = OracleString.Null;
        oracom.Parameters["p_srv_type"].Value = OracleNumber.Null;
        oracom.Parameters["p_sr_number"].Value = OracleString.Null;

        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 = "Ecom_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
        lblRetailerID.Text = ds.Tables[0].Rows[0]["retailer_id"].ToString();
        ddlRelationshipOfficer.Enabled = 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();
        //ddlSettlMethod.SelectedValue = ds.Tables[0].Rows[0]["settlement_method"].ToString();
        //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();
        
        //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();

        //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.SelectedValue == ddlRelationshipOfficer.SelectedValue)
            ddlRelationshipOfficerOld.Visible = false;
        else
            ddlRelationshipOfficerOld.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)
        //    txtRetailerIDOld.Visible = false;
        //else
        //    txtRetailerIDOld.Visible = true;

        //string autoPayment = ds.Tables[0].Rows[0]["auto_payment"].ToString(); // Check this later !important
        //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;
        //}
        loadAddress(ds);
    }

    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 loadeComMerchantTerminals(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 = "Ecom_Merchant_Reg.Get_List_eComClient_Device";

        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_ListDevice", 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());
        if (nop == -1 && ds.Tables[0].Rows.Count > 0)
            nop = int.Parse(Math.Ceiling((double.Parse(ds.Tables[0].Rows[0]["ROW_COUNT"].ToString()) / pageSize)).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 gvTerminals_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void gvTerminals_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        // searching through the rows
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string status = DataBinder.Eval(e.Row.DataItem, "status").ToString();
            if (status == "007")
                e.Row.BackColor = Color.SkyBlue; // is a modified
        }
    }
    protected void gvTerminals_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.DataRow)
        {

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

            ViewState["rowid"] = rowID;
            string error = "";
            bool saved = disableTerminal(rowID, ref error);
            if (saved)
            {
                lblError.Text = "Terminal Cancelled";
            }
            else
            {
                if (Helper.OracleError(error))
                {
                    lblError.Text = "Disabled Failed";
                    ExceptionUtility.LogException(9, "", "", "GridView1_RowCommand.Delete", error);
                }
                else
                    lblError.Text = error;
            }
            loadeComMerchantTerminals(Request.QueryString["clID"], Helper.gridSize(), 1);
            ViewState["mode"] = null;
            ViewState["rowid"] = null;
            pnlTerminals.Visible = false;
        }
    }

    private bool disableTerminal(string DeviceID, 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 = "Ecom_Merchant_Reg.Disable_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 = DeviceID;

        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 btnAddTerminal_Click(object sender, EventArgs e)
    {
        pnlTerminals.Visible = true;       
        ViewState["mode"] = "a";
    }

    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;
            }
            else
            {
                string mode = ViewState["mode"].ToString();
                string error = "";
                if (mode.Equals("a"))
                {
                        string clID = Request.QueryString["clID"];
                        bool saved = addTerminal(clID, ref error);
                        if (saved)
                        {
                            lblError.Text = "Terminal data Saved";
                            ExceptionUtility.LogException(0, "Ecom_Merchant_Reg.Add_eComClient_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;
                        }
                }
                loadeComMerchantTerminals(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 = "Ecom_Merchant_Reg.Add_eComClient_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_terminal_location", 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_terminal_id"].Value = txtTerminalID.Text;

        oracom.Parameters["p_terminal_location"].Value = txtTerminalLocation.Text;

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        ID = oracom.Parameters["p_client_no"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }
    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {

        loadeComMerchantTerminals(Request.QueryString["clID"], Helper.gridSize(), int.Parse(ddlPages.SelectedValue));
    }
    protected void ddlBusinessUnit_SelectedIndexChanged(object sender, EventArgs e)
    {
        //clLevel = ddlClientLevel.SelectedValue.ToString();
        loadBUAcc(ddlBusinessUnit.SelectedValue);
    }
    
    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();

    }

    private void loadAddress(DataSet ds)
    {
        //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();
        
        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();

        //txtTerminalID.Text = ds.Tables[0].Rows[0]["Term_Id"].ToString();
        //txtTerminalLocation.Text = ds.Tables[0].Rows[0]["Terminal_Location"].ToString();

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

       



        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;

        //txtTerminalIDOld.Text = ds.Tables[0].Rows[0]["Term_Id_old"].ToString();
        //if (txtTerminalIDOld.Text == txtTerminalID.Text)
        //    txtTerminalIDOld.Visible = false;
        //else
        //    txtTerminalIDOld.Visible = true;

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

    }



    //**************************************************************************************************************************************************************\\

    

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

   

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

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

        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 = "002";
        // ddlPostingMethod.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 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();


        ddlRelationshipOfficer.Items.Insert(0, new ListItem("------------- Select-------------", "0"));

        oracon.Close();
    }

   

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

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

        //hide the old version
        ddlCurrancyOld.Visible = false;
        txtPercentMOld.Visible = false;
        txtPercentBOld.Visible = false;
        txtAccNoOld.Visible = false;
        txtBrAccNoOld.Visible = false;
        chkKeyEntryOld.Visible = false;

        if (ddlServices.SelectedValue == "001")
        {
            getFeesMax();
        }
        lblPercent.Text = txtPercentM.Text;
    }

    protected void ddlServices_SelectedIndexChanged(object sender, EventArgs e)
    {
        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;
            if (ViewState["mode"].ToString().Equals("a"))
                getFeesMax();
        }
        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;
        }

        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")
            {
                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 (txtPICapacity.Text.Trim().Length == 0)
                {
                    lblError.Text = "Please enter the 'Fee Capacity' field";
                    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)
        {
            lblError.Text = ex.Message;
        }
    }

    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_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 = 0; // Only for POS
        oracom.Parameters["p_bank_fee_percent_lower"].Value = 0;// Only for POS
        //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;
        oracom.Parameters["p_bank_pi_cap"].Value = 0;// Always 0(mean not used) Disable;

        //
        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_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_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 = 0; // Only for POS
        oracom.Parameters["p_bank_fee_percent_lower"].Value = 0;// Only for POS
        //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;
        oracom.Parameters["p_bank_pi_cap"].Value = 0;// Always 0(mean not used) Disable;

        //

        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.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_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 = 0; // Only for POS
        oracom.Parameters["p_bank_fee_percent_lower"].Value = 0;// Only for POS
        //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;
        oracom.Parameters["p_bank_pi_cap"].Value = 0;// Always 0(mean not used) Disable in Ecom;


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

        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 = "";
        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();

        //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();
        // 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();
        }
        catch (Exception ex) {
            lblError.Text = ex.Message;
        }
        
        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();
        txtInterAccNo.Text = ds.Tables[0].Rows[0]["inter_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;

        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;

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

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

    protected void gvServices_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("u"))
        {
            try
            {
                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;
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }
        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()
    {
        string DBConnection = Helper.dbConnection();

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

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

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "Ecom_Merchant_Reg.get_Fees_Max";

        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 = "0";
        

        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;

    }
      
    //***************************************   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)
        {
            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 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 txtStreet_TextChanged(object sender, EventArgs e)
    //{
    //    txtEngAdd1.Text = txtStreet.Text;
    //}
    


    //*********************** Change Account and handle black list *******************************//

    protected void btnChangeAccount_Click(object sender, EventArgs e)
    {
        txtAccNoGeneral.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;
        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(" ", "");
        if (checkCCR())
        {
            lblError.Text = "Account Verification Done...";
            txtAccNoGeneral.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 ddlBranch_SelectedIndexChanged(object sender, EventArgs e)
    {
        loadBranch(2);
    }
    protected void ddlBranchAcc_SelectedIndexChanged(object sender, EventArgs e)
    {
        loadBranchAcc(2);
    }


    
    
}
