/// <summary>
        ///     Insert a new profile, if is set the idProfile, make an update of that idProfile
        /// </summary>
        /// <param name="idProfile">
        ///     Id of the profile to update.
        /// </param>
        /// <returns>
        ///     Returns the view to create a new profile
        /// </returns>
        public ActionResult newProfile(string idProfile = null)
        {
            bool   edit                  = false;
            bool   editclient            = false;
            String dataPermissions       = Session["Permissions"].ToString();
            String dataPermissionsClient = Session["PermissionsClient"].ToString();
            bool   access                = false;
            bool   accessClient          = false;

            //  access = getpermissions("users", "r");
            access = validatepermissions.getpermissions("profiles", "r", dataPermissions);
            edit   = validatepermissions.getpermissions("profiles", "u", dataPermissions);

            accessClient = validatepermissions.getpermissions("profiles", "r", dataPermissionsClient);
            editclient   = validatepermissions.getpermissions("profiles", "u", dataPermissionsClient);



            if (Profile != null && (edit == false || editclient == false))
            {
                access       = false;
                accessClient = false;
            }

            if (access == true && accessClient == true)
            {
                CustomFieldsTable cft         = new CustomFieldsTable("CustomFields");
                String            fieldsArray = cft.GetRows();
                JArray            fields      = JsonConvert.DeserializeObject <JArray>(fieldsArray);

                if (idProfile != null && idProfile != "null" && idProfile != "")
                {
                    BsonDocument profile = _employeeProfileTable.getRow(idProfile);
                    if (profile != null)
                    {
                        profile.Set("_id", profile.GetElement("_id").Value.ToString());
                        try
                        {
                            profile.Set("CreatedTimeStamp", profile.GetElement("CreatedTimeStamp").Value.ToString());
                        }
                        catch (Exception ex)
                        {
                        }
                        string profileJson = profile.ToJson();
                        ViewData["profile"] = new HtmlString(profileJson);
                    }
                }

                List <BsonDocument> profiles = _employeeProfileTable.getRows();
                ViewBag.profiles = profiles;

                return(View(fields));
            }
            else
            {
                return(Redirect("~/Home"));
            }
        }
        public String saveEmployee(FormCollection formData, HttpPostedFileBase file)
        {
            bool   access                = false;
            String dataPermissions       = Session["Permissions"].ToString();
            String dataPermissionsClient = Session["PermissionsClient"].ToString();
            bool   accessClient          = false;

            access       = validatepermissions.getpermissions("employee", "u", dataPermissions);
            accessClient = validatepermissions.getpermissions("employee", "u", dataPermissionsClient);
            //if (access == true && accessClient == true)
            if (true)
            {
                if (this.Request.IsAjaxRequest())
                {
                    formData = CustomForm.unserialize(formData);                                               //use the method serialize to parse the string into an array

                    String  employeeID   = (formData["employeeID"] == "null") ? null : formData["employeeID"]; //check insert new or update existing
                    String  EmployeeName = "";
                    JObject employee     = new JObject();
                    //get employee if update
                    if (employeeID != null)
                    {
                        String employeestring = employeetable.GetRow(employeeID);
                        employee = JsonConvert.DeserializeObject <JObject>(employeestring);
                    }

                    /*check when update , employee exist or not*/
                    if (employeeID != null && (employee == null))
                    {
                        return("{\"msg\":\"El id especificado no existe\", \"status\":\"error\"}");
                    }


                    /*The selected emoloyee Id is already in use and is not the employee who has it*/
                    if (employeeExists(formData["employee"]) == "true" && (employeeID == null || employeetable.get("employee", formData["employee"])[0].GetElement("_id").Value.ToString() != employeeID))
                    {
                        return("{\"msg\":\"El empleado ya está siendo utilizado\", \"status\":\"error\"}");
                    }

                    //due that the Employee's id is unique we use it has the image's name, so we store only the extension in the db
                    string ext = null;
                    if (file != null)
                    {
                        ext = file.FileName.Split('.').Last(); //getting the extension
                    }
                    else if (employeeID != null)
                    {
                        try
                        {
                            ext = employee["imgext"].ToString();
                        }
                        catch (Exception e) { }
                    }



                    //JArray listp = new JArray();
                    /* Format validations */



                    if (!Regex.IsMatch(formData["name"], "[A-ZÁÉÍÓÚÑa-záéíóúñ]+( [A-ZÁÉÍÓÚÑa-záéíóúñ]+){0,2}"))
                    {
                        return("{\"msg\":\"Formato incorrecto para: name\", \"status\":\"error\"}");
                    }
                    else if (!Regex.IsMatch(formData["lastname"], "[A-ZÁÉÍÓÚÑa-záéíóúñ]+( [A-ZÁÉÍÓÚÑa-záéíóúñ]+){0,1}"))
                    {
                        return("{\"msg\":\"Formato incorrecto para: Apellido Paterno\", \"status\":\"error\"}");
                    }
                    else if (!Regex.IsMatch(formData["motherlastname"], "[A-ZÁÉÍÓÚÑa-záéíóúñ]+( [A-ZÁÉÍÓÚÑa-záéíóúñ]+){0,1}"))
                    {
                        return("{\"msg\":\"Formato incorrecto para: Apellido Materno\", \"status\":\"error\"}");
                    }
                    else if (!Regex.IsMatch(formData["employee"], "([a-zA-Z0-9-_.]){4,}"))
                    {
                        return("{\"msg\":\"Formato incorrecto para: ID Empleado\", \"status\":\"error\"}");
                    }
                    ///check selected profile id exist or not
                    ///
                    else if (formData["profileId"] == "null")
                    {
                        return("{\"msg\":\"Elija El perfil\", \"status\":\"error\"}");
                    }
                    else if (employeeprofileTable.getRow(formData["profileId"]) == null)
                    {
                        return("{\"msg\":\"El perfil especificado no existe\", \"status\":\"error\"}");
                    }
                    else if (formData["type"] == "null")
                    {
                        return("{\"msg\":\"Elija El Tipo de Empleado\", \"status\":\"error\"}");
                    }
                    else if (formData["area"] == "null")
                    {
                        return("{\"msg\":\"Elija El Área\", \"status\":\"error\"}");
                    }
                    else
                    {
                        EmployeeName = formData["employee"];
                    }

                    /* Format validations */
                    //Change name representation
                    formData["name"]     = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(formData["name"].ToString().ToLower().Trim());
                    formData["lastname"] = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(formData["lastname"].ToString().ToLower().Trim());

                    //there are fields that we know that exists so we set them into the json
                    String jsonData = "{'employee':'" + formData["employee"] + "','name':'" + formData["name"].Replace("+", " ") + "','imgext':'" + ext
                                      + "','lastname':'" + formData["lastname"].Replace("+", " ")
                                      + "','motherlastname':'" + formData["motherlastname"].Replace("+", " ") + "','type':'" + formData["type"]
                                      + "','profileId':'" + formData["profileId"] + "','area':'" + formData["area"];

                    try //trying to set the creator's id
                    {
                        jsonData += "','creatorId':'";
                        jsonData += this.Session["_id"];
                        jsonData += "'";
                    }
                    catch (Exception e) { /*Ignored*/ }

                    //remove the setted data in the json from the formData
                    formData.Remove("employeeID");
                    formData.Remove("employee");
                    formData.Remove("name");
                    formData.Remove("lastname");
                    formData.Remove("motherlastname");
                    formData.Remove("type");
                    formData.Remove("profileId");
                    formData.Remove("area");


                    jsonData += ", 'profileFields':{";

                    //foreach element in the formData, let's append it to the jsonData in the profileFields
                    int cont = 0;
                    foreach (String key in formData.Keys)
                    {
                        jsonData += "'" + key + "':'" + formData[key] + "'";

                        cont++;
                        if (cont < formData.Keys.Count)
                        {
                            jsonData += ", ";
                        }
                    }
                    jsonData += "}}";



                    //now that we have the json and we know the data is ok, let's save it
                    string id = employeetable.saveRow(jsonData, employeeID);
                    //Notify this action
                    if (employeeID == null)
                    {
                        Notificate.saveNotification("Employees", "Create", "El empleado '" + EmployeeName + "' ha sido creado");
                        _logTable.SaveLog(Session["_id"].ToString(), "empleados", "Insert: " + EmployeeName, "Employee", DateTime.Now.ToString());
                    }
                    else
                    {
                        Notificate.saveNotification("Employees", "Update", "El empleado '" + EmployeeName + "' ha sido modificado");
                        _logTable.SaveLog(Session["_id"].ToString(), "empleados", "Update: " + EmployeeName, "Employee", DateTime.Now.ToString());
                    }

                    //TODO:Aqui se guarda la imagen
                    if (file != null)
                    {
                        string relativepath = "\\Uploads\\Images\\";
                        string absolutepath = Server.MapPath(relativepath);
                        if (!System.IO.Directory.Exists(absolutepath))
                        {
                            System.IO.Directory.CreateDirectory(absolutepath);
                        }
                        file.SaveAs(absolutepath + "\\" + id + "." + ext);

                        Images resizeImage = new Images(absolutepath + "\\" + id + "." + ext, absolutepath, id + "." + ext);
                        // If image bigger than 1MB, resize to 1024px max
                        if (file.ContentLength > 1024 * 1024)
                        {
                            resizeImage.resizeImage(new System.Drawing.Size(1024, 1024));
                        }

                        // Create the thumbnail of the image
                        resizeImage.createThumb();
                    }


                    return("{\"msg\":\"" + id + "\", \"status\":\"success\"}"); //returns the saved user's id
                }
                return(null);
            }

            else
            {
                return(null);
            }
        }