Esempio n. 1
0
 public void RemoveSubsidiaryAirline(SubsidiaryAirline subsidiary)
 {
     Subsidiaries.Remove(subsidiary);
 }
        private static void LoadAirline(XmlElement airlineNode)
        {
            // chs, 2011-21-10 changed for the possibility of creating a new airline
            string airlineName = airlineNode.Attributes["name"].Value;
            string airlineIATA = airlineNode.Attributes["code"].Value;

            Boolean airlineIsSubsidiary = Convert.ToBoolean(airlineNode.Attributes["subsidiary"].Value);
            Country airlineCountry = Countries.GetCountry(airlineNode.Attributes["country"].Value);
            string color = airlineNode.Attributes["color"].Value;
            string airlineCEO = airlineNode.Attributes["CEO"].Value;
            double money = Convert.ToDouble(airlineNode.Attributes["money"].Value, new CultureInfo("de-DE", false));
            int reputation = Convert.ToInt16(airlineNode.Attributes["reputation"].Value);
            var mentality =
                (Airline.AirlineMentality)
                Enum.Parse(typeof (Airline.AirlineMentality), airlineNode.Attributes["mentality"].Value);
            var market =
                (AirlineFocus) Enum.Parse(typeof (AirlineFocus), airlineNode.Attributes["market"].Value);
            var license =
                (Airline.AirlineLicense)
                Enum.Parse(typeof (Airline.AirlineLicense), airlineNode.Attributes["license"].Value);
            Route.RouteType routefocus = airlineNode.HasAttribute("routefocus")
                                             ? (Route.RouteType) Enum.Parse(typeof (Route.RouteType), airlineNode.Attributes["routefocus"].Value)
                                             : Route.RouteType.Passenger;

            Boolean isReal = !airlineNode.HasAttribute("real") || Convert.ToBoolean(airlineNode.Attributes["real"].Value);
            int founded = airlineNode.HasAttribute("founded")
                              ? Convert.ToInt16(airlineNode.Attributes["founded"].Value)
                              : 1950;
            int folded = airlineNode.HasAttribute("folded")
                             ? Convert.ToInt16(airlineNode.Attributes["folded"].Value)
                             : 2199;

            Airline airline;
            if (airlineIsSubsidiary)
            {
                Airline parent = Airlines.GetAirline(airlineNode.Attributes["parentairline"].Value);
                airline = new SubsidiaryAirline(
                    parent,
                    new AirlineProfile(airlineName, airlineIATA, color, airlineCEO, isReal, founded, folded),
                    mentality,
                    market,
                    license,
                    routefocus) {Profile = {Country = airlineCountry}};
                parent.AddSubsidiaryAirline((SubsidiaryAirline) airline);
            }
            else
            {
                airline =
                    new Airline(
                        new AirlineProfile(airlineName, airlineIATA, color, airlineCEO, isReal, founded, folded),
                        mentality,
                        market,
                        license,
                        routefocus) {Profile = {Country = airlineCountry}};
            }
            if (airlineNode.HasAttribute("logo"))
            {
                string logo = AppSettings.GetDataPath() + "\\graphics\\airlinelogos\\"
                              + airlineNode.Attributes["logo"].Value;

                airline.Profile.AddLogo(new AirlineLogo(logo));
            }
            airline.Fleet.Clear();
            airline.Airports.Clear();
            airline.Routes.Clear();
            airline.Alliances.Clear();

            airline.Money = money;
            airline.Reputation = reputation;

            XmlNodeList logosList = airlineNode.SelectNodes("logos/logo");

            if (logosList != null)
                foreach (XmlElement logoElement in logosList)
                {
                    int logoFromYear = Convert.ToInt16(logoElement.Attributes["from"].Value);
                    int logoToYear = Convert.ToInt16(logoElement.Attributes["to"].Value);
                    string logoPath = logoElement.Attributes["path"].Value;

                    if (!File.Exists(logoPath))
                    {
                        logoPath = AppSettings.GetDataPath() + "\\graphics\\airlinelogos\\"
                                   + logoPath.Substring(logoPath.LastIndexOf('\\') + 1);
                    }

                    airline.Profile.AddLogo(new AirlineLogo(logoFromYear, logoToYear, logoPath));
                }

            var airlineContractNode = (XmlElement) airlineNode.SelectSingleNode("contract");
            if (airlineContractNode != null)
            {
                Manufacturer contractManufacturer =
                    Manufacturers.GetManufacturer(airlineContractNode.Attributes["manufacturer"].Value);
                DateTime contractSigningDate = DateTime.Parse(
                    airlineContractNode.Attributes["signingdate"].Value,
                    new CultureInfo("de-DE", false));
                int contractLength = Convert.ToInt16(airlineContractNode.Attributes["length"].Value);
                double contractDiscount = Convert.ToDouble(
                    airlineContractNode.Attributes["discount"].Value,
                    new CultureInfo("de-DE", false));
                int contractAirliners = Convert.ToInt16(airlineContractNode.Attributes["airliners"].Value);

                var contract = new ManufacturerContract(
                    contractManufacturer,
                    contractSigningDate,
                    contractLength,
                    contractDiscount) {PurchasedAirliners = contractAirliners};

                airline.Contract = contract;
            }

            // chs, 2011-17-10 added for loading of passenger happiness
            var airlinePassengerNode = (XmlElement) airlineNode.SelectSingleNode("passengerhappiness");
            if (airlinePassengerNode != null)
            {
                double passengerHappiness = Convert.ToDouble(
                    airlinePassengerNode.Attributes["value"].Value,
                    new CultureInfo("de-DE", false));
                PassengerHelpers.SetPassengerHappiness(airline, passengerHappiness);
            }

            XmlNodeList airlineFacilitiesList = airlineNode.SelectNodes("facilities/facility");
            if (airlineFacilitiesList != null)
                foreach (XmlElement airlineFacilityNode in airlineFacilitiesList)
                {
                    string airlineFacility = airlineFacilityNode.Attributes["uid"].Value;

                    airline.AddFacility(AirlineFacilities.GetFacility(airlineFacility));
                }

            XmlNodeList airlinePoliciesList = airlineNode.SelectNodes("policies/policy");

            foreach (XmlElement airlinePolicyNode in airlinePoliciesList)
            {
                string policyName = airlinePolicyNode.Attributes["name"].Value;
                object policyValue = airlinePolicyNode.Attributes["value"].Value;

                int number;
                airline.AddAirlinePolicy(int.TryParse(policyValue.ToString(), out number) ? new AirlinePolicy(policyName, number) : new AirlinePolicy(policyName, policyValue));
            }

            XmlNodeList airlineLoanList = airlineNode.SelectNodes("loans/loan");
            foreach (XmlElement airlineLoanNode in airlineLoanList)
            {
                DateTime date = DateTime.Parse(
                    airlineLoanNode.Attributes["date"].Value,
                    new CultureInfo("de-DE", false));
                double rate = Convert.ToDouble(
                    airlineLoanNode.Attributes["rate"].Value,
                    new CultureInfo("de-DE", false));
                double amount = Convert.ToDouble(
                    airlineLoanNode.Attributes["amount"].Value,
                    new CultureInfo("de-DE", false));
                int length = Convert.ToInt16(airlineLoanNode.Attributes["length"].Value);
                double payment = Convert.ToDouble(
                    airlineLoanNode.Attributes["payment"].Value,
                    new CultureInfo("de-DE", false));

                var loan = new Loan(date, amount, length, rate) {PaymentLeft = payment};

                airline.AddLoan(loan);
            }

            XmlNodeList airlineStatList = airlineNode.SelectNodes("stats/stat");
            foreach (XmlElement airlineStatNode in airlineStatList)
            {
                int year = Convert.ToInt32(airlineStatNode.Attributes["year"].Value);
                string airlineStatType = airlineStatNode.Attributes["type"].Value;
                double value = Convert.ToDouble(
                    airlineStatNode.Attributes["value"].Value,
                    new CultureInfo("de-DE", false));

                airline.Statistics.SetStatisticsValue(year, StatisticsTypes.GetStatisticsType(airlineStatType), value);
            }

            XmlNodeList airlineInvoiceList = airlineNode.SelectNodes("invoices/invoice");

            foreach (XmlElement airlineInvoiceNode in airlineInvoiceList)
            {
                var type =
                    (Invoice.InvoiceType)
                    Enum.Parse(typeof (Invoice.InvoiceType), airlineInvoiceNode.Attributes["type"].Value);
                int invoiceYear = Convert.ToInt16(airlineInvoiceNode.Attributes["year"].Value);
                int invoiceMonth = Convert.ToInt16(airlineInvoiceNode.Attributes["month"].Value);
                double invoiceAmount = Convert.ToDouble(
                    airlineInvoiceNode.Attributes["amount"].Value,
                    new CultureInfo("de-DE", false));

                airline.SetInvoice(type, invoiceYear, invoiceMonth, 1, invoiceAmount);
            }

            // chs, 2011-13-10 added for loading of airline advertisements
            XmlNodeList advertisementList = airlineNode.SelectNodes("advertisements/advertisement");

            foreach (XmlElement advertisementNode in advertisementList)
            {
                var type =
                    (AdvertisementType.AirlineAdvertisementType)
                    Enum.Parse(
                        typeof (AdvertisementType.AirlineAdvertisementType),
                        advertisementNode.Attributes["type"].Value);
                string advertisementName = advertisementNode.Attributes["name"].Value;

                airline.SetAirlineAdvertisement(AdvertisementTypes.GetType(type, advertisementName));
            }
            // chs, 2011-17-10 added for loading of fees
            var fees = new AirlineFees();

            XmlNodeList airlineFeeList = airlineNode.SelectNodes("fees/fee");
            foreach (XmlElement feeNode in airlineFeeList)
            {
                string feeType = feeNode.Attributes["type"].Value;
                double feeValue = Convert.ToDouble(feeNode.Attributes["value"].Value, new CultureInfo("de-DE", false));

                fees.SetValue(FeeTypes.GetType(feeType), feeValue);
            }

            airline.Fees = fees;

            XmlNodeList flightschoolsList = airlineNode.SelectNodes("flightschools/flightschool");

            foreach (XmlElement flightschoolNode in flightschoolsList)
            {
                string fsID = flightschoolNode.Attributes["id"].Value;
                Airport fsAirport = Airports.GetAirportFromID(flightschoolNode.Attributes["airport"].Value);

                var fs = new FlightSchool(fsAirport) {ID = fsID};

                XmlNodeList aircraftsList = flightschoolNode.SelectNodes("trainingaircrafts/trainingaircraft");

                foreach (XmlElement aircraftNode in aircraftsList)
                {
                    TrainingAircraftType aircraftType =
                        TrainingAircraftTypes.GetAircraftType(aircraftNode.Attributes["type"].Value);
                    DateTime aircraftDate = DateTime.Parse(
                        aircraftNode.Attributes["date"].Value,
                        new CultureInfo("de-DE", false));

                    fs.AddTrainingAircraft(new TrainingAircraft(aircraftType, aircraftDate, fs));
                }

                XmlNodeList studentsList = flightschoolNode.SelectNodes("students/student");

                foreach (XmlElement studentNode in studentsList)
                {
                    string firstname = studentNode.Attributes["firstname"].Value;
                    string lastname = studentNode.Attributes["lastname"].Value;
                    DateTime birthdate = DateTime.Parse(
                        studentNode.Attributes["birthdate"].Value,
                        new CultureInfo("de-DE", false));
                    Town town = Towns.GetTown(studentNode.Attributes["town"].Value);
                    DateTime startdate = DateTime.Parse(
                        studentNode.Attributes["startdate"].Value,
                        new CultureInfo("de-DE", false));

                    fs.AddStudent(
                        new PilotStudent(
                            new PilotProfile(firstname, lastname, birthdate, town),
                            startdate,
                            null,
                            null,
                            ""));
                }

                airline.AddFlightSchool(fs);
            }

            XmlNodeList airlineFleetList = airlineNode.SelectNodes("fleet/airliner");

            foreach (XmlElement airlineAirlinerNode in airlineFleetList)
            {
                Airliner airliner = Airliners.GetAirliner(airlineAirlinerNode.Attributes["airliner"].Value);

                string fAirlinerName = airlineAirlinerNode.Attributes["name"].Value;
                Airport homebase = Airports.GetAirport(airlineAirlinerNode.Attributes["homebase"].Value);
                var purchasedtype =
                    (FleetAirliner.PurchasedType)
                    Enum.Parse(
                        typeof (FleetAirliner.PurchasedType),
                        airlineAirlinerNode.Attributes["purchased"].Value);
                DateTime purchasedDate = DateTime.Parse(
                    airlineAirlinerNode.Attributes["date"].Value,
                    new CultureInfo("de-DE", false));
                var status =
                    (FleetAirliner.AirlinerStatus)
                    Enum.Parse(typeof (FleetAirliner.AirlinerStatus), airlineAirlinerNode.Attributes["status"].Value);
                DateTime groundedDate = DateTime.Parse(
                    airlineAirlinerNode.Attributes["groundeddate"].Value,
                    new CultureInfo("de-DE", false));

                // Coordinate latitude = Coordinate.Parse(airlineAirlinerNode.Attributes["latitude"].Value);
                //Coordinate longitude = Coordinate.Parse(airlineAirlinerNode.Attributes["longitude"].Value);

                string[] latitude = airlineAirlinerNode.Attributes["value"].Value.Split('°', '\'', '\'');
                string[] longitude = airlineAirlinerNode.Attributes["value"].Value.Split('°', '\'', '\'');
                var coords = new int[6];
                foreach (string l in latitude)
                {
                    int c = 0;
                    int.TryParse(l, out coords[c]);
                    c++;
                }

                foreach (string l in longitude)
                {
                    int c = 3;
                    int.TryParse(l, out coords[c]);
                    c++;
                }

                //cleaning up
                latitude = null;
                longitude = null;

                var pos = new GeoCoordinate(
                    MathHelpers.DMStoDeg(coords[0], coords[1], coords[2]),
                    MathHelpers.DMStoDeg(coords[3], coords[4], coords[5]));

                var fAirliner = new FleetAirliner(purchasedtype, purchasedDate, airline, airliner, homebase) {CurrentPosition = null, Status = status, GroundedToDate = groundedDate};

                XmlNodeList airlinerStatList = airlineAirlinerNode.SelectNodes("stats/stat");

                foreach (XmlElement airlinerStatNode in airlinerStatList)
                {
                    int year = Convert.ToInt32(airlinerStatNode.Attributes["year"].Value);
                    string statType = airlinerStatNode.Attributes["type"].Value;
                    double statValue = Convert.ToDouble(
                        airlinerStatNode.Attributes["value"].Value,
                        new CultureInfo("de-DE", false));
                    fAirliner.Statistics.SetStatisticsValue(
                        year,
                        StatisticsTypes.GetStatisticsType(statType),
                        statValue);
                }

                airline.AddAirliner(fAirliner);
            }
            XmlNodeList routeList = airlineNode.SelectNodes("routes/route");

            foreach (XmlElement routeNode in routeList)
            {
                airline.AddRoute(LoadRoute(routeNode, airline));
            }

            XmlNodeList flightNodes = airlineNode.SelectNodes("flights/flight");
            foreach (XmlElement flightNode in flightNodes)
            {
                FleetAirliner airliner =
                    airline.Fleet.Find(a => a.Airliner.ID == flightNode.Attributes["airliner"].Value);

                if (airliner != null)
                {
                    Route route = airline.Routes.Find(r => r.Id == flightNode.Attributes["route"].Value);

                    if (route != null)
                    {
                        string destination = flightNode.Attributes["destination"].Value;

                        var day = (DayOfWeek) Enum.Parse(typeof (DayOfWeek), flightNode.Attributes["day"].Value);
                        TimeSpan time = TimeSpan.Parse(flightNode.Attributes["time"].Value);
                        DateTime flightTime = DateTime.Parse(
                            flightNode.Attributes["flighttime"].Value,
                            new CultureInfo("de-DE", false));

                        var stopoverNode = (XmlElement) flightNode.SelectSingleNode("stopover");

                        Boolean isStopoverFlight = stopoverNode != null;

                        if (destination != "Service")
                        {
                            RouteTimeTableEntry rtte =
                                route.TimeTable.Entries.Find(
                                    e => e.Destination.FlightCode == destination && e.Day == day && e.Time == time);

                            var currentFlight = new Flight(rtte) {FlightTime = flightTime};
                            currentFlight.Classes.Clear();

                            if (currentFlight.IsPassengerFlight())
                            {
                                XmlNodeList flightClassList = flightNode.SelectNodes("flightclasses/flightclass");

                                foreach (XmlElement flightClassNode in flightClassList)
                                {
                                    var airlinerClassType =
                                        (AirlinerClass.ClassType)
                                        Enum.Parse(
                                            typeof (AirlinerClass.ClassType),
                                            flightClassNode.Attributes["type"].Value);
                                    int flightPassengers =
                                        Convert.ToInt16(flightClassNode.Attributes["passengers"].Value);

                                    currentFlight.Classes.Add(
                                        new FlightAirlinerClass(
                                            ((PassengerRoute) route).GetRouteAirlinerClass(airlinerClassType),
                                            flightPassengers));
                                }
                            }
                            if (currentFlight.IsCargoFlight())
                            {
                                var flightCargoNode = (XmlElement) flightNode.SelectSingleNode("flightcargo");
                                double flightCargo = Convert.ToDouble(
                                    flightCargoNode.Attributes["cargo"].Value,
                                    new CultureInfo("de-DE", false));

                                currentFlight.Cargo = flightCargo;
                            }
                            if (isStopoverFlight)
                            {
                                int currentStopoverFlight =
                                    Convert.ToInt32(stopoverNode.Attributes["currentflight"].Value);

                                XmlNodeList stopoverClassesList = stopoverNode.SelectNodes("classes/class");

                                var stopEntryAllClasses =
                                    new Dictionary<RouteTimeTableEntry, List<FlightAirlinerClass>>();

                                foreach (XmlElement stopoverClassNode in stopoverClassesList)
                                {
                                    RouteTimeTableEntry stopoverEntry =
                                        airline.Routes.SelectMany(r => r.TimeTable.Entries)
                                               .ToList()
                                               .Find(e => e.ID == stopoverClassNode.Attributes["id"].Value);

                                    XmlNodeList stopoverFlightClassList =
                                        stopoverClassNode.SelectNodes("flightclasses/flightclass");

                                    List<FlightAirlinerClass> stopoverFlightClasses = (from XmlElement stopoverFlightClassNode in stopoverFlightClassList
                                                                                       let stopoverAirlinerClassType =
                                                                                           (AirlinerClass.ClassType)
                                                                                           Enum.Parse(typeof (AirlinerClass.ClassType), stopoverFlightClassNode.Attributes["type"].Value)
                                                                                       let stopoverFlightPassengers = Convert.ToInt16(stopoverFlightClassNode.Attributes["passengers"].Value)
                                                                                       select
                                                                                           new FlightAirlinerClass(((PassengerRoute) route).GetRouteAirlinerClass(stopoverAirlinerClassType),
                                                                                                                   stopoverFlightPassengers)).ToList();

                                    stopEntryAllClasses.Add(stopoverEntry, stopoverFlightClasses);
                                }

                                XmlNodeList stopoverCargosList = stopoverNode.SelectNodes("cargos/cargo");

                                var stopEntryAllCargo = new Dictionary<RouteTimeTableEntry, double>();

                                foreach (XmlElement stopoverCargoNode in stopoverCargosList)
                                {
                                    RouteTimeTableEntry stopoverEntry =
                                        airline.Routes.SelectMany(r => r.TimeTable.Entries)
                                               .ToList()
                                               .Find(e => e.ID == stopoverCargoNode.Attributes["id"].Value);
                                    double cargoValue = Convert.ToDouble(
                                        stopoverCargoNode.Attributes["value"].Value,
                                        new CultureInfo("de-DE", false));

                                    stopEntryAllCargo.Add(stopoverEntry, cargoValue);
                                }

                                var stopoverFlight = new StopoverFlight(rtte)
                                    {
                                        AllClasses = stopEntryAllClasses,
                                        AllCargo = stopEntryAllCargo,
                                        CurrentFlight = currentStopoverFlight,
                                        FlightTime = currentFlight.FlightTime,
                                        Classes = currentFlight.Classes
                                    };

                                airliner.CurrentFlight = stopoverFlight;
                            }
                            else
                            {
                                airliner.CurrentFlight = currentFlight;
                            }
                        }
                        else
                        {
                            airliner.CurrentFlight =
                                new Flight(
                                    new RouteTimeTableEntry(
                                        route.TimeTable,
                                        GameObject.GetInstance().GameTime.DayOfWeek,
                                        GameObject.GetInstance().GameTime.TimeOfDay,
                                        new RouteEntryDestination(airliner.Homebase, "Service", null),
                                        null));

                            airliner.Status = FleetAirliner.AirlinerStatus.OnService;
                        }
                    }
                    else
                    {
                        airliner.Status = FleetAirliner.AirlinerStatus.Stopped;
                    }
                }
            }
            Airlines.AddAirline(airline);
        }
