public async Task<ActionResult> Edit(OrderViewModel order)
        {
            if (ModelState.IsValid)
            {
                var dbOrder = await db.Orders.Include(o => o.Car).Include(o=>o.Group).FirstAsync(o => o.Id == order.Id);
                User driver = await SearchService.FindUser(order.Driver1License, db) ?? await SearchService.FindUserName(order.Driver1FirstName, order.Driver1LastName,db) ?? await SearchService.FindUserById(order.Driver1Id,db);
                User coDriver = await SearchService.FindUser(order.Driver2License, db) ?? await SearchService.FindUserName(order.Driver2FirstName, order.Driver2LastName, db) ?? await SearchService.FindUserById(order.Driver2Id, db);

                var team = SearchService.FindTeam(order.Entrant, db) ?? order.CreateTeam();

                if (driver == null)
                {
                    dbOrder.Driver = order.CreateDriver1();
                }
                else
                {
                    try
                    {
                        driver.BirthDate = DateTime.Parse(order.Driver1BirthDate);
                    }
                    catch
                    {
                        driver.BirthDate = driver.BirthDate;
                    }

                    driver.FirstName = order.Driver1FirstName;
                    driver.LastName = order.Driver1LastName;
                    driver.Location = string.IsNullOrWhiteSpace(order.Driver1City) ? driver.Location : order.Driver1City;
                    driver.Passport = string.IsNullOrWhiteSpace(order.Driver1Passport) ? driver.Passport : order.Driver1Passport;
                    driver.Phone = string.IsNullOrWhiteSpace(order.Driver1Phone) ? driver.Phone : order.Driver1Phone;
                    driver.Address = string.IsNullOrWhiteSpace(order.Driver1Address) ? driver.Address : order.Driver1Address;
                    if (!string.IsNullOrWhiteSpace(order.Driver1License))
                    {
                        driver.Licenses = driver.Licenses ?? new List<License>();
                        if (!driver.Licenses.Any(l => l.Season == 2014 && l.Number == order.Driver1License))
                        {
                            db.Licenses.Add(new License()
                            {
                                IssuesOn = DateTime.Today,
                                Number = order.Driver1License,
                                Season = 2014,
                                Type = LicenseType.Driver,
                                User = driver
                            });
                        }
                    }
                    dbOrder.Driver = driver;
                }

                if (coDriver == null)
                {
                    dbOrder.CoDriver = order.CreateDriver2();
                }
                else
                {
                    try
                    {
                        coDriver.BirthDate = DateTime.Parse(order.Driver2BirthDate);
                    } catch {
                        coDriver.BirthDate = coDriver.BirthDate; 
                    }
                    coDriver.FirstName = order.Driver2FirstName;
                    coDriver.LastName = order.Driver2LastName;
                    coDriver.Location = string.IsNullOrWhiteSpace(order.Driver2City)? coDriver.Location: order.Driver2City;
                    coDriver.Passport = string.IsNullOrWhiteSpace(order.Driver2Passport)? coDriver.Passport : order.Driver2Passport;
                    coDriver.Phone = string.IsNullOrWhiteSpace(order.Driver2Phone)? coDriver.Phone: order.Driver2Phone;
                    coDriver.Address = string.IsNullOrWhiteSpace(order.Driver2Address)? coDriver.Address: order.Driver2Address;
                
                    if (!string.IsNullOrWhiteSpace(order.Driver2License))
                    {
                        coDriver.Licenses = coDriver.Licenses ?? new List<License>();
                        if (!coDriver.Licenses.Any(l => l.Season == 2014 && l.Number == order.Driver2License))
                        {
                            db.Licenses.Add(new License()
                            {
                                IssuesOn = DateTime.Today,
                                Number = order.Driver2License,
                                Season = 2014,
                                Type = LicenseType.Driver,
                                User = coDriver
                            });
                        }
                    }
                    dbOrder.CoDriver = coDriver;
                }                
                // данные по пользователю всегда для текущего (ajax при смене № лицензии)

                team.Address = order.EntrantAddress;
                team.ASN = order.EntrantASN;
                team.City = order.EntrantCity;
                team.Email = order.EntrantEmail;
                team.Fax = order.EntrantFax;
                team.License = order.EntrantLicense;
                team.Phone = order.EntrantPhone;

                dbOrder.Team = team;

                dbOrder.Car.Engine = order.Engine;
                dbOrder.Car.Mark = order.Mark;
                dbOrder.Car.Model = order.Model;
                dbOrder.Car.RegistrationNumber = order.Number;

                dbOrder.Confirmed = true;
                dbOrder.StartNumber = order.StartNumber;
                var tag = await db.Tags.OfType<EventTag>().Include(t => t.Event).Include("Event.Groups").FirstAsync(t => t.Orders.Any(o => o.Id == order.Id));


                dbOrder.Group.Clear();
                dbOrder.Group = tag.Event.Groups.Where(g => order.Groups.Contains(g.Id.ToString())).ToList();
                
                await db.SaveChangesAsync();

                

                return RedirectToAction("List", new { id = tag.Id });
            }
            return View(order);
        }
        public async Task<ActionResult> RegisterFinish(OrderViewModel modelObj, string slug)
        {
            if (modelObj == null) modelObj = new OrderViewModel();

            TryUpdateModel(modelObj);

            using (var ctx = new SportDataContext())
            {
                var userManager = new UserManager<User>(new UserStore<User>(ctx));
                var currentUser = await userManager.FindByIdAsync(User.Identity.GetUserId());

                var team = SearchService.FindTeam(modelObj.Entrant, ctx);
                if (team == null)                
                    team = modelObj.CreateTeam();

                var driver1 = await SearchService.FindUser(modelObj.Driver1License, ctx) ?? await SearchService.FindUserById(modelObj.Driver1Id, ctx) ?? await SearchService.FindUserName(modelObj.Driver1FirstName, modelObj.Driver1LastName, ctx);
                var driver2 = await SearchService.FindUser(modelObj.Driver2License, ctx) ?? await SearchService.FindUserById(modelObj.Driver2Id, ctx) ?? await SearchService.FindUserName(modelObj.Driver2FirstName, modelObj.Driver2LastName, ctx);

                //Защита от
                if (driver1==null || string.IsNullOrWhiteSpace(driver1.LastName + driver1.FirstName + "")) {
                    driver1 = modelObj.CreateDriver1();
                    var existingUser = await userManager.FindByNameAsync(driver1.UserName);
                    if (existingUser != null)
                        driver1.UserName = Guid.NewGuid().ToString();
                }
                if (driver2 == null || string.IsNullOrWhiteSpace(driver2.LastName + driver2.FirstName + ""))
                {
                    driver2 = modelObj.CreateDriver2();
                    var existingUser = await userManager.FindByNameAsync(driver2.UserName);
                    if (existingUser != null)
                        driver2.UserName = Guid.NewGuid().ToString();
                }

                var car = modelObj.CreateCar();

                var ev = await EventService.GetEvent(slug, ctx);

                Dictionary<SubEvent, Order> orders = new Dictionary<SubEvent,Order>();
                ViewBag.Error = null;
                if (driver1.Id == driver2.Id)
                {
                    ViewBag.Error = "В вашей заявке совпадают первый и второй водитель. Пожалуйста, проверьте правильность заполнения заявки. Если у вас в настоящее время нет полной информации о составе экипажа - оставьте недостающие поля пустыми.";                    
                }
                if (string.IsNullOrWhiteSpace(driver1.LastName + driver1.FirstName + driver2.LastName + driver2.FirstName))
                {
                    ViewBag.Error = "Укажите пожалуйста в заявке не менее 1 водителя.";                    
                }
                if (modelObj.Groups == null || modelObj.Groups.Count() == 0)
                {
                    ViewBag.Error = "В вашей заявке на " + ev.Title + " не указано ни одной зачетной группы. Пожалуйста, укажите минимум 1 зачет из списка.";                    
                }
                if(!string.IsNullOrWhiteSpace(ViewBag.Error))
                    return View("RegistrationError", ev);

                foreach (var group in modelObj.Groups)
                {
                    var tokens = group.Split('_');
                    var subEv = ev.SubEvents.First(e=>e.Id == int.Parse(tokens[0]));

                    if(!orders.ContainsKey(subEv)) {
                        orders.Add(subEv, new Order() {
                            Driver = driver1,
                            CoDriver = driver2,
                            Team = team,
                            Car = car,
                            Redimmed = false,
                            Confirmed = false,
                            CreatedAt= DateTime.Now,
                            StartNumber="",
                            Group = new List<Group>(),
                            CreatedBy = currentUser
                        });
                    }

                    orders[subEv].Group.Add(subEv.Groups.First(g => g.Id == int.Parse(tokens[1])));
                }

                foreach (var item in orders.Keys)
                {

                    item.Tag.Orders = item.Tag.Orders ?? new List<Order>();
                    item.Tag.Orders.Add(orders[item]);
                }
                try
                {
                    await ctx.SaveChangesAsync();
                }
                catch (Exception ex)
                {
                    throw;
                }

                return View("RegistrationComplete", ev);
            }
        }