using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
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.Xml.Linq;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.IO;
using System.Xml;


public partial class Domestic_OneWayResult : System.Web.UI.Page
{
    public string DepartDate_range;
    Hermes obj_Hermes;
    AirEpointSupport obj_AirEpointSupport;
    DataSet ds = new DataSet();
    string Clientid, Clientpassword, Clienttype;
    string intClienttype, intClientid, intClientpassword, IntAvalability;
    string prfredairlines;
    int TotalPassenger = 0;



    decimal minimumfare = 0;
    decimal maximumfare = 0;
    protected void Page_Load(object sender, EventArgs e)
    {

        //__________

        Lavidatatable = new DataTable();
        Lavidatatable.Columns.Add("id", typeof(int));
        Lavidatatable.Columns.Add("fare", typeof(decimal));
        //_________
        obj_AirEpointSupport = new AirEpointSupport();
        try
        {
         
          

            if (!IsPostBack)
            {
                
               if (Convert.ToString(Session["Client_id"]) != "10280")
                {
                    Session["agentMarkup"] = Convert.ToDecimal(Session["agentMarkup"]);
                }
                ds = obj_AirEpointSupport.GetAirPortDetails();
                AirPortList = ds.Tables[0];
                txt_departdate.Text = DateTime.Now.AddDays(1).ToString("dd-MMM-yyyy");
                txt_arrivaldate.Text = DateTime.Now.AddDays(2).ToString("dd-MMM-yyyy");

                HiddenField_Roundtrip.Value = "False";
                Fill_Initial();
                GetResults();





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

                    lbl_dayofweek.Text = Convert.ToDateTime(Convert.ToString(Session["DepartureDate"])).ToString("ddd");
                   
                    lbl_date.Text = Convert.ToDateTime(Convert.ToString(Session["DepartureDate"])).ToString("dd-MMM-yyyy");
                  
                    lbl_adults.Text = Convert.ToString(Session["Adults"]);
                    lbl_child.Text = Convert.ToString(Session["Children"]);
                    lbl_infant.Text = Convert.ToString(Session["Infants"]);
                    lbl_from.Text = Convert.ToString(Session["DestinationFromValue"]);
                    lbl_to.Text = Convert.ToString(Session["DestinationToValue"]);

                    TotalPassenger = Convert.ToInt32(Session["Adults"]) + Convert.ToInt32(Session["Children"]) + Convert.ToInt32(Session["Infants"]);

                    Session["Total_Passenger"] = Convert.ToInt32(lbl_adults.Text) + Convert.ToInt32(lbl_child.Text) + Convert.ToInt32(lbl_infant.Text);

                }


                GetData();
                lbl_filter_maxprice.Text = maximumfare.ToString();
                lbl_filter_minprice.Text = minimumfare.ToString();
                lbl_filter_minprice_slider.Text = minimumfare.ToString();
                lbl_filter_maxprice_slider.Text = maximumfare.ToString();
                #region Fill modify search flight div according to previous session search


                txt_departdate.Text = DateTime.Now.AddDays(0).ToString("dd-MMM-yyyy");
                txt_arrivaldate.Text = DateTime.Now.AddDays(1).ToString("dd-MMM-yyyy");

                #endregion

                //}
            }




            txt_departdate.Attributes.Add("readonly", "readonly");

            txt_arrivaldate.Attributes.Add("readonly", "readonly");
            #region Depart  Date Validation
            // Depart Date VALIDATION
            DateTime DepartMaxDate = new DateTime();
            DepartMaxDate = DateTime.Now.AddYears(10);

            DateTime DepartMinimumDate = new DateTime();
            DepartMinimumDate = DateTime.Now;


            string DepartMinYear = DepartMinimumDate.ToString("yyyy");
            string DepartMinMonth = DepartMinimumDate.ToString("MM");
            string DepartMinDay = DepartMinimumDate.ToString("dd");


            string DepartMaxYear = DepartMaxDate.ToString("yyyy");
            string DepartMaxMonth = DepartMaxDate.ToString("MM");
            string DepartMaxDay = DepartMaxDate.ToString("dd");
            DepartDate_range = "[[" + DepartMinYear + "," + DepartMinMonth + "," + DepartMinDay + "],[" + DepartMaxYear + "," + DepartMaxMonth + "," + DepartMaxDay + "]]";


            #endregion
        }
        catch (Exception ex)
        {
            obj_AirEpointSupport.WriteToLog(ex.Message, "OneWayResult", "Page_Load__" + Convert.ToString(Session["partnerRefId"]));
            Response.Redirect("../User/Index.aspx?s=timeout");
        }
    }

    public static DataTable AirPortList;

    [System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
    public static string[] GetCompletionList(string prefixText, int count, string contextKey)
    {


        prefixText = AirEpointSupport.ToUpperFirstLetter(prefixText);
        var RESULT = (from table1 in AirPortList.AsEnumerable()
                      where table1.Field<string>("CityName").Contains(prefixText) || table1.Field<string>("CityCode").Contains(prefixText) || table1.Field<string>("Counrty").Contains(prefixText) || table1.Field<string>("AirPortDec").Contains(prefixText) ||
                     table1.Field<string>("CityName").Contains(prefixText.ToUpper()) || table1.Field<string>("CityCode").Contains(prefixText.ToUpper()) || table1.Field<string>("Counrty").Contains(prefixText.ToUpper()) || table1.Field<string>("AirPortDec").Contains(prefixText.ToUpper())
                      select table1).Distinct();

        DataTable dt = new DataTable();
        dt = RESULT.CopyToDataTable();
        DataSet _ds = new DataSet();
        _ds.Tables.Add(dt);
        List<string> CompletionSet = new List<string>();

        foreach (DataRow rdr in _ds.Tables[0].Rows)
        {
            string daaa = rdr["CityName"].ToString().ToUpper() + "," + rdr["AirPortDec"].ToString().ToUpper() + " (" + rdr["CityCode"].ToString().ToUpper() + ")";
            CompletionSet.Add(daaa.ToString());

        }
        return CompletionSet.ToArray();
    }

    #region GET DATA
    private void GetData()
    {
        try
        {
            Session.Remove("childnode");
            if (Convert.ToString(Session["Response"]) != "")
            {

                XmlDocument xDoc = new XmlDocument();
                xDoc.LoadXml(Session["myResult"].ToString());
                XmlNodeList xNodeList = xDoc.SelectNodes("AvailabilityResponse");
                foreach (XmlNode xNode in xNodeList)
                {
                    XmlNodeList innerNodeList = xNode.ChildNodes;
                    foreach (XmlNode xNodeInner in innerNodeList)
                    {
                        if (xNodeInner.Name == "UserTrackId")
                        {
                            Session["UserT_ID"] = xNodeInner.InnerText;
                        }

                        if (xNodeInner.Name == "AvailFlightDetails")
                        {




                            ViewState["TotalSearchResult"] = xNodeInner.InnerXml;
                            ds = new DataSet();
                            string st1 = "<root>" + xNodeInner.InnerXml + "</root>";
                            ds.ReadXml(new StringReader(st1));

                      
                            DataTable flightSegment = ds.Tables["SegFlightDetails"];
                            Session["fs"] = flightSegment;
                            DataTable adult_price = (from abc in ds.Tables["Item"].AsEnumerable()
                                                     where abc.Field<string>("Pax") == "ADT"
                                                     select abc).CopyToDataTable();
                            //// For Adult only

                            DataTable newTable = new DataTable();
                            newTable.Columns.Add(new DataColumn("FlightId", typeof(string)));
                            newTable.Columns.Add(new DataColumn("CarrierCode", typeof(string)));
                            newTable.Columns.Add(new DataColumn("FlightNo", typeof(string)));
                            newTable.Columns.Add(new DataColumn("AirCraftType", typeof(string)));
                            newTable.Columns.Add(new DataColumn("Source", typeof(string)));
                            newTable.Columns.Add(new DataColumn("Destination", typeof(string)));
                            newTable.Columns.Add(new DataColumn("DepartureDateTime", typeof(string)));
                            newTable.Columns.Add(new DataColumn("ArrivalDateTime", typeof(string)));
                            newTable.Columns.Add(new DataColumn("Duration", typeof(string)));
                            newTable.Columns.Add(new DataColumn("NumberofStops", typeof(string)));
                            newTable.Columns.Add(new DataColumn("SegFlightDetails_Id", typeof(int)));
                            newTable.Columns.Add(new DataColumn("AvailFlightItem_Id", typeof(int)));
                            newTable.Columns.Add(new DataColumn("PaxFareDetails_Id", typeof(int)));
                            newTable.Columns.Add(new DataColumn("BasicAmount", typeof(double)));
                            newTable.Columns.Add(new DataColumn("GrossAmount", typeof(double)));
                            newTable.Columns.Add(new DataColumn("FareBasis", typeof(string)));
                            newTable.Columns.Add(new DataColumn("FuelSurcharge", typeof(double)));
                            newTable.Columns.Add(new DataColumn("Commission", typeof(double)));
                            newTable.Columns.Add(new DataColumn("Pax", typeof(string)));
                            newTable.Columns.Add(new DataColumn("ClassCode", typeof(string)));
                            DataRow Table_Row;
                            for (int i = 0; i < ds.Tables["SegFlightDetails"].Rows.Count; i++)
                            {
                                //new line
                                 var dttt = (from table2 in ds.Tables["PaxFareDetails"].AsEnumerable()
where table2.Field<int>("SegFlightDetails_Id") == i
select table2).Take(1).ToArray();
//End New line
int j = Convert.ToInt32(dttt[0].ItemArray[3]);

                                double GA = 0;
                                double BA = 0;
                                double FS = 0;
                                double Com = 0;
                                string Farebasis = string.Empty;
                                if (adult_price.Rows[j]["GrossAmount"] == null || Convert.ToString(adult_price.Rows[j]["GrossAmount"]) == "" || Convert.ToString(adult_price.Rows[j]["GrossAmount"]) == "0")
                                {
                                    for (int a = 1; a <= 4; a++)
                                    {
                                        if (Convert.ToString(adult_price.Rows[j + a]["GrossAmount"]) != "" && Convert.ToString(adult_price.Rows[j + a]["GrossAmount"]) != "0")
                                        {
                                            GA = Convert.ToDouble(adult_price.Rows[j + a]["GrossAmount"]);
                                            BA = Convert.ToDouble(adult_price.Rows[j + a]["BasicAmount"]);
                                            FS = Convert.ToDouble(adult_price.Rows[j + a]["FuelSurcharge"]);
                                            Com = Convert.ToDouble(adult_price.Rows[j + a]["Commission"]);
                                            Farebasis = Convert.ToString(adult_price.Rows[j + a]["FareBasis"]);
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    GA = Convert.ToDouble(adult_price.Rows[j]["GrossAmount"]);
                                    BA = Convert.ToDouble(adult_price.Rows[j]["BasicAmount"]);
                                    FS = Convert.ToDouble(adult_price.Rows[j]["FuelSurcharge"]);
                                    Com = Convert.ToDouble(adult_price.Rows[j]["Commission"]);
                                    Farebasis = Convert.ToString(adult_price.Rows[j]["FareBasis"]);
                                }
                                string noStop = string.Empty;
                                if (ds.Tables["SegFlightDetails"].Rows[i]["NumberofStops"].ToString() == "")
                                {
                                    noStop = "0";
                                }
                                else
                                {
                                    noStop = ds.Tables["SegFlightDetails"].Rows[i]["NumberofStops"].ToString();
                                }

                                newTable.Rows.Add(ds.Tables["SegFlightDetails"].Rows[i]["FlightId"].ToString(), ds.Tables["SegFlightDetails"].Rows[i]["CarrierCode"],
                                    Convert.ToString(ds.Tables["SegFlightDetails"].Rows[i]["FlightNo"]), ds.Tables["SegFlightDetails"].Rows[i]["AirCraftType"],
                                    ds.Tables["SegFlightDetails"].Rows[i]["Source"], ds.Tables["SegFlightDetails"].Rows[i]["Destination"],
                                    ds.Tables["SegFlightDetails"].Rows[i]["DepartureDateTime"], ds.Tables["SegFlightDetails"].Rows[i]["ArrivalDateTime"],
                                    ds.Tables["SegFlightDetails"].Rows[i]["Duration"], noStop,
                                    ds.Tables["SegFlightDetails"].Rows[i]["SegFlightDetails_Id"], ds.Tables["SegFlightDetails"].Rows[i]["AvailFlightItem_Id"],
                                   // dttt[0].ItemArray[3].ToString(), BA, GA, Farebasis, FS, Com, Convert.ToString(adult_price.Rows[i]["Pax"]), Convert.ToString(dttt[0].ItemArray[0]));
ds.Tables["PaxFareDetails"].Rows[i]["PaxFareDetails_Id"], BA, GA, Farebasis, FS, Com, Convert.ToString(adult_price.Rows[j]["Pax"]), Convert.ToString(ds.Tables["PaxFareDetails"].Rows[i]["ClassCode"]));


                            }

                            DataTable asc_amount = (from table1 in newTable.AsEnumerable()
                                                    orderby table1["GrossAmount"] ascending
                                                    select table1).CopyToDataTable();
                            var dist_Item = (from table2 in asc_amount.AsEnumerable()
                                             select table2.Field<int>("AvailFlightItem_Id")).Distinct();
                            DataTable dist_Detail = new DataTable();
                            dist_Detail.Columns.Add("AvailFlightItem_Id", typeof(int));


                            foreach (int item in dist_Item)
                            {
                                DataRow newRow = dist_Detail.NewRow();
                                newRow["AvailFlightItem_Id"] = item;
                                dist_Detail.Rows.Add(newRow);
                            }

                           // myrepeater.DataSource = asc_amount;
                            myrepeater.DataSource = dist_Detail;
                            Session["FareData"] = newTable;
                            Session["chargeableFares"] = adult_price;
                            
                            Session["NonchargeableFares"] = ds.Tables["Item"];
                            Session["BookingClassFare"] = ds.Tables["PaxFareDetails"];


                         B2B obj = new B2B();
                         ViewState["AgentComm_Perc"] = obj.Domestic_GetAgentCommission_Perc(Session["agid"].ToString(), Convert.ToString(Session["HURL"]));

                          ViewState["CompanyComm_Perc"] = obj.Domestic_GetCompanyCommission_Perc(Session["agid"].ToString(), Convert.ToString(Session["HURL"]));

                  // ViewState["AgentComm_Perc"] = "80";

                           // ViewState["CompanyComm_Perc"] = "20";


                            myrepeater.DataBind();
                            ViewState["Lavitable"] = Lavidatatable;
                            sortloop("asc");




                        }

                    }
                }
            }
        }

        catch (Exception ex)
        {
            obj_AirEpointSupport.WriteToLog(ex.Message, "OneWayResult", "GetData__" + Convert.ToString(Session["partnerRefId"]));
            Response.Redirect("../User/Index.aspx?s=timeout");
        }
    }

    #endregion

    #region GET THE RESULT FROM AIR API
    private void GetResults()
    {
        try
        {
            //if (Convert.ToString(Session["Send_Request"]) != "")
            //{
                string cdate = DateTime.Now.ToString("yyy-MM-dd");
                string ctime = DateTime.Now.ToString("HH_mm_ss");
                string time_date = cdate + "_" + ctime;


               
                string get_request = Convert.ToString(Session["myResult"]);


              


                ds = new DataSet();
                ds = (DataSet)Session["Response"];

                if (ds.Tables[0].Rows.Count == 0)
                {


                
                    Response.Redirect("../User/Index.aspx?s=NoFlight", false);



                }
           // }
        }
        catch (Exception ex)
        {
            obj_AirEpointSupport.WriteToLog(ex.Message, "OneWayResult", "GetResults__" + Convert.ToString(Session["partnerRefId"]));
            Response.Redirect("../User/Index.aspx?s=timeout");
        }
    }
    #endregion

    public void RemoveSession()
    {


        Session.Remove("childnode");
        //   Session.Remove("Send_Request");
        Session.Remove("myResult");
        Session.Remove("fs");
        Session.Remove("chargeableFares");
        Session.Remove("NonchargeableFares");
        Session.Remove("BookingClassFare");


    }

    private void Checklist()
    {
        try
        {

            CheckBoxList list = CheckBoxList_Airlines;

            int count = 0;
            foreach (ListItem item in list.Items)
            {
                if (item.Selected)
                {
                    prfredairlines += item.Value + ",";
                    count += 1;
                }
            }
            if (count == 0)
            {
                foreach (ListItem item in list.Items)
                {

                    prfredairlines += item.Value + ",";


                }

            }
            ViewState["selectedairlines"] = prfredairlines.Remove(prfredairlines.Length - 1, 1);
        }
        catch (Exception ex)
        {
          //  Air_transaction_Cal.writeToLogFile("BookingProcess_DomesticInterNational.aspx-Checklist()" + ex.Message.ToString(), Server.MapPath("~/Air_InternaltionalExceptionList"));
            ViewState["selectedairlines"] = "";
        }
    }

    protected void btn_submit_Click(object sender, EventArgs e)
    {

        try
        {
            bool validation = true;
            string msg = "";

            if (RadioButtonround.Checked && Convert.ToDateTime(txt_arrivaldate.Text) < Convert.ToDateTime(txt_departdate.Text))
            {
                validation = false;
                msg = "Return date can not less than departure date.";
            }
            if (txt_from.Text.Trim() == "" || txt_from.Text == "Enter Origin City or Airport Name")
            {
                validation = false;
                msg = "Please enter origin city.";
            }

            if (txt_to.Text.Trim() == "" || txt_to.Text == "Enter Destination City or Airport Name")
            {
                validation = false;
                msg = "Please enter destination city.";
            }

            if (validation)
            {

                #region Submit Form

                int x = obj_AirEpointSupport.CheckSearchFlight(txt_from.Text, txt_to.Text);
                if (x == 1)
                {
                    Checklist();

                    if (txt_departdate.Text != "" && txt_arrivaldate.Text != "")
                    {
                        Session["From_Source"] = txt_from.Text;
                        Session["To_Source"] = txt_to.Text;
                        string DestinationFromValue = obj_AirEpointSupport.FindAirPortCode(txt_from.Text).Replace(")", "");
                        string DestinationToValue = obj_AirEpointSupport.FindAirPortCode(txt_to.Text).Replace(")", "");
                        Session["sourc"] = DestinationFromValue;
                        Session["Dest"] = DestinationToValue;

                        string DestinationFrom = obj_AirEpointSupport.FindAirPortCityName(txt_from.Text);
                        string DestinationTo = obj_AirEpointSupport.FindAirPortCityName(txt_to.Text);
                        string trip;
                        if (RadioButtononeway.Checked)
                        {
                            trip = "One";

                        }
                        else if (RadioButtonround.Checked)
                        {
                            trip = "Round";
                        }
                        else
                        {
                            trip = "SplFare";
                        }

                        Session["Trip"] = trip;
                        Session["DestinationFrom"] = DestinationFrom.ToString();
                        Session["DestinationFromValue"] = DestinationFrom;
                        Session["DestinationTo"] = DestinationTo;
                        Session["DestinationToValue"] = DestinationTo;
                        Session["DepartureDate"] = Convert.ToDateTime(txt_departdate.Text).ToString("yyyy-MMM-dd");
                        Session["ReturnDate"] = Convert.ToDateTime(txt_arrivaldate.Text).ToString("yyyy-MMM-dd");
                        Session["DepartureDate1"] = Convert.ToDateTime(txt_departdate.Text).ToString("dd-MMM-yyyy");
                        Session["ReturnDate1"] = Convert.ToDateTime(txt_arrivaldate.Text).ToString("dd-MMM-yyyy");
                        Session["Adults"] = ddl_adult.SelectedItem.Value.ToString();
                        Session["Children"] = ddl_child.SelectedItem.Value.ToString();
                        Session["Infants"] = ddl_infant.SelectedItem.Value.ToString();
                        Session["Class"] = ddl_class.SelectedItem.Value.ToString();
                        TotalPassenger = Convert.ToInt32(ddl_adult.SelectedItem.Value) + Convert.ToInt32(ddl_child.SelectedItem.Value);
                        Session.Remove("partnerRefId");

                        Random r = new Random();

                        Session["partnerRefId"] = obj_AirEpointSupport.Generate_TID();
                        string sss = Convert.ToString(Session["partnerRefId"]);
                        #region  Domestic Search
                        if (obj_AirEpointSupport.CheckSourceDestination(txt_from.Text, txt_to.Text) == "DOM")
                        {




                            #region Regular Domestic

                            #region Domestic

                            if (Convert.ToString(ViewState["flighttypelavi"]) != "DOM")
                            {
                                ViewState["selectedairlines"] = "";
                            }
                            Session["DestinationFrom"] = DestinationFrom;
                            Session["DestinationFromValue"] = DestinationFromValue;
                            Session["DestinationTo"] = DestinationTo;
                            Session["DestinationToValue"] = DestinationToValue;
                            Session["FlightType"] = "DOM";
                            #region Domestic Oneway
                            if (Convert.ToString(Session["Trip"]) == "One")
                            {
                                if (TotalPassenger <= 9)
                                {
                                  //  ViewState["selectedairlines"] = "AI,G8,IC,6E,9W,S2,IT,9H,I7,SG,IX";
                                    txt_arrivaldate.Text = DateTime.Parse(txt_departdate.Text).ToString("MM/dd/yyyy");
                                    string request_Avail = @"<AvailabilityReq><BookingType>O</BookingType><JryDetails><Item><Origin>" + DestinationFromValue + @"</Origin><Destination>" + DestinationToValue + @"</Destination>
<TravelDate>" + txt_arrivaldate.Text + @"</TravelDate></Item></JryDetails><ClassType>Economy</ClassType>
<Airlinecodes></Airlinecodes><Adults>" + ddl_adult.SelectedItem.Value.ToString() + @"</Adults><Childs>" + ddl_child.SelectedItem.Value.ToString() + @"</Childs>
<Infants>" + ddl_infant.SelectedItem.Value.ToString() + @"</Infants>
<ResidentofIndia>1</ResidentofIndia><DirectAccess>0</DirectAccess><TransFeeFlag>1</TransFeeFlag></AvailabilityReq>";
                                    Hermes obj_hermes = new Hermes();
                                    DataSet ds = new DataSet();
                                    string response_avail = obj_hermes.AirAvailability(request_Avail);
                                    Session["myResult"] = response_avail;
                                    ds.ReadXml(new StringReader(response_avail));
                                    Session["Response"] = ds;



                                    Response.Redirect("../Domestic/OneWayResult.aspx", false);
                                }
                                else
                                {
                                    Page.RegisterStartupScript("XXX", "<script> alert('Sum of Adult and child passenger travelling not more than 9')</script>");
                                }
                            }
                            #endregion
                            #region Domestic Round
                            else if (Convert.ToString(Session["Trip"]) == "Round")
                            {
                                if (TotalPassenger <= 9)
                                {
                                 
                                    txt_departdate.Text = DateTime.Parse(txt_departdate.Text).ToString("MM/dd/yyyy");
                                    txt_arrivaldate.Text = DateTime.Parse(txt_arrivaldate.Text).ToString("MM/dd/yyyy");
                                    
                                    string request_Avail = @"<AvailabilityReq><BookingType>R</BookingType><JryDetails><Item><Origin>" + DestinationFromValue + @"</Origin><Destination>" + DestinationToValue + @"</Destination>
<TravelDate>" + txt_departdate.Text + @"</TravelDate></Item><Item><Origin>" + DestinationToValue + @"</Origin><Destination>" + DestinationFromValue + @"</Destination>
<TravelDate>" + txt_arrivaldate.Text + @"</TravelDate></Item></JryDetails><ClassType>Economy</ClassType>
<Airlinecodes></Airlinecodes><Adults>" + ddl_adult.SelectedItem.Value.ToString() + @"</Adults><Childs>" + ddl_child.SelectedItem.Value.ToString() + @"</Childs>
<Infants>" + ddl_infant.SelectedItem.Value.ToString() + @"</Infants>
<ResidentofIndia>1</ResidentofIndia><DirectAccess>0</DirectAccess><TransFeeFlag>1</TransFeeFlag></AvailabilityReq>";
                                    Hermes obj_hermes = new Hermes();
                                    DataSet ds = new DataSet();
                                    string response_avail = obj_hermes.AirAvailability(request_Avail);
                                   
                                    Session["myResult"] = response_avail;
                                    ds.ReadXml(new StringReader(response_avail));
                                    Session["Response"] = ds;

                                    Response.Redirect("../Domestic/RoundTripResult.aspx", false);
                                }
                                else
                                {
                                    Page.RegisterStartupScript("XXX", "<script> alert('Sum of Adult and child passenger travelling not more than 9')</script>");
                                }
                            }
                            #endregion
                            #endregion

                            #endregion



                        }
                        #endregion


                        #region International Search
                        //else if (obj_AirEpointSupport.CheckSourceDestination(txt_from.Text, txt_to.Text) == "INAIR" || obj_AirEpointSupport.CheckSourceDestination(txt_from.Text, txt_to.Text) == "SETO")
                        //{
                        //    //if (obj_AirEpointSupport.GetActiveVendorForService("International") == "Arzoo")
                        //    //{

                        //        Session["FlightType"] = "INAIR";
                        //        if (Convert.ToString(ViewState["flighttypelavi"]) != "INAIR")
                        //        {
                        //            ViewState["selectedairlines"] = "";
                        //        }
                        //        #region INTERNATIONAL One Way
                        //        if (Convert.ToString(Session["Trip"]) == "One")
                        //        {


                        //            if (TotalPassenger <= 9)
                        //            {

                        //                txt_arrivaldate.Text = DateTime.Parse(txt_departdate.Text).AddDays(2).ToString("MM/dd/yyyy");
                        //                string Request = "<AvailabilityReq><BookingType>O</BookingType><Details><Item><Source>" + DestinationFromValue + "</Source><Destination>" + DestinationToValue + "</Destination><Date>" + DateTime.Parse(txt_departdate.Text).ToString("MM/dd/yyyy") + "</Date></Item></Details><ClassTypeId>Economy</ClassTypeId><AIRLINES /><Adult>" + Convert.ToInt16(ddl_adult.SelectedItem.Value.ToString()) + "</Adult><Child>" + Convert.ToInt16(ddl_child.SelectedItem.Value.ToString()) + "</Child><Infant>" + Convert.ToInt16(ddl_infant.SelectedItem.Value.ToString()) + "</Infant><ResidentofIndia>1</ResidentofIndia><AirlineCode></AirlineCode><DirectAccess>0</DirectAccess></AvailabilityReq>";
                        //                Session.Remove("Response");
                        //                obj_AirEpointSupport.WriteXmlLog(Request, "International_Request");
                        //                obj_Hermes = new Hermes();
                        //                string Response_result = obj_Hermes.Inter_AirAvailability(Request);
                        //                obj_AirEpointSupport.WriteXmlLog(Response_result, "International_Response");
                        //                Session["Response"] = Response_result;
                        //                Response.Redirect("../International/OneWayInternational.aspx", false);
                        //            }

                        //            else
                        //            {
                        //                Page.RegisterStartupScript("XXX", "<script> alert('Sum of Adult and child passenger travelling not more than 9')</script>");
                        //            }

                        //        }
                        //        #endregion

                        //        #region INTERNATIONAL RoundTrip
                        //        else if (Convert.ToString(Session["Trip"]) == "Round")
                        //        {
                        //            if (DateTime.Parse(txt_arrivaldate.Text) < DateTime.Parse(txt_departdate.Text))
                        //            {


                        //                Page.RegisterStartupScript("XXX", "<script> alert('Return Date Cannot be less than Depart Date')</script>");


                        //                if (TotalPassenger > 9)
                        //                {
                        //                    Page.RegisterStartupScript("XXX", "<script> alert('Sum of Adult and child passenger travelling not more than 9')</script>");
                        //                }
                        //            }
                        //            else
                        //            {
                        //                if (TotalPassenger <= 9)
                        //                {

                        //                    string Request = "<AvailabilityReq><BookingType>R</BookingType><Details><Item><Source>" + DestinationFromValue + "</Source><Destination>" + DestinationToValue + "</Destination><Date>" + DateTime.Parse(txt_departdate.Text).ToString("MM/dd/yyyy") + "</Date></Item><Item><Source>" + DestinationToValue + "</Source><Destination>" + DestinationFromValue + "</Destination><Date>" + DateTime.Parse(txt_arrivaldate.Text).ToString("MM/dd/yyyy") + "</Date></Item></Details><ClassTypeId>Economy</ClassTypeId><AIRLINES /><Adult>" + Convert.ToInt16(ddl_adult.SelectedItem.Value.ToString()) + "</Adult><Child>" + Convert.ToInt16(ddl_child.SelectedItem.Value.ToString()) + "</Child><Infant>" + Convert.ToInt16(ddl_infant.SelectedItem.Value.ToString()) + "</Infant><ResidentofIndia>1</ResidentofIndia><AirlineCode></AirlineCode><DirectAccess>0</DirectAccess></AvailabilityReq>";
                                           
                        //                    Session.Remove("Response");
                        //                    obj_Hermes = new Hermes();
                        //                    string Response_result = obj_Hermes.Inter_AirAvailability(Request);
                        //                    Session["Response"] = Response_result;
                        //                    Response.Redirect("../international/RoundTripResultInternational.aspx", false);
                                         

                                           
                        //                }

                        //                else
                        //                {
                        //                    Page.RegisterStartupScript("XXX", "<script> alert('Sum of Adult and child passenger travelling not more than 9')</script>");
                        //                }

                        //            }
                        //        }
                        //        #endregion
                        //    //}
                        //    //else
                        //    //{
                        //    //    Page.RegisterStartupScript("XXX", "<script> alert('This service is currently unavailable.Please try later.')</script>");
                        //    //}
                        //}
                        #endregion

                    }
                    else
                    {
                        Page.RegisterStartupScript("XXX", "<script> alert('Source and Destination names do not exist.')</script>");
                    }

                }
                else if (x == 0)
                {
                    Page.RegisterStartupScript("XXX", "<script> alert('Source and Destination names do not exist.')</script>");
                }
                #endregion
            }
            else
            {
                RegisterClientScriptBlock("alert", "<script>alert('" + msg + "');</script>");
            }


        }

        catch (Exception ex)
        {
            obj_AirEpointSupport.WriteToLog(ex.Message, "OneWayResult", "btn_submit_modify search__" + Convert.ToString(Session["partnerRefId"]));

            RegisterClientScriptBlock("alert", "<script>alert('Please correct input validations');</script>");
        }
    }

    DataTable Lavidatatable;

    public void sortloop(string sortorder)
    {

        DataTable Lavidatatable = (DataTable)ViewState["Lavitable"];
        if (sortorder == "asc")
        {
            Lavidatatable = (from abc in Lavidatatable.AsEnumerable()
                             orderby abc.Field<decimal>("fare") ascending
                             select abc).CopyToDataTable();
        }
        else
        {
            Lavidatatable = (from abc in Lavidatatable.AsEnumerable()
                             orderby abc.Field<decimal>("fare") descending
                             select abc).CopyToDataTable();
        }

        decimal AgentComm_Perc = Convert.ToDecimal(ViewState["AgentComm_Perc"]);
        decimal CompanyComm_Perc = Convert.ToDecimal(ViewState["CompanyComm_Perc"]);

        DataTable flightdetails = (DataTable)Session["fs"];
        DataRow row2 = null;
        var AirLinesName1 = (from Airline in flightdetails.AsEnumerable()
                             select new { Aircode = Airline["CarrierCode"] }).Distinct();

        DataTable dataTable2 = new DataTable();
        // dataTable2 = (DataTable)Session["dataTable2"];
        dataTable2.Columns.Add("AirlineCode", typeof(string));
        dataTable2.Columns.Add("AirLineName", typeof(string));
        foreach (var rowObj in AirLinesName1.ToList())
        {
            DataSet ds2 = new DataSet();
            ds2 = obj_AirEpointSupport.GetAirLineDetails();
            var AirName = from Airline2 in ds2.Tables["AirLine"].AsEnumerable()
                          where Airline2.Field<string>("AirLineCode") == rowObj.Aircode.ToString()
                          select new
                          {
                              Airlinename = Airline2["AirLineName"]
                          };
            row2 = dataTable2.NewRow();
            string airlinenamefinal;
            if (AirName.AsEnumerable().Count() <= 0)
            {
                airlinenamefinal = "";
            }
            else airlinenamefinal = AirName.AsEnumerable().ElementAt(0).Airlinename.ToString();
            dataTable2.Rows.Add(rowObj.Aircode, airlinenamefinal);
        }

        CheckBoxList_Airlines.DataSource = dataTable2;
        CheckBoxList_Airlines.DataValueField = "AirLineCode";
        CheckBoxList_Airlines.DataTextField = "AirLineName";
        CheckBoxList_Airlines.DataBind();

        foreach (ListItem item in CheckBoxList_Airlines.Items)
        {
            item.Selected = true;
            int thisIndex = CheckBoxList_Airlines.Items.IndexOf(item);
            if (thisIndex == -1)
            {
                item.Attributes.Add("Style", "Display:none;");
            }
            item.Attributes.Add("onClick", "hideRows('" + item.Value + "',this);");

        }

        for (int index = 0; index < Lavidatatable.Rows.Count; index++)
        {
            DataTable flight = (DataTable)Session["fs"];

           
            DataTable fare = (DataTable)Session["faredata"];

            DataTable data = (from a in fare.AsEnumerable()
                              where a.Field<int>("AvailFlightItem_Id") == Convert.ToInt16(Lavidatatable.Rows[index][0])
                              select a).CopyToDataTable();

          //  DataRow faredata = fare.Rows[Convert.ToInt16(Lavidatatable.Rows[index][0])];
            DataRow faredata = data.Rows[0];
            DataTable farenon = (DataTable)Session["NonchargeableFares"];
            DataRow farenonc = farenon.Rows[Convert.ToInt16(Lavidatatable.Rows[index][0])];

            ((Label)myrepeater.Items[index].FindControl("lbl_fare_segmrnt_id")).Text = Convert.ToString(Lavidatatable.Rows[index][0]);
            Label BaseFarelabel = (Label)myrepeater.Items[index].FindControl("lbl_basefare");
            Label AirportTaxLabel = (Label)myrepeater.Items[index].FindControl("lbl_AirportTax");
            Label Servicetaxlabel = (Label)myrepeater.Items[index].FindControl("lbl_Serice_Tax");
            Label Txnfee = (Label)myrepeater.Items[index].FindControl("lbl_txn_fee");
            Label BookingDiscountLabel = (Label)myrepeater.Items[index].FindControl("lbl_bookingdiscount");
            Label TotalPrice = (Label)myrepeater.Items[index].FindControl("lbl_total_fee");
            Label TotalPrice1 = (Label)myrepeater.Items[index].FindControl("LabelTotalFare");
            Label Misc = (Label)myrepeater.Items[index].FindControl("lbl_mics");


            Label curr = (Label)myrepeater.Items[index].FindControl("Label1");

            Label labelAgentCommissin = (Label)myrepeater.Items[index].FindControl("lbl_agent_commission");
            Label lbl_total_price = (Label)myrepeater.Items[index].FindControl("lbl_total_price");
            Label lbl_amt_with_comp_comm = (Label)myrepeater.Items[index].FindControl("lbl_amt_with_comp_comm");

            string baseAmount, FuelSurcharge, GrossAmount, Commission;
            if (faredata["BasicAmount"].ToString() == "")
                baseAmount = "0";
            else
                baseAmount = faredata["BasicAmount"].ToString();
            if (faredata["FuelSurcharge"].ToString() == "")
                FuelSurcharge = "0";
            else
                FuelSurcharge = faredata["FuelSurcharge"].ToString();
            if (faredata["GrossAmount"].ToString() == "")
                GrossAmount = "0";
            else
                GrossAmount = faredata["GrossAmount"].ToString();
            if (faredata["Commission"].ToString() == "")
                Commission = "0";
            else
                Commission = faredata["Commission"].ToString();
            decimal[] fares = DomesticPrice_Result(Convert.ToDecimal(baseAmount), Convert.ToDecimal(FuelSurcharge), Convert.ToDecimal(GrossAmount), Convert.ToDecimal(Commission), 0);
          

            decimal mark_up = Convert.ToDecimal(Session["agentMarkup"]);
            decimal all_markup = Convert.ToDecimal(Session["allMarkup"]);



            BaseFarelabel.Text = Math.Round(fares[0] * Convert.ToDecimal(Session["convertor"])).ToString();
            AirportTaxLabel.Text = Math.Round(fares[1] * Convert.ToDecimal(Session["convertor"])).ToString();
            Servicetaxlabel.Text = Math.Round(fares[2] * Convert.ToDecimal(Session["convertor"])).ToString();
            BookingDiscountLabel.Text = Math.Round(0 * Convert.ToDecimal(Session["convertor"])).ToString();
            Txnfee.Text = Math.Round(fares[3] * Convert.ToDecimal(Session["convertor"])).ToString();
            decimal ticketfare = fares[5];
            decimal Hermes_Comm = fares[4];

            decimal CompanyComm = Math.Ceiling((Hermes_Comm * CompanyComm_Perc) / 100);
            decimal AgentComm = Math.Ceiling((Hermes_Comm * AgentComm_Perc) / 100);

            lbl_amt_with_comp_comm.Text = Math.Round((ticketfare - AgentComm+all_markup) * Convert.ToDecimal(Session["convertor"])).ToString();
            labelAgentCommissin.Text = Math.Round((AgentComm + mark_up) * Convert.ToDecimal(Session["convertor"])).ToString();

            lbl_total_price.Text = Math.Round((ticketfare + mark_up+all_markup) * Convert.ToDecimal(Session["convertor"])).ToString();
            TotalPrice1.Text = Math.Round((ticketfare + mark_up+all_markup) * Convert.ToDecimal(Session["convertor"])).ToString();
            TotalPrice.Text = Math.Round((ticketfare + mark_up+all_markup) * Convert.ToDecimal(Session["convertor"])).ToString();
            Misc.Text = Math.Round((mark_up+all_markup) * Convert.ToDecimal(Session["convertor"])).ToString();

            curr.Text = Session["Currency"].ToString();

            Session["Dom_CompanyComm"] = CompanyComm;

            #region outer data
       
            DataRow dr = data.Rows[0];
            Image img = (Image)myrepeater.Items[index].FindControl("ImageFlight");
            img.ImageUrl = dr["CarrierCode"].ToString();
            string airlinecode = dr["CarrierCode"].ToString();

      

            Label LabelAirllinename = (Label)myrepeater.Items[index].FindControl("LabelAirllinename");
        
            DataSet ds = obj_AirEpointSupport.GetAirImageDetails();
            var imageurl = from ImgurlDetail in ds.Tables["AirLineImageUrlDetail"].AsEnumerable()
                           where ImgurlDetail.Field<string>("AirlineCode") == Convert.ToString(airlinecode).Trim()
                           select new
                           {
                               airlineimgeurl = ImgurlDetail["filename"].ToString(),
                               airlinename = ImgurlDetail["AirlineName"].ToString()
                           };
            if (imageurl.Count() > 0)
            {
                img.ImageUrl = "../AirLineImage/" + imageurl.AsEnumerable().ElementAt(0).airlineimgeurl;
                LabelAirllinename.Text = imageurl.AsEnumerable().ElementAt(0).airlinename;
            }
            else
            {
                //img.ImageUrl = "";
                img.ImageUrl = "../AirLineImage/blank.jpg";
            }





            Label LabelStations = (Label)myrepeater.Items[index].FindControl("LabelStations");
           LabelStations.Text = dr["Source"].ToString();
            Label LabelDepartdate = (Label)myrepeater.Items[index].FindControl("LabelDepartdate");
           LabelDepartdate.Text = dr["DepartureDateTime"].ToString();
            Label LabelStopQuantity = (Label)myrepeater.Items[index].FindControl("LabelStopQuantity");
            LabelStopQuantity.Text = dr["NumberofStops"].ToString();
            Label LabelDepartTime = (Label)myrepeater.Items[index].FindControl("LabelDepartTime");
            LabelDepartTime.Text = dr["DepartureDateTime"].ToString();

            Label LabelDurationMain = (Label)myrepeater.Items[index].FindControl("LabelDuration");
            string datedepart = dr["Duration"].ToString();

            #endregion


            DataTable bookingfare = (DataTable)Session["BookingClassFare"];

            #region inner region
            for (int i = 0; i < data.Rows.Count; i++)
            {
                dr = data.Rows[i];

                string farerule = "";
              
                Label Labelfaretype = (Label)myrepeater.Items[index].FindControl("LabelFareType" + i.ToString());
          
                Labelfaretype.Text = "Refundable";
              

                Label Labelclasstype = (Label)myrepeater.Items[index].FindControl("LabelClassType" + i.ToString());
                Labelclasstype.Text = bookingfare.Rows[Convert.ToInt32(dr["SegFlightDetails_Id"])]["ClassCode"].ToString().ToUpper();


                if (i > 0)
                {
                    LabelStations.Text = LabelStations.Text + "&rarr;" + dr["Source"].ToString();

                }
                ((HtmlTableRow)myrepeater.Items[index].FindControl("data" + i.ToString())).Visible = true;

               

                LabelAirllinename = (Label)myrepeater.Items[index].FindControl("LabelAirllinename_repeat" + i.ToString());
                LabelAirllinename.Text = dr["CarrierCode"].ToString();
          
             
                Label LabelAirlinecode = (Label)myrepeater.Items[index].FindControl("LabelAirlinecode" + i.ToString());
                LabelAirlinecode.Text = dr["CarrierCode"].ToString();
              

                Label LabelFlightNumber = (Label)myrepeater.Items[index].FindControl("LabelFlightNumber" + i.ToString());
                LabelFlightNumber.Text = dr["FlightNo"].ToString();

                img = (Image)myrepeater.Items[index].FindControl("ImageFlight" + i.ToString());
                img.ImageUrl = dr["CarrierCode"].ToString();
                string airlinecode1 = dr["CarrierCode"].ToString();
                //Image img = new Image();
                img = (Image)myrepeater.Items[index].FindControl("ImageFlight" + i.ToString());
                DataSet ds1 = obj_AirEpointSupport.GetAirImageDetails();
                var imageurl1 = from ImgurlDetail in ds1.Tables["AirLineImageUrlDetail"].AsEnumerable()
                               where ImgurlDetail.Field<string>("AirlineCode") == Convert.ToString(airlinecode1).Trim()
                               select new
                               {
                                   airlineimgeurl = ImgurlDetail["filename"].ToString(),
                                   airlinename = ImgurlDetail["AirlineName"].ToString()
                               };
                if (imageurl.Count() > 0)
                {
                    img.ImageUrl = "../AirLineImage/" + imageurl1.AsEnumerable().ElementAt(0).airlineimgeurl;
                    LabelAirllinename.Text = imageurl1.AsEnumerable().ElementAt(0).airlinename;
                }
                else
                {
                   // img.ImageUrl = "../../AirLineImage/AI.jpg";
                    img.ImageUrl = "../AirLineImage/blank.jpg";
                }


                Label LabelDepartFromCode = (Label)myrepeater.Items[index].FindControl("LabelDepartFromCode" + i.ToString());
                LabelDepartFromCode.Text = dr["Source"].ToString();


                Label LabelArrivalAirportCode = (Label)myrepeater.Items[index].FindControl("LabelArrivalAirportCode" + i.ToString());
                LabelArrivalAirportCode.Text = dr["Destination"].ToString();




                LabelDepartTime = (Label)myrepeater.Items[index].FindControl("LabelDepartTime" + i.ToString());
                LabelDepartTime.Text = dr["DepartureDateTime"].ToString();


                Label LabelArrivalTime = (Label)myrepeater.Items[index].FindControl("LabelArrivalTime" + i.ToString());
                LabelArrivalTime.Text = dr["ArrivalDateTime"].ToString();

                Label duration = (Label)myrepeater.Items[index].FindControl("LabelDuration" + i.ToString());
            
                string durationtime = dr["Duration"].ToString();
                duration.Text = durationtime;

                if (i == data.Rows.Count - 1)
                {

                    LabelArrivalTime = (Label)myrepeater.Items[index].FindControl("LabelArrivalTime");
                    LabelArrivalTime.Text = dr["ArrivalDateTime"].ToString();

                    LabelStations.Text = LabelStations.Text + "&rarr;" + dr["Destination"].ToString();
                 
                    LabelDurationMain.Text = dr["Duration"].ToString();

                }

            }
            #endregion





        }
    }


    protected void myrepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {

        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            DataTable flight = (DataTable)Session["fs"];
            DataTable fare = (DataTable)Session["FareData"];
            DataTable data = (from a in fare.AsEnumerable()
                        where a.Field<int>("AvailFlightItem_Id") == e.Item.ItemIndex
                        select a).CopyToDataTable();
            DataRow faredata = data.Rows[0];
            DataTable farenon = (DataTable)Session["NonchargeableFares"];
            DataRow farenonc = farenon.Rows[e.Item.ItemIndex];
            decimal AgentComm_Perc = Convert.ToDecimal(ViewState["AgentComm_Perc"]);
            decimal CompanyComm_Perc = Convert.ToDecimal(ViewState["CompanyComm_Perc"]);
            if (faredata["Pax"].ToString() == "ADT")
            {
                string baseAmount, FuelSurcharge, GrossAmount, Commission;
                if (faredata["BasicAmount"].ToString() == "")
                    baseAmount = "0";
                else
                    baseAmount = faredata["BasicAmount"].ToString();
                if (faredata["FuelSurcharge"].ToString() == "")
                    FuelSurcharge = "0";
                else
                    FuelSurcharge = faredata["FuelSurcharge"].ToString();
                if (faredata["GrossAmount"].ToString() == "")
                    GrossAmount = "0";
                else
                    GrossAmount = faredata["GrossAmount"].ToString();
                if (faredata["Commission"].ToString() == "")
                    Commission = "0";
                else
                    Commission = faredata["Commission"].ToString();
                decimal[] fares = DomesticPrice_Result(Convert.ToDecimal(baseAmount), Convert.ToDecimal(FuelSurcharge), Convert.ToDecimal(GrossAmount), Convert.ToDecimal(Commission), 0);
                decimal mark_up = Convert.ToDecimal(Session["agentMarkup"]);
                decimal ticketfare = fares[5];
                decimal CompanyComm = Math.Round((fares[4] * CompanyComm_Perc) / 100);
                decimal AgentComm = Math.Round((fares[4] * AgentComm_Perc) / 100);
                decimal totalfare = ticketfare  + mark_up;
                DataRow dat = Lavidatatable.NewRow();
                dat[0] = e.Item.ItemIndex;
                dat[1] = totalfare;
                Lavidatatable.Rows.Add(dat);
                if (e.Item.ItemIndex == 0)
                {
                    minimumfare = totalfare;
                    maximumfare = totalfare;
                }
                if (totalfare < minimumfare)
                {
                    minimumfare = totalfare;
                }
                if (totalfare > maximumfare)
                {
                    maximumfare = totalfare;
                }
            }
        }
    }


    protected void myrepeater_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        try
        {
            if (e.CommandName == "Rule")
            {
                string output = (string)e.CommandArgument;
                string Air_ID = Convert.ToString(((Label)myrepeater.Items[Convert.ToInt32(output)].FindControl("LabelAirlinecode0")).Text);
                string Fly_ID = Convert.ToString(((Label)myrepeater.Items[Convert.ToInt32(output)].FindControl("LabelFlightNumber0")).Text);
                string Cls_ID = Convert.ToString(((Label)myrepeater.Items[Convert.ToInt32(output)].FindControl("LabelClassType0")).Text);
                string requ = @"<FareRequest>
<UserTrackId>" + Convert.ToString(Session["UserT_ID"]) + @"</UserTrackId>
<AirlineId>" + Air_ID + @"</AirlineId >
<FlightId>" + Fly_ID + @"</FlightId>
<ClassCode>" + Cls_ID + @"</ClassCode>
</FareRequest>";
                Hermes heman = new Hermes();
                string ase = heman.Dom_Fare_Rule(requ);
                string rule = string.Empty;
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(ase);
                XmlNodeList xNodeList = doc.SelectNodes("FareResponse");
                foreach (XmlNode Node in xNodeList)
                {
                    XmlNodeList xNodeList1 = Node.ChildNodes;
                    foreach (XmlNode xnode in xNodeList1)
                    {
                        if (xnode.Name == "Status")
                        {
                            if (xnode.InnerText == "1")
                            {
                                rule = xnode.NextSibling.InnerText;
                            }
                            else
                            {
                                rule = "No Rule is Available.";
                            }
                        }
                    }
                }
                litl_Rule.Text = rule;
ContentPlaceHolder myPlaceHolder = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
HtmlControl myControl = (HtmlControl)myPlaceHolder.FindControl("contioner_pop");
                myControl.Style.Add("display", "");
            }
            else
            {
                DataTable abc = new DataTable();
                string id = Convert.ToString(((Label)e.Item.FindControl("lbl_fare_segmrnt_id")).Text);
                DataTable charge = new DataTable();
                charge = (DataTable)Session["FareData"];
                DataTable seg_charge = (from asd in charge.AsEnumerable()
                                        where asd.Field<int>("AvailFlightItem_Id") == Convert.ToInt16(id)
                                        select asd).CopyToDataTable();
                ds = (DataSet)Session["Response"];
                Session["BookinRequest_OriginDestinationOption_OneWay_Depart"] = seg_charge;
                string Tax_Request = @"<TAXREQUEST>
<UserTrackId>" + ds.Tables["AvailabilityResponse"].Rows[0][0].ToString() + @"</UserTrackId>
<AirlineId>" + seg_charge.Rows[0]["CarrierCode"].ToString() + @"</AirlineId>
<FlightDetails>";
abc.Columns.Add(new DataColumn("ClassCode", typeof(string)));
                for (int i = 0; i < seg_charge.Rows.Count; i++)
{
Tax_Request = Tax_Request + @"<Item>
<FlightId>" + seg_charge.Rows[i]["FlightId"].ToString() + @"</FlightId>";
var cs_id = (from csid in ds.Tables["PaxFareDetails"].AsEnumerable()
where csid.Field<int>("SegFlightDetails_Id") == Convert.ToInt32(seg_charge.Rows[i]["SegFlightDetails_Id"])
select csid).ToArray();
Tax_Request = Tax_Request + @"<ClassCode>" + cs_id[0].ItemArray[0].ToString() + @"</ClassCode>";
  abc.Rows.Add(cs_id[0].ItemArray[0].ToString());
Tax_Request = Tax_Request + @"<AirlineId>" + seg_charge.Rows[i]["CarrierCode"].ToString() + @"</AirlineId>
<EticketFlag>1</EticketFlag>
<BasicAmount>" + seg_charge.Rows[i]["GrossAmount"].ToString() + @"</BasicAmount>
</Item>";
}

                Tax_Request = Tax_Request + @"</FlightDetails>
<TransFeeFlag>0</TransFeeFlag>
</TAXREQUEST>";

                Session["ClassCodeNew"] = abc;
                Hermes objhermes = new Hermes();
                DataSet ds_taxdetail = new DataSet();
                ds_taxdetail = objhermes.AirTaxDetails(Tax_Request);
                Session["Tax_Details"] = ds_taxdetail;
                Session["FareRule"] = "FareRule";
                decimal adultfare = 0;
                decimal childfare = 0;
                decimal infantfare = 0;
                decimal adultbase = 0;
                decimal childbase = 0;
                decimal infantbase = 0;
                decimal adultservice = 0;
                decimal childservice = 0;
                decimal infantservice = 0;
                decimal adultComm = 0;
                decimal childComm = 0;
                decimal infantComm = 0;
                decimal totalfare, totalbase, totalser,totalcomm;
                string AdultServiceAmount=Convert.ToString(ds_taxdetail.Tables["Adult"].Rows[0]["ServiceAmount"]);
                if (AdultServiceAmount == "")
                AdultServiceAmount = "0.0";
                adultfare = adultfare + Convert.ToDecimal(Convert.ToDecimal(ds_taxdetail.Tables["Adult"].Rows[0]["GrossAmount"]) * Convert.ToDecimal(Session["Adults"]));
                adultbase = adultbase + Convert.ToDecimal(Convert.ToDecimal(ds_taxdetail.Tables["Adult"].Rows[0]["BasicAmt"]) * Convert.ToDecimal(Session["Adults"]));
                adultservice = adultservice + (Convert.ToDecimal(AdultServiceAmount) * Convert.ToDecimal(Session["Adults"]));
                if (ds_taxdetail.Tables["Adult"].Rows[0]["Commission"].ToString() == "")
                    adultComm = adultComm + 0;
                else
                adultComm = adultComm + (Convert.ToDecimal(ds_taxdetail.Tables["Adult"].Rows[0]["Commission"]) * Convert.ToDecimal(Session["Adults"]));
                Session["Adultfare"] = adultfare;
                if (Convert.ToInt32(Session["Children"]) > 0)
                {
                    string childServiceAmount=Convert.ToString(ds_taxdetail.Tables["Child"].Rows[0]["ServiceAmount"]);
                    if (childServiceAmount == "")
                    childServiceAmount = "0.0";
                    childfare = childfare + Convert.ToDecimal(Convert.ToDecimal(ds_taxdetail.Tables["Child"].Rows[0]["GrossAmount"]) * Convert.ToDecimal(Session["Children"]));
                    childbase = childbase + Convert.ToDecimal(Convert.ToDecimal(ds_taxdetail.Tables["Child"].Rows[0]["BasicAmt"]) * Convert.ToDecimal(Session["Children"]));
                    childservice = childservice + Convert.ToDecimal(Convert.ToDecimal(childServiceAmount) * Convert.ToDecimal(Session["Children"]));
                    if (ds_taxdetail.Tables["Child"].Rows[0]["Commission"].ToString() == "")
                        childComm = childComm + 0;
                    else
                    childComm = childComm + Convert.ToDecimal(Convert.ToDecimal(ds_taxdetail.Tables["Child"].Rows[0]["Commission"]) * Convert.ToDecimal(Session["Children"]));
                    Session["Childfare"] = childfare;
                }
                if (Convert.ToInt32(Session["Infants"]) > 0)
                { 
                    string infantServiceAmount=Convert.ToString(ds_taxdetail.Tables["Infant"].Rows[0]["ServiceAmount"]);
                    if (infantServiceAmount == "")
                    infantServiceAmount = "0.0";
                    infantfare = infantfare + Convert.ToDecimal(Convert.ToDecimal(ds_taxdetail.Tables["Infant"].Rows[0]["GrossAmount"]) * Convert.ToDecimal(Session["Infants"]));
                    infantbase = infantbase + Convert.ToDecimal(Convert.ToDecimal(ds_taxdetail.Tables["Infant"].Rows[0]["BasicAmt"]) * Convert.ToDecimal(Session["Infants"]));
                    infantservice = infantservice + Convert.ToDecimal(Convert.ToDecimal(infantServiceAmount) * Convert.ToDecimal(Session["Infants"]));
                    if (ds_taxdetail.Tables["Infant"].Rows[0]["Commission"].ToString() == "")
                        infantComm = infantComm + 0;
                    else
                    infantComm = infantComm + Convert.ToDecimal(Convert.ToDecimal(ds_taxdetail.Tables["Infant"].Rows[0]["Commission"]) * Convert.ToDecimal(Session["Infants"]));
                    Session["Infantfare"] = infantfare;
                }
                totalfare = adultfare + childfare + infantfare;
                totalbase = adultbase + childbase + infantbase;
                totalser = adultservice + childservice + infantservice;
                totalcomm = adultComm + childComm + infantComm;
                decimal[] fares = DomesticPrice(totalbase, totalfare, totalser, 0, 0);
                decimal mark_up = Convert.ToDecimal(Session["agentMarkup"]);
                decimal all_markup = Convert.ToDecimal(Session["allMarkup"]);
                Session["AirportTax"] = fares[1];
                Session["Basefare"] = fares[0];
                Session["ServiceTax"] = fares[2];
                Session["TxnCharge"] = fares[3];
                Session["BookingDiscount"] = fares[4];
                //B2B objbeb = new B2B();
                 decimal CompanyComm_Perc = 20;
                 decimal AgentComm_Perc = 80;
                decimal price = fares[5];
                Session["totalPrice"] = price;
                decimal CompanyComm = Math.Round((totalcomm * CompanyComm_Perc) / 100);
                decimal AgentComm = Math.Round((totalcomm * AgentComm_Perc) / 100);
                Session["Dom_Ticket_Price"] = fares[5] + mark_up + all_markup;
                Session["Dom_Ticket_detect"] = fares[5] - AgentComm+all_markup;
                Session["Dom_AgentComm"] = AgentComm + mark_up;
                Session["Dom_CompanyComm"] = CompanyComm+all_markup;
               // RemoveSession();
                Response.Redirect("step3.aspx", false);
            }
        }
        catch (Exception ex)
        {
            obj_AirEpointSupport.WriteToLog(ex.Message, "OneWayResult", "myrepeater_ItemCommand__" + Convert.ToString(Session["partnerRefId"]));
            Response.Redirect("../User/IndexDom.aspx?s=exception");
        }
    }
    public decimal[] DomesticPrice(decimal ActualBaseFare, decimal Gross, decimal STax, decimal TDiscount, decimal TCharge)
    {
        decimal Tax = Gross - ActualBaseFare;
        decimal[] fares = new decimal[6];
        fares[0] = ActualBaseFare;
        fares[1] = Tax;
        fares[2] = STax;
        fares[3] = TCharge;
        fares[4] = TCharge;
        decimal totalfare = (fares[0] + fares[1] + fares[2] + fares[3]) - fares[4];
        fares[5] = totalfare;
        return fares;
    }


    private void Fill_Initial()
    {
        if (Convert.ToString(Session["Trip"]) == "One")
        {
            RadioButtononeway.Checked = true;
            RadioButtonround.Checked = false;
            RadioButtonspecial.Checked = false;
        }
        else if (Convert.ToString(Session["Trip"]) == "Round")
        {
            RadioButtononeway.Checked = false;
            RadioButtonround.Checked = true;
            RadioButtonspecial.Checked = false;
        }
        else if (Convert.ToString(Session["Trip"]) == "SplFare")
        {
            RadioButtononeway.Checked = false;
            RadioButtonround.Checked = false;
            RadioButtonspecial.Checked = true;
        }
        ddl_adult.SelectedValue = Convert.ToString(Session["Adults"]);
        ddl_child.SelectedValue = Convert.ToString(Session["Children"]);
        ddl_infant.SelectedValue = Convert.ToString(Session["Infants"]);
        ddl_class.SelectedValue = Convert.ToString(Session["Class"]);
        txt_departdate.Text = Convert.ToDateTime(Session["DepartureDate"]).ToString("dd-MMM-yyyy");
        txt_arrivaldate.Text = Convert.ToDateTime(Session["ReturnDate"]).ToString("dd-MMM-yyyy");
    }

    protected void linkbuttonprefferd_Click(object sender, EventArgs e)
    {
        int x = obj_AirEpointSupport.CheckSearchFlight(txt_from.Text, txt_to.Text);
        if (x == 1)
        {
            if (obj_AirEpointSupport.CheckSourceDestination(txt_from.Text, txt_to.Text) == "INAIR" || obj_AirEpointSupport.CheckSourceDestination(txt_from.Text, txt_to.Text) == "SETO")
            {
               
                ViewState["flighttypelavi"] = "INAIR";
            }
            else
            {
               
                ViewState["flighttypelavi"] = "DOM";
            }
        }
        else
        {
            modalpopup1.Show();
            lblmsg.Visible = true;
            ViewState["flighttypelavi"] = "";
        }
    }
    protected void btn_sort_Click(object sender, EventArgs e)
    {
        sortloop("asc");
    }
    protected void btn_sort0_Click(object sender, EventArgs e)
    {
        sortloop("desc");
    }
    public decimal[] DomesticPrice_Result(decimal ActualBaseFare, decimal Tax, decimal STax, decimal TDiscount, decimal TCharge)
    {
        decimal[] fares = new decimal[6];
        fares[0] = ActualBaseFare;
        fares[1] = STax - ActualBaseFare;
        fares[2] = 0;
        fares[3] = TCharge;
        fares[4] = TDiscount;
        decimal totalfare = (fares[0] + fares[1] + fares[2] + fares[3]) - fares[4];
        fares[5] = STax;
        return fares;
    }
}
