public ActionResult RegisterCandidateSubmit(MemberCandidate model)
        {
            if (!ModelState.IsValid)
                return CurrentUmbracoPage();

            var validationErrorInfo = string.Empty;

            var memberService = Services.MemberService;
            if (memberService.GetByEmail(model.Email) != null)
            {
                ModelState.AddModelError("", "Uživatel se zadaným emailem již existuje!");
                return CurrentUmbracoPage();
            }
            if (!model.Confirm)
            {
                ModelState.AddModelError("", "Pro dokončení registrace je nezbytné udělit souhlas se zpracováním Vašich osobních údajů, a také souhlas s našimi obchodními podmínkami a podmínkami užití.");
                return CurrentUmbracoPage();
            }

            // Candidate je typ členského účtu
            var name = model.Firstname + " " + model.Surname;
            var member = memberService.CreateMember(model.Email, model.Email, name, "Candidate");
            var filepath = "";
            var cvExists = false;

            // profilové údaje uživatele - úplný seznam je v /umbraco/Členové/Typy členů/Zájemce o práci
            member.SetValue("FirstName", model.Firstname);
            member.SetValue("Surname", model.Surname);
            member.SetValue("BirthDate", model.BirthDate);
            member.SetValue("Phone", model.Phone);
            member.Comments = model.Comments;
            member.SetValue("RegistrationUP", model.RegistrationUP);
            member.SetValue("RegistrationUPFrom", model.RegistrationUPFrom);
            member.SetValue("EmployeeDepartment", model.EmployeeDepartmentId);

            if (model.EmployeeDepartmentId.HasValue)
            {
                var ctrl = new EmployDepartmentsApiController();
                model.EmployeeDepartmentName = ctrl.GetById(model.EmployeeDepartmentId.Value).Name;
            }

            // todo: nahrat zivotopis
            if (model.CV != null && model.CV.InputStream != null)
            {
                var filename = "zivotopis_" + DateTime.Now.ToString("yyyy-MM-dd") + Path.GetExtension(model.CV.FileName);
                var path = "/media/cv/";
                var fullPath = Server.MapPath("~" + path);
                var dir = new DirectoryInfo(fullPath);
                if (!dir.Exists)
                    dir.Create();

                path += JobsplusHelpers.RemoveDiacritics(model.Surname).ToLower() + "_" + model.BirthDate.Value.ToString("yyyy-MM-dd") + "/";
                fullPath = Server.MapPath("~" + path);
                var dirUser = new DirectoryInfo(fullPath);
                if (!dirUser.Exists)
                    dirUser.Create();

                try
                {
                    filepath = fullPath + filename;
                    model.CV.SaveAs(fullPath + filename);
                    cvExists = true;
                }
                catch (Exception ex)
                {
                    filepath = "";
                    ModelState.AddModelError("", "Při nahrávání životopisu došlo k chybě");
                    TempData.Add("ValidationErrorInfo", JobsplusHelpers.GetMsgFromException(ex));
                    return CurrentUmbracoPage();
                }

                member.SetValue("CV", path + filename);
            }
            member.SetValue("CVExists", cvExists);

            // Not yet allowed to log in!
            member.IsApproved = true;

            // Don't forget to save all these things
            memberService.Save(member);

            // save their password
            memberService.SavePassword(member, model.Password);

            // "Candidate" je skupina členů
            memberService.AssignRole(member.Id, "Zájemce o práci");

            #region Odeslat email spravci
            var mail = new MailMessage(JobsplusConstants.EmailRobotEmail, _SendToEmail);
            if (!string.IsNullOrEmpty(filepath))
            {
                var atachementPath = filepath;

                if (System.IO.File.Exists(atachementPath))
                    mail.Attachments.Add(new Attachment(atachementPath));
            }
            mail.Subject = "NOVÁ REGISTRACE - zájemce o práci";
            mail.IsBodyHtml = true;
            mail.Body = "<p>Dobrý den,<br />" +
                "na webu jobsplus.cz se zaregistroval nový uchazeč o zaměstnání.</p><br /><br />" +
                "<h3>Uchazeč</h3>" +
                "<b>Jméno a příjmení:</b> " +       JobsplusHelpers.GetValueToEmail(name) + "<br />" +
                "<b>Email:</b> " +                  JobsplusHelpers.GetValueToEmail(member.Email) + "<br />" +
                "<b>Datum narození</b> " +          JobsplusHelpers.GetValueToEmail(model.BirthDate) + "<br />" +
                "<b>Telefon</b> " +                 JobsplusHelpers.GetValueToEmail(model.Phone) + "<br />" +
                "<b>Registrován na ÚP:</b> " +      JobsplusHelpers.GetValueToEmail(model.RegistrationUP) + "<br />" +
                (model.RegistrationUP ?
                    "<b>Úřad práce (kontaktní pracoviště)</b> " + JobsplusHelpers.GetValueToEmail(model.EmployeeDepartmentName) + "<br />" :
                    "") +
                (!string.IsNullOrEmpty(model.Comments) ?
                    "<br /><b>Zpráva od zájemce</b><br />" + JobsplusHelpers.GetValueToEmail(model.Comments) + "<br />" :
                    "") + "<br />" +
                "<p>S pozdravem,<br />Váš JOBSPLUS AUTOMATICKÝ ROZESÍLAČ e-mailů ;-)</p>";

            try
            {
                var smtpClient = new SmtpClient();
                smtpClient.Send(mail);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", JobsplusConstants.SendEmailErrorMsg);
                TempData.Add("ValidationErrorInfo", JobsplusHelpers.GetMsgFromException(ex));
                return CurrentUmbracoPage();
            }
            #endregion

            #region Odeslat email zajemci
            var mailCandidate = new MailMessage(JobsplusConstants.EmailRobotEmail, model.Email);
            if (!string.IsNullOrEmpty(filepath))
            {
                var atachementPath = filepath;

                if (System.IO.File.Exists(atachementPath))
                    mail.Attachments.Add(new Attachment(atachementPath));
            }

            mailCandidate.Subject = "POTVRZENÍ REGISTRACE - zájemce o práci";
            mailCandidate.IsBodyHtml = true;
            mailCandidate.Body = "<p>Dobrý den,<br />" +
                "zaznamenali jsme Vaši registraci na webu jobsplus.cz.</p><br /><br />" +
                "<h3>Přihlašovací údaje</h3>" +
                "<b>Přihlašovací jméno:</b>: " + member.Email + "<br />" +
                "<b>Heslo:</b> " + model.Password + "<br />" +
                "<p>Váš účet je již aktivní a můžete <a href=\"http://www.jobsplus.cz/vip-vstup/prihlasit/\">přihlásit</a> na web jobsplus.cz a odpovídat na inzerci. Těšíme se Vaší přízni a přejeme brzké nalezení vysněného zaměstnání.</p><br /><br />" +
                "<b>Jméno a příjmení:</b> " + JobsplusHelpers.GetValueToEmail(name) + "<br />" +
                "<b>Email:</b> " + JobsplusHelpers.GetValueToEmail(member.Email) + "<br />" +
                "<b>Datum narození</b> " + JobsplusHelpers.GetValueToEmail(model.BirthDate) + "<br />" +
                "<b>Telefon</b> " + JobsplusHelpers.GetValueToEmail(model.Phone) + "<br />" +
                "<b>Registrován na ÚP:</b> " + JobsplusHelpers.GetValueToEmail(model.RegistrationUP) + "<br />" +
                (model.RegistrationUP ?
                    "<b>Úřad práce (kontaktní pracoviště)</b> " + JobsplusHelpers.GetValueToEmail(model.EmployeeDepartmentName) + "<br />" :
                    "") +
                (!string.IsNullOrEmpty(model.Comments) ?
                    "<br /><b>Poznámka</b><br />" + JobsplusHelpers.GetValueToEmail(model.Comments) + "<br />" :
                    "") + "<br />" +
                "<p>S pozdravem,<br />Váš JOBSPLUS AUTOMATICKÝ ROZESÍLAČ e-mailů ;-)</p>";
            try
            {
                var smtpClient = new SmtpClient();
                smtpClient.Send(mailCandidate);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", JobsplusConstants.SendEmailErrorMsg);
                TempData.Add("ValidationErrorInfo", JobsplusHelpers.GetMsgFromException(ex));
                return CurrentUmbracoPage();
            }
            #endregion

            TempData.Add("RegisterCandidateIsSuccess", true);
            TempData.Add("Email", model.Email);
            TempData.Add("ValidationErrorInfo", validationErrorInfo);

            return RedirectToCurrentUmbracoPage();
        }
        //
        // GET: /EditCandidate/
        public ActionResult Index()
        {
            var memberService = Services.MemberService;
            var profile = Members.GetCurrentMemberProfileModel();
            var candidate = memberService.GetByUsername(Members.CurrentUserName); // Members.GetByUsername(Members.CurrentUserName) as IMember;
            MemberCandidate model = new MemberCandidate();
            model.Firstname = candidate.GetValue<string>("Firstname");
            model.Surname = candidate.GetValue<string>("Surname");
            if (candidate.GetValue("BirthDate") != null)
                model.BirthDate = candidate.GetValue<DateTime>("BirthDate");
            model.Phone = candidate.GetValue<string>("Phone");
            model.RegistrationUP = candidate.GetValue<bool>("RegistrationUP");
            if (candidate.GetValue("RegistrationUPFrom") != null)
                model.RegistrationUPFrom = candidate.GetValue<DateTime>("RegistrationUPFrom");
            if (candidate.GetValue("EmployeeDepartment") != null)
            {
                var employeeDepartmentId = candidate.GetValue<int>("EmployeeDepartment");
                model.EmployeeDepartmentId = employeeDepartmentId;
                var ctrl = new EmployDepartmentsApiController();
                model.EmployeeDepartmentName = ctrl.GetById(employeeDepartmentId).Name;
            }
            model.Comments = candidate.Comments;

            if (TempData.ContainsKey("EditCandidateCV")) TempData.Remove("EditCandidateCV");
            TempData.Add("EditCandidateCV", candidate.GetValue<string>("CV"));

            // prihlasovaci udaje
            model.Email = profile.UserName;
            model.Password = candidate.RawPasswordValue;
            // souhlas
            model.Confirm = true;

            return PartialView(model);
        }
        public ActionResult EditCandidateSubmit(MemberCandidate model)
        {
            if (!ModelState.IsValid)
                return CurrentUmbracoPage();

            var memberService = Services.MemberService;
            if (memberService.GetByEmail(model.Email) == null)
            {
                ModelState.AddModelError("", "Uživatel se zadaným emailem neexistuje!");
                return CurrentUmbracoPage();
            }

            // Candidate je typ členského účtu
            var name = model.Firstname + " " + model.Surname;
            var member = memberService.GetByEmail(model.Email);
            var cvExists = false;

            // profilové údaje uživatele - úplný seznam je v /umbraco/Členové/Typy členů/Zájemce o práci
            member.Name = name;
            member.SetValue("FirstName", model.Firstname);
            member.SetValue("Surname", model.Surname);
            member.SetValue("BirthDate", model.BirthDate);
            member.SetValue("Phone", model.Phone);
            member.SetValue("RegistrationUP", model.RegistrationUP);
            member.SetValue("RegistrationUPFrom", model.RegistrationUPFrom);
            member.SetValue("EmployeeDepartment", model.EmployeeDepartmentId);
            member.Comments = model.Comments;

            if (model.EmployeeDepartmentId.HasValue)
            {
                var ctrl = new EmployDepartmentsApiController();
                model.EmployeeDepartmentName = ctrl.GetById(model.EmployeeDepartmentId.Value).Name;
            }

            // todo: nahrat zivotopis
            if (model.CV != null && model.CV.InputStream != null)
            {
                var filename = "zivotopis_" + DateTime.Now.ToString("yyyy-MM-dd") + Path.GetExtension(model.CV.FileName);
                var path = "/media/cv/";
                var fullPath = Server.MapPath("~" + path);
                var dir = new DirectoryInfo(fullPath);
                if (!dir.Exists)
                    dir.Create();
                path += JobsplusHelpers.RemoveDiacritics(model.Surname).ToLower() + "_" + model.BirthDate.Value.ToString("yyyy-MM-dd") + "/";
                fullPath = Server.MapPath("~" + path);
                var dirUser = new DirectoryInfo(fullPath);
                if (!dirUser.Exists)
                    dirUser.Create();

                try
                {
                    model.CV.SaveAs(fullPath + filename);
                    cvExists = true;
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", JobsplusConstants.SendEmailErrorMsg);
                    TempData.Add("ValidationErrorInfo", JobsplusHelpers.GetMsgFromException(ex));
                    return CurrentUmbracoPage();
                }

                var filepath = path + filename;
                TempData["EditCandidateCV"] = filepath;
                member.SetValue("CV", filepath);
            }
            member.SetValue("CVExists", cvExists);

            // Don't forget to save all these things
            memberService.Save(member);

            // save their password
               // memberService.SavePassword(member, model.Password);

            if (TempData.ContainsKey("EditCandidateIsSuccess")) TempData.Remove("EditCandidateIsSuccess");
            TempData.Add("EditCandidateIsSuccess", true);
            return RedirectToCurrentUmbracoPage();
        }
        /// <summary>
        /// Získá všechny definice dotací, na které má nárok člen.
        /// </summary>
        /// <param name="memberId">Id člena</param>
        /// <returns></returns>
        public MemberGrantDefResult GetAllByMember(int memberId)
        {
            var result = new MemberGrantDefResult();
            result.CheckDate = DateTime.Now;

            // načtení údajů o členovi
            var memberService = ApplicationContext.Services.MemberService;
            var member = memberService.GetById(memberId);

            #region Validation member
            // ověření člena
            if (member == null)
            {
                result.IsError = true;
                result.CheckMessage = "Nepodařilo se načíst zájemce o práci, jeho profil byl odstraněn.";
                return result;
            }
            // typ - zájemce o práci?
            if (member == null || member.ContentTypeAlias != "Candidate")
            {
                result.IsError = true;
                result.CheckMessage = "Nejedná se zájemce o práci!";
                return result;
            }
            #endregion
            result.Id = member.Id;
            result.Phone = member.GetValue<string>("Phone");

            DateTime? birthDate = null;
            if (member.GetValue("BirthDate") != null)
            {
                birthDate = member.GetValue<DateTime>("BirthDate");
            }
            else
            {
                // věk nelze určit => nelze určit nárok na dotace
                result.IsError = true;
                result.CheckMessage = "Zájemce nemá uvedeno datum narození, na jehož základě se určuje nárok na dotace dle věku!";
                return result;
            }
            result.Age = result.CheckDate.Year - birthDate.Value.Year;

            if (!member.GetValue<bool>("RegistrationUP"))
            {
                result.IsError = true;
                result.CheckMessage = "Zájemce uvedl, že NENÍ registrován na ÚP.";
                return result;
            }

            int evidenceMonths = 0;
            if (member.GetValue("RegistrationUPFrom") != null)
            {
                var registrationUPFrom = member.GetValue<DateTime>("RegistrationUPFrom");
                evidenceMonths = ((result.CheckDate.Year - registrationUPFrom.Year) * 12) + result.CheckDate.Month - registrationUPFrom.Month;
            }
            else
            {
                result.IsError = true;
                result.CheckMessage = "Zájemce uvedl, že je registrován na ÚP, ale neuvedl od kterého data!";
                return result;
            }
            result.EvidenceMonths = evidenceMonths;

            if (member.GetValue("EmployeeDepartment") != null)
            {
                var employeeDepartmentId = member.GetValue<int>("EmployeeDepartment");
                var ctrl = new EmployDepartmentsApiController();
                result.EmployDepartment = ctrl.GetById(employeeDepartmentId);
                if (result.EmployDepartment == null)
                {
                    result.IsError = true;
                    result.CheckMessage = "Při načtení vybraného ÚP selhalo! EmployeeDepartment.Id = " + employeeDepartmentId.ToString();
                    return result;
                }
            }
            else
            {
                result.IsError = true;
                result.CheckMessage = "Zájemce uvedl, že je registrován na ÚP, ale neuvedl na kterém ÚP!";
                return result;
            }

            // načtení kritérií pro kontrolu nároku na dotace proběhlo v pořádku
            result.IsError = false;
            result.CheckMessage = "Zájemce o práci má uvedeny všechny potřebné údaje pro ověření nároku na dotace.";

            var query = new Sql().Select("gd.*").From("JobsplusGrantDefinitions gd").
                LeftJoin("JobsplusGrantDefEmployDeparts gded").On("gded.GrantDefinitionId = gd.Id").
                Where(@"
                    (gd.AgeFrom <= @0 AND gd.AgeTo >= @0) AND
                    gd.EvidenceMonths <= @1 AND
                    gded.EmployDepartmentId = @2", result.Age, result.EvidenceMonths, result.EmployDepartment.Id);
            result.GrantDefinitions = DatabaseContext.Database.Fetch<GrantDefinition>(query);

            return result;
        }