Esempio n. 3
0
 public void AddSubsidiaryAirline(SubsidiaryAirline subsidiary)
 {
     Subsidiaries.Add(subsidiary);
 }
        public void removeSubsidiaryAirline(SubsidiaryAirline airline)
        {
            Subsidiaries.Remove(airline);
            AirlineAirlines.Remove(airline);

            FundsAirlines.Remove(airline);
        }
        //adds a subsidiary airline
        public void addSubsidiaryAirline(SubsidiaryAirline airline)
        {
            Subsidiaries.Add(airline);

            AirlineHelpers.AddSubsidiaryAirline(
                GameObject.GetInstance().MainAirline,
                airline,
                airline.Money,
                airline.Airports[0]);

            MaxSubsidiaryMoney = Airline.Money / 2;

            AirlineAirlines.Add(airline);

            FundsAirlines.Add(airline);
        }
        //creates a subsidiary airline for an airline
        public static SubsidiaryAirline CreateSubsidiaryAirline(Airline airline, double money, string name, string iata, Airline.AirlineMentality mentality, AirlineFocus market,
                                                                Route.RouteType routefocus, Airport homebase)
        {
            var profile = new AirlineProfile(name, iata, airline.Profile.Color, airline.Profile.CEO, true, GameObject.GetInstance().GameTime.Year, 2199) {Country = homebase.Profile.Country};

            var sAirline = new SubsidiaryAirline(airline, profile, mentality, market, airline.License, routefocus);

            AddSubsidiaryAirline(airline, sAirline, money, homebase);

            return sAirline;
        }
        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            string iata = this.txtIATA.Text.ToUpper().Trim();
            string name = this.txtAirlineName.Text.Trim();
            var airport = (Airport)this.cbAirport.SelectedItem;
            string color = ((PropertyInfo)this.cbColor.SelectedItem).Name;
            Route.RouteType focus = this.rbPassengerType.IsChecked.Value
                ? Route.RouteType.Passenger
                : Route.RouteType.Cargo;

            var profile = new AirlineProfile(
                       name,
                       iata,
                       color,
                       GameObject.GetInstance().MainAirline.Profile.CEO,
                       false,
                       GameObject.GetInstance().GameTime.Year,
                       2199);

            profile.Country = airport.Profile.Country; //GameObject.GetInstance().MainAirline.Profile.Country;<

            var subAirline = new SubsidiaryAirline(
                GameObject.GetInstance().MainAirline,
                profile,
                Airline.AirlineMentality.Safe,
                AirlineFocus.Local,
                Airline.AirlineLicense.Domestic,
                focus);

            subAirline.AddAirport(airport);
            subAirline.Profile.Logos.Clear();
            subAirline.Profile.AddLogo(new AirlineLogo(this.logoPath));
            subAirline.Money = this.slMoney.Value;

            this.Selected = subAirline;
            this.Close();
        }
        //adds a subsidiary airline to an airline
        public static void AddSubsidiaryAirline(Airline airline, SubsidiaryAirline sAirline, double money, Airport airportHomeBase)
        {
            Terminal.TerminalType terminaltype = sAirline.AirlineRouteFocus == Route.RouteType.Cargo ? Terminal.TerminalType.Cargo : Terminal.TerminalType.Passenger;
            AddAirlineInvoice(airline, GameObject.GetInstance().GameTime, Invoice.InvoiceType.AirlineExpenses, -money);
            sAirline.Money = money;
            sAirline.StartMoney = money;

            sAirline.Fees = new AirlineFees();

            airline.AddSubsidiaryAirline(sAirline);

            if (!AirportHelpers.HasFreeGates(airportHomeBase, sAirline, terminaltype) && airportHomeBase.Terminals.GetFreeGates(terminaltype) > 1)
            {
                AirportHelpers.RentGates(airportHomeBase, sAirline, AirportContract.ContractType.Full, terminaltype, 2);
                //sets all the facilities at an airport to none for all airlines
                foreach (Airport airport in Airports.GetAllAirports())
                {
                    foreach (AirportFacility.FacilityType type in Enum.GetValues(typeof (AirportFacility.FacilityType)))
                    {
                        AirportFacility noneFacility = AirportFacilities.GetFacilities(type).Find((facility => facility.TypeLevel == 0));

                        airport.AddAirportFacility(sAirline, noneFacility, GameObject.GetInstance().GameTime);
                    }
                }


                AirportFacility serviceFacility = AirportFacilities.GetFacilities(AirportFacility.FacilityType.Service).Find(f => f.TypeLevel == 1);
                AirportFacility checkinFacility = AirportFacilities.GetFacilities(AirportFacility.FacilityType.CheckIn).Find(f => f.TypeLevel == 1);

                airportHomeBase.AddAirportFacility(sAirline, serviceFacility, GameObject.GetInstance().GameTime);
                airportHomeBase.AddAirportFacility(sAirline, checkinFacility, GameObject.GetInstance().GameTime);
            }

            foreach (AirlinePolicy policy in airline.Policies)
                sAirline.AddAirlinePolicy(policy);

            Airlines.AddAirline(sAirline);
        }
        //closes a subsidiary airline for an airline
        public static void CloseSubsidiaryAirline(SubsidiaryAirline airline)
        {
            AddAirlineInvoice(airline.Airline, GameObject.GetInstance().GameTime, Invoice.InvoiceType.AirlineExpenses, airline.Money);

            airline.Airline.RemoveSubsidiaryAirline(airline);
            Airlines.RemoveAirline(airline);

            List<FleetAirliner> fleet = airline.Fleet;

            foreach (FleetAirliner t in fleet)
            {
                t.Airliner.Airline = airline.Airline;
                airline.Airline.AddAirliner(t);
            }

            List<Airport> airports = airline.Airports;

            foreach (Airport t in airports)
            {
                List<AirportContract> contracts = t.GetAirlineContracts(airline);

                foreach (AirportContract t1 in contracts)
                {
                    t1.Airline = airline.Airline;
                }

                if (!airline.Airline.Airports.Contains(t))
                {
                    airline.Airline.AddAirport(t);
                }

                foreach (AirportFacility facility in t.GetCurrentAirportFacilities(airline))
                {
                    if (t.GetAirlineAirportFacility(airline.Airline, facility.Type).Facility.TypeLevel < facility.TypeLevel)
                        t.AddAirportFacility(airline.Airline, facility, GameObject.GetInstance().GameTime);
                }

                t.ClearFacilities(airline);
            }
            //moves the terminals from the subsidiary to the parent airline
            foreach (Airport airport in airline.Airports)
            {
                IEnumerable<Terminal> terminals = airport.Terminals.GetTerminals().Where(t => t.Airline == airline);

                foreach (Terminal terminal in terminals)
                    terminal.Airline = airline.Airline;
            }
        }
        //launches a subsidiary to operate on its own
        public static void MakeSubsidiaryAirlineIndependent(SubsidiaryAirline airline)
        {
            airline.Airline.RemoveSubsidiaryAirline(airline);

            airline.Airline = null;

            airline.Profile.CEO =
                $"{Names.GetInstance().GetRandomFirstName(airline.Profile.Country)} {Names.GetInstance().GetRandomLastName(airline.Profile.Country)}";

            if (!Airlines.ContainsAirline(airline))
                Airlines.AddAirline(airline);
        }
        private static void DoDailyUpdate()
        {
            //Clear stats when it on daily update
            if (Infrastructure.Settings.GetInstance().ClearStats == Intervals.Daily)
            {
                ClearAllUsedStats();
            }

            //Auto save when it on daily
            if (Infrastructure.Settings.GetInstance().AutoSave == Intervals.Daily)
            {
                SerializedLoadSaveHelpers.SaveGame("autosave");
            }

            //Clearing stats as an RAM work-a-round
            Airports.GetAllAirports().ForEach(a => a.ClearDestinationPassengerStatistics());
            Airports.GetAllAirports().ForEach(a => a.ClearDestinationCargoStatistics());

            List<Airline> humanAirlines = Airlines.GetAirlines(a => a.IsHuman);

            //Console.WriteLine(GameObject.GetInstance().GameTime.ToShortDateString() + ": " + DateTime.Now.Subtract(LastTime).TotalMilliseconds + " ms." + " : routes: " + totalRoutes + " airliners on route: " + totalAirlinersOnRoute);

            _lastTime = DateTime.Now;
            //changes the fuel prices
            double fuelDiff = Inflations.GetInflation(GameObject.GetInstance().GameTime.Year + 1).FuelPrice
                              - Inflations.GetInflation(GameObject.GetInstance().GameTime.Year).FuelPrice;
            double fuelPrice = (Rnd.NextDouble()*(fuelDiff/4));

            GameObject.GetInstance().FuelPrice =
                Inflations.GetInflation(GameObject.GetInstance().GameTime.Year).FuelPrice + fuelPrice;
            //checks for airports due to close in 14 days
            List<Airport> closingAirports =
                Airports.GetAllAirports(
                    a =>
                    a.Profile.Period.To.ToShortDateString()
                    == GameObject.GetInstance().GameTime.AddDays(14).ToShortDateString());
            List<Airport> openingAirports =
                Airports.GetAllAirports(
                    a =>
                    a.Profile.Period.From.ToShortDateString()
                    == GameObject.GetInstance().GameTime.AddDays(14).ToShortDateString());

            foreach (Airport airport in closingAirports)
            {
                Airport reallocatedAirport = openingAirports.Find(a => a.Profile.Town == airport.Profile.Town);

                if (reallocatedAirport == null)
                {
                    GameObject.GetInstance()
                              .NewsBox.AddNews(
                                  new News(
                                      News.NewsType.AirportNews,
                                      GameObject.GetInstance().GameTime,
                                      "Airport closing",
                                      $"The airport [LI airport={airport.Profile.IATACode}]({new AirportCodeConverter().Convert(airport)}) is closing in 14 days.\n\rPlease move all routes to another destination."));
                }
                else
                {
                    GameObject.GetInstance()
                              .NewsBox.AddNews(
                                  new News(
                                      News.NewsType.AirportNews,
                                      GameObject.GetInstance().GameTime,
                                      "Airport closing",
                                      string.Format(
                                          "The airport [LI airport={0}]({1}) is closing in 14 days.\n\rThe airport will be replaced by {2}({3}) and all gates and routes from {0} will be reallocated to {2}.",
                                          airport.Profile.IATACode,
                                          new AirportCodeConverter().Convert(airport),
                                          reallocatedAirport.Profile.Name,
                                          new AirportCodeConverter().Convert(reallocatedAirport))));
                }

                CalendarItems.AddCalendarItem(
                    new CalendarItem(
                        CalendarItem.ItemType.AirportClosing,
                        airport.Profile.Period.To,
                        "Airport closing",
                        $"{airport.Profile.Name}, {((Country) new CountryCurrentCountryConverter().Convert(airport.Profile.Country)).Name}"));
            }

            foreach (Airport airport in openingAirports)
            {
                GameObject.GetInstance()
                          .NewsBox.AddNews(
                              new News(
                                  News.NewsType.AirportNews,
                                  GameObject.GetInstance().GameTime,
                                  "Airport opening",
                                  $"A new airport {airport.Profile.Name}({new AirportCodeConverter().Convert(airport)}) is opening in 14 days in {airport.Profile.Town.Name}, {((Country) new CountryCurrentCountryConverter().Convert(airport.Profile.Country)).Name}."));
                CalendarItems.AddCalendarItem(
                    new CalendarItem(
                        CalendarItem.ItemType.AirportOpening,
                        airport.Profile.Period.From,
                        "Airport opening",
                        $"{airport.Profile.Name}, {((Country) new CountryCurrentCountryConverter().Convert(airport.Profile.Country)).Name}"));
            }
            //checks for new airports which are opening
            List<Airport> openedAirports =
                Airports.GetAllAirports(
                    a =>
                    a.Profile.Period.From.ToShortDateString()
                    == GameObject.GetInstance().GameTime.ToShortDateString());
            List<Airport> closedAirports =
                Airports.GetAllAirports(
                    a =>
                    a.Profile.Period.To.ToShortDateString() == GameObject.GetInstance().GameTime.ToShortDateString());

            //checks for airports which are closing down
            foreach (Airport airport in closedAirports)
            {
                //check for airport which are reallocated
                Airport reallocatedAirport = openedAirports.Find(a => a.Profile.Town == airport.Profile.Town);

                if (reallocatedAirport != null)
                {
                    IEnumerable<Airline> airlines =
                        new List<Airline>(from c in airport.AirlineContracts select c.Airline).Distinct();
                    foreach (Airline airline in airlines)
                    {
                        AirlineHelpers.ReallocateAirport(airport, reallocatedAirport, airline);

                        if (airline.IsHuman)
                        {
                            GameObject.GetInstance()
                                      .NewsBox.AddNews(
                                          new News(
                                              News.NewsType.AirportNews,
                                              GameObject.GetInstance().GameTime,
                                              "Airport operations changed",
                                              $"All your gates, routes and facilities has been moved from {airport.Profile.Name}({new AirportCodeConverter().Convert(airport)}) to [LI airport={reallocatedAirport.Profile.IATACode}]({new AirportCodeConverter().Convert(reallocatedAirport)})"));
                        }
                    }
                }

                GameObject.GetInstance()
                          .NewsBox.AddNews(
                              new News(
                                  News.NewsType.AirportNews,
                                  GameObject.GetInstance().GameTime,
                                  "Airport closed",
                                  $"The airport {airport.Profile.Name}({new AirportCodeConverter().Convert(airport)}) has now been closed. \n\rAll routes to and from the airports has been cancelled."));

                Airport airport1 = airport;
                IEnumerable<Route> obsoleteRoutes = (from r in Airlines.GetAllAirlines().SelectMany(a => a.Routes)
                                                     where r.Destination1 == airport1 || r.Destination2 == airport1
                                                     select r);

                foreach (Route route in obsoleteRoutes)
                {
                    route.Banned = true;

                    foreach (FleetAirliner airliner in route.GetAirliners())
                    {
                        if (airliner.Homebase == airport)
                        {
                            if (airliner.Airliner.Airline.IsHuman)
                            {
                                airliner.Homebase = (Airport) PopUpNewAirlinerHomebase.ShowPopUp(airliner);
                            }
                            else
                            {
                                AIHelpers.SetAirlinerHomebase(airliner);
                            }
                        }
                    }
                }
            }
            //checks for new airliner types for purchase
            foreach (
                AirlinerType aType in
                    AirlinerTypes.GetTypes(
                        a =>
                        a.Produced.From.ToShortDateString() == GameObject.GetInstance().GameTime.ToShortDateString())
                )
            {
                GameObject.GetInstance()
                          .NewsBox.AddNews(
                              new News(
                                  News.NewsType.AirlinerNews,
                                  GameObject.GetInstance().GameTime,
                                  "New airliner type available",
                                  $"{aType.Manufacturer.Name} has finished the design of {aType.Name} and it is now available for purchase"));

                if (
                    !AirlineFacilities.GetFacilities(f => f is PilotTrainingFacility)
                                      .Exists(f => ((PilotTrainingFacility) f).AirlinerFamily == aType.AirlinerFamily))
                {
                    AirlineFacilities.AddFacility(
                        new PilotTrainingFacility(
                            "airlinefacilities",
                            aType.AirlinerFamily,
                            9000,
                            1000,
                            GameObject.GetInstance().GameTime.Year,
                            0,
                            0,
                            aType.AirlinerFamily));
                }
            }
            //checks for airliner types which are out of production
            foreach (
                AirlinerType aType in
                    AirlinerTypes.GetTypes(
                        a => a.Produced.To.ToShortDateString() == GameObject.GetInstance().GameTime.ToShortDateString())
                )
            {
                GameObject.GetInstance()
                          .NewsBox.AddNews(
                              new News(
                                  News.NewsType.AirlinerNews,
                                  GameObject.GetInstance().GameTime,
                                  "Airliner type out of production",
                                  $"{aType.Manufacturer.Name} has taken {aType.Name} out of production"));

                Boolean lastFromManufacturer =
                    AirlinerTypes.GetAllTypes().Count(t => (t.Manufacturer == aType.Manufacturer
                                                            && t.Produced.To > GameObject.GetInstance().GameTime)) == 0;

                if (lastFromManufacturer)
                {
                    AirlinerType type = aType;
                    IEnumerable<Airline> manufacturerContracts =
                        Airlines.GetAllAirlines()
                                .Where(a => a.Contract != null && a.Contract.Manufacturer == type.Manufacturer);

                    foreach (Airline contractedAirline in manufacturerContracts)
                    {
                        contractedAirline.Contract = null;
                    }
                }
            }
            //checks for airport facilities for the human airline
            IEnumerable<AirlineAirportFacility> humanAirportFacilities =
                (from f in humanAirlines.SelectMany(ai => ai.Airports.SelectMany(a => a.GetAirportFacilities(ai)))
                 where f.FinishedDate.ToShortDateString() == GameObject.GetInstance().GameTime.ToShortDateString()
                 select f);

            foreach (AirlineAirportFacility facility in humanAirportFacilities)
            {
                GameObject.GetInstance()
                          .NewsBox.AddNews(
                              new News(
                                  News.NewsType.AirportNews,
                                  GameObject.GetInstance().GameTime,
                                  "Airport facility",
                                  $"Your airport facility {facility.Facility.Name} at [LI airport={facility.Airport.Profile.IATACode}] is now finished building"));
                facility.FinishedDate = GameObject.GetInstance().GameTime;
            }
            //checks for changed flight restrictions
            foreach (
                FlightRestriction restriction in
                    FlightRestrictions.GetRestrictions()
                                      .FindAll(
                                          r =>
                                          r.StartDate.ToShortDateString() == GameObject.GetInstance().GameTime.ToShortDateString()
                                          || r.EndDate.ToShortDateString()
                                          == GameObject.GetInstance().GameTime.ToShortDateString()))
            {
                string restrictionNewsText = "";
                if (restriction.Type == FlightRestriction.RestrictionType.Flights)
                {
                    restrictionNewsText = string.Format(restriction.StartDate.ToShortDateString()
                                                        == GameObject.GetInstance().GameTime.ToShortDateString() ? "All flights from {0} to {1} have been banned" : "The ban for all flights from {0} to {1} have been lifted", restriction.From.Name, restriction.To.Name);
                }
                if (restriction.Type == FlightRestriction.RestrictionType.Airlines)
                {
                    restrictionNewsText = string.Format(restriction.StartDate.ToShortDateString()
                                                        == GameObject.GetInstance().GameTime.ToShortDateString() ? "All airlines flying from {0} flying to {1} have been blacklisted" : "The blacklist on all airlines from {0} flying to {1} have been lifted", restriction.From.Name, restriction.To.Name);
                }
                if (restriction.StartDate.ToShortDateString() == GameObject.GetInstance().GameTime.ToShortDateString())
                {
                    if (restriction.Type == FlightRestriction.RestrictionType.Flights)
                    {
                        IEnumerable<Route> bannedRoutes = (from r in Airlines.GetAllAirlines().SelectMany(a => a.Routes)
                                                           where
                                                               FlightRestrictions.HasRestriction(
                                                                   r.Destination1.Profile.Country,
                                                                   r.Destination2.Profile.Country,
                                                                   GameObject.GetInstance().GameTime)
                                                           select r);

                        foreach (Route route in bannedRoutes)
                        {
                            route.Banned = true;
                        }
                    }
                }
                GameObject.GetInstance()
                          .NewsBox.AddNews(
                              new News(
                                  News.NewsType.StandardNews,
                                  GameObject.GetInstance().GameTime,
                                  "Flight restriction",
                                  restrictionNewsText));
            }
            //checks for historic events
            foreach (HistoricEvent e in HistoricEvents.GetHistoricEvents(GameObject.GetInstance().GameTime))
            {
                GameObject.GetInstance()
                          .NewsBox.AddNews(
                              new News(News.NewsType.StandardNews, GameObject.GetInstance().GameTime, e.Name, e.Text));

                foreach (HistoricEventInfluence influence in e.Influences)
                {
                    SetHistoricEventInfluence(influence, false);
                }
            }
            //checks for historic events influences ending
            foreach (
                HistoricEventInfluence influence in
                    HistoricEvents.GetHistoricEventInfluences(GameObject.GetInstance().GameTime))
            {
                SetHistoricEventInfluence(influence, true);
            }

            //updates airports
            //Parallel.ForEach(
            //    Airports.GetAllActiveAirports(),
            //    airport =>
            foreach (Airport airport in Airports.GetAllActiveAirports())
            {
                //AirportHelpers.CreateAirportWeather(airport);

                if (Infrastructure.Settings.GetInstance().MailsOnBadWeather
                    && humanAirlines.SelectMany(a => a.Airports.FindAll(aa => aa == airport)).Any()
                    && (airport.Weather[airport.Weather.Length - 1].WindSpeed == Weather.eWindSpeed.ViolentStorm
                        || airport.Weather[airport.Weather.Length - 1].WindSpeed == Weather.eWindSpeed.Hurricane))
                {
                    GameObject.GetInstance()
                              .NewsBox.AddNews(
                                  new News(
                                      News.NewsType.AirportNews,
                                      GameObject.GetInstance().GameTime,
                                      Translator.GetInstance().GetString("News", "1002"),
                                      string.Format(
                                          Translator.GetInstance().GetString("News", "1002", "message"),
                                          airport.Profile.IATACode,
                                          GameObject.GetInstance().GameTime.AddDays(airport.Weather.Length - 1).DayOfWeek)));
                }
                // chs, 2011-01-11 changed for delivery of terminals
                foreach (Terminal terminal in airport.Terminals.GetTerminals())
                {
                    if (terminal.DeliveryDate.Year == GameObject.GetInstance().GameTime.Year
                        && terminal.DeliveryDate.Month == GameObject.GetInstance().GameTime.Month
                        && terminal.DeliveryDate.Day == GameObject.GetInstance().GameTime.Day)
                    {
                        if (terminal.Airline == null)
                        {
                            GameObject.GetInstance()
                                      .NewsBox.AddNews(
                                          new News(
                                              News.NewsType.AirportNews,
                                              GameObject.GetInstance().GameTime,
                                              "Construction of terminal",
                                              $"[LI airport={airport.Profile.IATACode}], {airport.Profile.Country.Name} has build a new terminal with {terminal.Gates.NumberOfGates} gates"));
                        }

                        if (terminal.Airline != null && terminal.Airline.IsHuman)
                        {
                            GameObject.GetInstance()
                                      .NewsBox.AddNews(
                                          new News(
                                              News.NewsType.AirportNews,
                                              GameObject.GetInstance().GameTime,
                                              "Construction of terminal",
                                              $"Your terminal at [LI airport={airport.Profile.IATACode}], {airport.Profile.Country.Name} is now finished and ready for use."));
                        }

                        if (terminal.Airline != null)
                        {
                            Terminal terminal1 = terminal;
                            IEnumerable<AirportContract> oldContracts = new List<AirportContract>(airport.GetAirlineContracts(terminal.Airline)).Where(c => c.TerminalType == terminal1.Type);

                            var airportContracts = oldContracts as AirportContract[] ?? oldContracts.ToArray();
                            if (airportContracts.Any())
                            {
                                int totalGates = airportContracts.Sum(c => c.NumberOfGates);

                                int gatesDiff = totalGates - terminal.Gates.NumberOfGates;

                                if (gatesDiff > 0)
                                {
                                    int length = airportContracts.Max(c => c.Length);
                                    var newContract = new AirportContract(
                                        terminal.Airline,
                                        airport,
                                        AirportContract.ContractType.Full,
                                        terminal.Type,
                                        GameObject.GetInstance().GameTime,
                                        gatesDiff,
                                        length,
                                        AirportHelpers.GetYearlyContractPayment(
                                            airport,
                                            AirportContract.ContractType.Full,
                                            gatesDiff,
                                            length)/2,
                                        true);

                                    AirportHelpers.AddAirlineContract(newContract);
                                }

                                foreach (AirportContract oldContract in airportContracts)
                                {
                                    airport.RemoveAirlineContract(oldContract);

                                    for (int i = 0; i < oldContract.NumberOfGates; i++)
                                    {
                                        Gate oldGate =
                                            airport.Terminals.GetGates().First(g => terminal != null && g.Airline == terminal.Airline);
                                        oldGate.Airline = null;
                                    }
                                }
                            }
                            double yearlyPayment = AirportHelpers.GetYearlyContractPayment(
                                airport,
                                AirportContract.ContractType.Full,
                                terminal.Gates.NumberOfGates,
                                20);

                            AirportHelpers.AddAirlineContract(
                                new AirportContract(
                                    terminal.Airline,
                                    airport,
                                    AirportContract.ContractType.Full,
                                    terminal.Type,
                                    GameObject.GetInstance().GameTime,
                                    terminal.Gates.NumberOfGates,
                                    20,
                                    yearlyPayment*0.75,
                                    true));

                            if (
                                terminal.Airport.GetAirportFacility(
                                    terminal.Airline,
                                    AirportFacility.FacilityType.CheckIn).TypeLevel == 0)
                            {
                                AirportFacility checkinFacility =
                                    AirportFacilities.GetFacilities(AirportFacility.FacilityType.CheckIn)
                                                     .Find(f => f.TypeLevel == 1);

                                terminal.Airport.AddAirportFacility(
                                    terminal.Airline,
                                    checkinFacility,
                                    GameObject.GetInstance().GameTime);
                            }
                        }
                    }
                        //new gates in an existing terminal
                    else
                    {
                        int numberOfNewGates =
                            terminal.Gates.GetGates()
                                    .Count(
                                        g =>
                                        g.DeliveryDate.ToShortDateString()
                                        == GameObject.GetInstance().GameTime.ToShortDateString());

                        if (numberOfNewGates > 0)
                        {
                            GameObject.GetInstance()
                                      .NewsBox.AddNews(
                                          new News(
                                              News.NewsType.AirportNews,
                                              GameObject.GetInstance().GameTime,
                                              "Expansion of terminal",
                                              $"[LI airport={airport.Profile.IATACode}], {airport.Profile.Country.Name} has expanded {terminal.Name} with {numberOfNewGates} gates"));

                            double yearlyPayment = AirportHelpers.GetYearlyContractPayment(
                                airport,
                                AirportContract.ContractType.Full,
                                numberOfNewGates + terminal.Gates.NumberOfGates,
                                20);

                            AirportContract terminalContract =
                                airport.AirlineContracts.Find(c => c.Terminal != null && c.Terminal == terminal);

                            if (terminalContract != null)
                            {
                                terminalContract.NumberOfGates += numberOfNewGates;
                                terminalContract.YearlyPayment = yearlyPayment;

                                for (int i = 0; i < numberOfNewGates; i++)
                                {
                                    Gate newGate = airport.Terminals.GetGates().First(g => g.Airline == null);
                                    newGate.Airline = terminalContract.Airline;
                                }
                            }
                        }
                    }
                    //expired contracts
                    var airlineContracts =
                        new List<AirportContract>(
                            airport.AirlineContracts.FindAll(
                                c =>
                                c.ExpireDate.ToShortDateString()
                                == GameObject.GetInstance().GameTime.ToShortDateString()));

                    foreach (AirportContract contract in airlineContracts)
                    {
                        if (contract.AutoRenew)
                        {
                            contract.ContractDate = GameObject.GetInstance().GameTime;
                            contract.ExpireDate = GameObject.GetInstance().GameTime.AddYears(contract.Length);

                            if (contract.Airline.IsHuman)
                            {
                                GameObject.GetInstance()
                                          .NewsBox.AddNews(
                                              new News(
                                                  News.NewsType.AirportNews,
                                                  GameObject.GetInstance().GameTime,
                                                  "Airport contract renewed",
                                                  $"Your contract for {contract.NumberOfGates} gates at [LI airport={contract.Airport.Profile.IATACode}], {contract.Airport.Profile.Country.Name} is now been renewed"));
                            }
                        }
                        else
                        {
                            for (int i = 0; i < contract.NumberOfGates; i++)
                            {
                                Gate gate =
                                    airport.Terminals.GetGates().First(g => contract != null && g.Airline == contract.Airline);
                                gate.Airline = null;
                            }

                            if (contract.Airline.IsHuman)
                            {
                                int totalContractGates =
                                    airport.AirlineContracts.Where(c => c.Airline.IsHuman).Sum(c => c.NumberOfGates);

                                var airlineRoutes =
                                    new List<Route>(AirportHelpers.GetAirportRoutes(airport, contract.Airline));

                                var remainingContracts =
                                    new List<AirportContract>(
                                        airport.AirlineContracts.FindAll(
                                            c => c.Airline == contract.Airline && c != contract));

                                Boolean canFillRoutes = AirportHelpers.CanFillRoutesEntries(
                                    airport,
                                    contract.Airline,
                                    remainingContracts,
                                    Weather.Season.AllYear);

                                if (!canFillRoutes)
                                {
                                    GameObject.GetInstance()
                                              .NewsBox.AddNews(
                                                  new News(
                                                      News.NewsType.AirportNews,
                                                      GameObject.GetInstance().GameTime,
                                                      "Airport contract expired",
                                                      $"Your contract for {contract.NumberOfGates} gates at [LI airport={contract.Airport.Profile.IATACode}], {contract.Airport.Profile.Country.Name} is now expired, and a number of routes has been cancelled"));

                                    int currentRoute = 0;
                                    while (!canFillRoutes)
                                    {
                                        Route routeToDelete = airlineRoutes[currentRoute];

                                        foreach (FleetAirliner fAirliner in routeToDelete.GetAirliners())
                                        {
                                            fAirliner.Status = FleetAirliner.AirlinerStatus.Stopped;
                                            fAirliner.RemoveRoute(routeToDelete);
                                        }

                                        contract.Airline.RemoveRoute(routeToDelete);

                                        currentRoute++;

                                        canFillRoutes = AirportHelpers.CanFillRoutesEntries(
                                            airport,
                                            contract.Airline,
                                            remainingContracts,
                                            Weather.Season.AllYear);
                                    }
                                }
                                else
                                {
                                    GameObject.GetInstance()
                                              .NewsBox.AddNews(
                                                  new News(
                                                      News.NewsType.AirportNews,
                                                      GameObject.GetInstance().GameTime,
                                                      "Airport contract expired",
                                                      $"Your contract for {contract.NumberOfGates} gates at [LI airport={contract.Airport.Profile.IATACode}], {contract.Airport.Profile.Country.Name} is now expired"));
                                }

                                airport.RemoveAirlineContract(contract);
                            }
                            else
                            {
                                int numberOfRoutes = AirportHelpers.GetAirportRoutes(airport, contract.Airline).Count;

                                if (numberOfRoutes > 0)
                                {
                                    contract.ContractDate = GameObject.GetInstance().GameTime;
                                    contract.ExpireDate = GameObject.GetInstance().GameTime.AddYears(contract.Length);
                                }
                                else
                                {
                                    airport.RemoveAirlineContract(contract);
                                }
                            }
                        }
                    }
                }
                //checks for airport expansions
                foreach (AirportExpansion expansion in airport.Profile.Expansions.Where(e => e.Date.ToShortDateString() == GameObject.GetInstance().GameTime.ToShortDateString()))
                {
                    AirportHelpers.SetAirportExpansion(airport, expansion);
                }
            } //);
            //checks for airliners for the human airline
            foreach (
                FleetAirliner airliner in
                    humanAirlines.SelectMany(
                        a =>
                        a.Fleet.FindAll(
                            f =>
                            f.Airliner.BuiltDate == GameObject.GetInstance().GameTime
                            && f.Purchased != FleetAirliner.PurchasedType.BoughtDownPayment)))
            {
                if (airliner.Airliner.Airline == GameObject.GetInstance().HumanAirline)
                {
                    GameObject.GetInstance()
                              .NewsBox.AddNews(
                                  new News(
                                      News.NewsType.FleetNews,
                                      GameObject.GetInstance().GameTime,
                                      "Delivery of airliner",
                                      $"Your new airliner [LI airliner={airliner.Airliner.TailNumber}] as been delivered to your fleet.\nThe airliner is currently at [LI airport={airliner.Homebase.Profile.IATACode}], {airliner.Homebase.Profile.Country.Name}"));
                }
                else
                {
                    GameObject.GetInstance()
                              .NewsBox.AddNews(
                                  new News(
                                      News.NewsType.FleetNews,
                                      GameObject.GetInstance().GameTime,
                                      "Delivery of airliner",
                                      $"The new airliner [LI airliner={airliner.Airliner.TailNumber}] as been delivered for [LI airline={airliner.Airliner.Airline.Profile.IATACode}].\nThe airliner is currently at [LI airport={airliner.Homebase.Profile.IATACode}], {airliner.Homebase.Profile.Country.Name}"));
                }
            }

            //Parallel.ForEach(
            //    Airlines.GetAllAirlines(),
            //    airline =>
            foreach (Airline airline in Airlines.GetAllAirlines())

            {
                lock (airline.Fleet)
                {
                    var fleet = new List<FleetAirliner>(airline.Fleet);
                    foreach (FleetAirliner airliner in
                        fleet.FindAll(
                            a =>
                            a != null
                            && a.Airliner.BuiltDate.ToShortDateString()
                               == GameObject.GetInstance().GameTime.ToShortDateString()
                            && a.Purchased == FleetAirliner.PurchasedType.BoughtDownPayment))
                    {
                        if (airline.Money >= airliner.Airliner.Type.Price)
                        {
                            AirlineHelpers.AddAirlineInvoice(
                                airline,
                                GameObject.GetInstance().GameTime,
                                Invoice.InvoiceType.Purchases,
                                -airliner.Airliner.Type.Price);
                            airliner.Purchased = FleetAirliner.PurchasedType.Bought;
                        }
                        else
                        {
                            airline.RemoveAirliner(airliner);

                            if (airline.IsHuman)
                            {
                                GameObject.GetInstance()
                                          .NewsBox.AddNews(
                                              new News(
                                                  News.NewsType.FleetNews,
                                                  GameObject.GetInstance().GameTime,
                                                  "Delivery of airliner",
                                                  $"Your new airliner {airliner.Name} can't be delivered to your fleet.\nYou don't have enough money to purchase it."));
                            }
                        }
                    }
                }

                if (airline.Contract != null
                    && airline.Contract.ExpireDate.ToShortDateString()
                    == GameObject.GetInstance().GameTime.ToShortDateString())
                {
                    int missingAirliners = airline.Contract.Airliners - airline.Contract.PurchasedAirliners;

                    if (missingAirliners > 0)
                    {
                        double missingFee = (airline.Contract.GetTerminationFee()/(airline.Contract.Length*2))
                                            *missingAirliners;
                        AirlineHelpers.AddAirlineInvoice(
                            airline,
                            GameObject.GetInstance().GameTime,
                            Invoice.InvoiceType.Purchases,
                            -missingFee);

                        if (airline.IsHuman)
                        {
                            GameObject.GetInstance()
                                      .NewsBox.AddNews(
                                          new News(
                                              News.NewsType.FleetNews,
                                              GameObject.GetInstance().GameTime,
                                              "Contract expired",
                                              $"Your contract with {airline.Contract.Manufacturer.Name} has now expired.\nYou didn't purchased enough airliners with costs a fee of {missingFee:C} for missing {missingAirliners} airliners"));
                        }
                    }
                    else if (airline.IsHuman)
                    {
                        GameObject.GetInstance()
                                  .NewsBox.AddNews(
                                      new News(
                                          News.NewsType.FleetNews,
                                          GameObject.GetInstance().GameTime,
                                          "Contract expired",
                                          $"Your contract with {airline.Contract.Manufacturer.Name} has now expired."));
                    }

                    airline.Contract = null;
                }
                //checks for students educated
                IEnumerable<PilotStudent> educatedStudents =
                    airline.FlightSchools.SelectMany(
                        f =>
                        f.Students.FindAll(
                            s =>
                            s.EndDate.ToShortDateString()
                            == GameObject.GetInstance().GameTime.ToShortDateString()));

                foreach (PilotStudent student in educatedStudents)
                {
                    var pilot = new Pilot(student.Profile, GameObject.GetInstance().GameTime, student.Rating);

                    if (student.AirlinerFamily != "")
                    {
                        pilot.AddAirlinerFamily(student.AirlinerFamily);
                    }

                    student.Instructor.RemoveStudent(student);
                    student.Instructor.FlightSchool.RemoveStudent(student);
                    student.Instructor = null;

                    airline.AddPilot(pilot);

                    if (airline.IsHuman)
                    {
                        GameObject.GetInstance()
                                  .NewsBox.AddNews(
                                      new News(
                                          News.NewsType.FlightNews,
                                          GameObject.GetInstance().GameTime,
                                          Translator.GetInstance().GetString("News", "1006"),
                                          string.Format(
                                              Translator.GetInstance().GetString("News", "1006", "message"),
                                              pilot.Profile.Name)));
                    }
                }

                IEnumerable<Pilot> trainedPilots =
                    airline.Pilots.Where(
                        p =>
                        p.Training != null
                        && p.Training.EndDate.ToShortDateString()
                        == GameObject.GetInstance().GameTime.ToShortDateString());

                foreach (Pilot pilot in trainedPilots)
                {
                    pilot.AddAirlinerFamily(pilot.Training.AirlinerFamily);

                    if (airline.IsHuman)
                    {
                        GameObject.GetInstance()
                                  .NewsBox.AddNews(
                                      new News(
                                          News.NewsType.FlightNews,
                                          GameObject.GetInstance().GameTime,
                                          Translator.GetInstance().GetString("News", "1015"),
                                          string.Format(
                                              Translator.GetInstance().GetString("News", "1015", "message"),
                                              pilot.Profile.Name,
                                              pilot.Training.AirlinerFamily)));
                    }

                    pilot.Training = null;
                }
            } //);
            //checks for mergers
            foreach (AirlineMerger merger in AirlineMergers.GetAirlineMergers(GameObject.GetInstance().GameTime))
            {
                if (merger.Type == AirlineMerger.MergerType.Merger)
                {
                    AirlineHelpers.SwitchAirline(merger.Airline2, merger.Airline1);

                    Airlines.RemoveAirline(merger.Airline2);

                    if (merger.NewName != null && merger.NewName.Length > 1)
                    {
                        merger.Airline1.Profile.Name = merger.NewName;
                    }
                }
                if (merger.Type == AirlineMerger.MergerType.Subsidiary)
                {
                    string oldLogo = merger.Airline2.Profile.Logo;

                    var sAirline = new SubsidiaryAirline(
                        merger.Airline1,
                        merger.Airline2.Profile,
                        merger.Airline2.Mentality,
                        merger.Airline2.MarketFocus,
                        merger.Airline2.License,
                        merger.Airline2.AirlineRouteFocus);

                    AirlineHelpers.SwitchAirline(merger.Airline2, merger.Airline1);

                    merger.Airline1.AddSubsidiaryAirline(sAirline);

                    Airlines.RemoveAirline(merger.Airline2);

                    sAirline.Profile.Logos = merger.Airline2.Profile.Logos;
                    sAirline.Profile.Color = merger.Airline2.Profile.Color;
                }

                GameObject.GetInstance()
                          .NewsBox.AddNews(
                              new News(
                                  News.NewsType.AirlineNews,
                                  GameObject.GetInstance().GameTime,
                                  "Airline merger",
                                  merger.Name));
            }
            /*
            //does monthly budget work
               DateTime budgetExpires = GameObject.GetInstance().HumanAirline.Budget.BudgetExpires;
            if (budgetExpires <= GameObject.GetInstance().GameTime.AddDays(30))
            {
                GameObject.GetInstance().NewsBox.addNews(new News(News.NewsType.Airline_News, GameObject.GetInstance().GameTime, "Budget Expires Soon", "Your budget will expire within the next 30 days. Please go to the budget screen and adjust it as needed and click 'Apply'."));
            }
            else if (budgetExpires <= GameObject.GetInstance().GameTime)
            {
                //GraphicsModel.PageModel.PageFinancesModel.PageFinances.ResetValues();
            }

            if (GameObject.GetInstance().HumanAirline.Money < GameObject.GetInstance().HumanAirline.Budget.TotalBudget / 12)
            {
                WPFMessageBox.Show("Low Cash!", "Your current cash is less than your budget deduction for the month! Decrease your budget immediately or you will be negative!", WPFMessageBoxButtons.Ok);
            }
            else { GameObject.GetInstance().HumanAirline.Money -= GameObject.GetInstance().HumanAirline.Budget.TotalBudget / 12; }
             * */

            //check for insurance settlements and do maintenance
            foreach (Airline a in Airlines.GetAllAirlines())
            {
                AirlineHelpers.CheckInsuranceSettlements(a);

                var airliners = new List<FleetAirliner>(a.Fleet);
                foreach (FleetAirliner airliner in airliners)
                {
                    if (airliner != null)
                    {
                        FleetAirlinerHelpers.DoMaintenance(airliner);
                        FleetAirlinerHelpers.RestoreMaintRoutes(airliner);
                    }
                }

                //checks for special contracts
                var sContracts = new List<SpecialContract>(a.SpecialContracts.Where(s => s.Date <= GameObject.GetInstance().GameTime));

                foreach (SpecialContract sc in sContracts)
                {
                    if (sc.Date.ToShortDateString() == GameObject.GetInstance().GameTime.ToShortDateString() && sc.Type.IsFixedDate)
                    {
                        foreach (SpecialContractRoute route in sc.Type.Routes)
                        {
                            PassengerHelpers.ChangePaxDemand(route.Departure, route.Destination, (int) route.PassengersPerDay);

                            if (route.BothWays)
                                PassengerHelpers.ChangePaxDemand(route.Destination, route.Departure, (int) route.PassengersPerDay);
                        }
                    }
                    if (AirlineHelpers.CheckSpecialContract(sc))
                    {
                        a.SpecialContracts.Remove(sc);

                        if (sc.Type.IsFixedDate)
                        {
                            foreach (SpecialContractRoute route in sc.Type.Routes)
                            {
                                PassengerHelpers.ChangePaxDemand(route.Departure, route.Destination, -(int) route.PassengersPerDay);

                                if (route.BothWays)
                                    PassengerHelpers.ChangePaxDemand(route.Destination, route.Departure, -(int) route.PassengersPerDay);
                            }
                        }
                    }
                }
            }

            if (GameObject.GetInstance().GameTime.Day%7 == 0)
            {
                foreach (Airline airline in Airlines.GetAllAirlines())
                    airline.OverallScore += StatisticsHelpers.GetWeeklyScore(airline);
                // GameObject.GetInstance().HumanAirline.OverallScore +=
                //   StatisticsHelpers.GetWeeklyScore(GameObject.GetInstance().HumanAirline);
            }
            //checks for new special contract types
            List<SpecialContractType> randomSpecialContracts = SpecialContractTypes.GetRandomTypes();
            List<SpecialContractType> fixedSpecialContracts =
                SpecialContractTypes.GetTypes().FindAll(s => s.IsFixedDate && GameObject.GetInstance().GameTime.ToShortDateString() == s.Period.From.AddMonths(-1).ToShortDateString());

            var existingContracts = new List<SpecialContractType>(GameObject.GetInstance().Contracts);

            foreach (SpecialContractType sct in existingContracts)
            {
                if (sct.LastDate.AddMonths(1).ToShortDateString() == GameObject.GetInstance().GameTime.ToShortDateString())
                    GameObject.GetInstance().Contracts.Remove(sct);
                else
                {
                    Boolean taken = false;
                    int i = 0;

                    while (!taken && i < Airlines.GetAirlines(a => !a.IsHuman).Count)
                    {
                        Airline airline = Airlines.GetAirlines(a => !a.IsHuman)[i];
                        taken = AIHelpers.WillTakeSpecialContract(airline, sct);

                        if (taken)
                        {
                            DateTime startdate = sct.IsFixedDate ? sct.Period.From : GameObject.GetInstance().GameTime;

                            var sc = new SpecialContract(sct, startdate, airline);
                            airline.SpecialContracts.Add(sc);

                            GameObject.GetInstance().Contracts.Remove(sct);
                        }

                        i++;
                    }
                }
            }

            foreach (SpecialContractType sct in fixedSpecialContracts)
            {
                if (sct.LastDate == DateTime.MinValue)
                    sct.LastDate = GameObject.GetInstance().GameTime;

                GameObject.GetInstance().Contracts.Add(sct);
            }

            foreach (SpecialContractType sct in randomSpecialContracts)
            {
                if (sct.LastDate == DateTime.MinValue)
                    sct.LastDate = GameObject.GetInstance().GameTime;

                int monthsSinceLast = MathHelpers.GetAgeMonths(sct.LastDate);

                int monthsFrequency = 12/sct.Frequency;

                //mf = 12, ms = 1 => procent = lille, mf = 6, ms = 6 => procent = medium, mf = 1, ms = 12 => procent = høj

                int value = 100 - (monthsSinceLast - monthsFrequency);

                Boolean createContract = !GameObject.GetInstance().Contracts.Contains(sct) && Rnd.Next(value) == 0;

                if (createContract)
                {
                    sct.LastDate = GameObject.GetInstance().GameTime;

                    GameObject.GetInstance().Contracts.Add(sct);
                }
            }
        }
        private void btnBuyAsSubsidiary_Click(object sender, RoutedEventArgs e)
        {
            AirlinesMVVM airline = SelectedAirline;

            double buyingPrice = airline.Airline.GetValue() * 100000 * 1.10;

            WPFMessageBoxResult result = WPFMessageBox.Show(
                Translator.GetInstance().GetString("MessageBox", "2113"),
                string.Format(
                    Translator.GetInstance().GetString("MessageBox", "2113", "message"),
                    airline.Airline.Profile.Name,
                    buyingPrice),
                WPFMessageBoxButtons.YesNo);

            if (result == WPFMessageBoxResult.Yes)
            {
                List<AirlineLogo> oldLogos = airline.Airline.Profile.Logos;
                string oldColor = airline.Airline.Profile.Color;

                //creates independent airlines for each subsidiary
                while (airline.Airline.Subsidiaries.Count > 0)
                {
                    SubsidiaryAirline subAirline = airline.Airline.Subsidiaries[0];

                    subAirline.Airline = null;

                    airline.Airline.RemoveSubsidiaryAirline(subAirline);
                }

                if (airline.Airline.License > GameObject.GetInstance().HumanAirline.License)
                {
                    GameObject.GetInstance().HumanAirline.License = airline.Airline.License;
                }

                var sAirline = new SubsidiaryAirline(
                    GameObject.GetInstance().HumanAirline,
                    airline.Airline.Profile,
                    airline.Airline.Mentality,
                    airline.Airline.MarketFocus,
                    airline.Airline.License,
                    airline.Airline.AirlineRouteFocus);

                AirlineHelpers.SwitchAirline(airline.Airline, sAirline);

                GameObject.GetInstance().HumanAirline.AddSubsidiaryAirline(sAirline);

                AirlineHelpers.AddAirlineInvoice(
                    GameObject.GetInstance().HumanAirline,
                    GameObject.GetInstance().GameTime,
                    Invoice.InvoiceType.AirlineExpenses,
                    -buyingPrice);

                Airlines.RemoveAirline(airline.Airline);
                Airlines.AddAirline(sAirline);

                sAirline.Profile.Logos = oldLogos;
                sAirline.Profile.Color = oldColor;

                foreach (AirlinePolicy policy in airline.Airline.Policies)
                {
                    sAirline.AddAirlinePolicy(policy);
                }

                sAirline.Money = airline.Airline.Money;
                sAirline.StartMoney = airline.Airline.Money;

                sAirline.Fees = new AirlineFees();

                PageNavigator.NavigateTo(new PageAirline(GameObject.GetInstance().HumanAirline));
            }
        }