protected void btnSearch_Click(object sender, EventArgs e)
        {
            // Get data from database gateway
            ProjectSectionsNavigatorTDS projectSectionsNavigatorTDS = SubmitSearch();

            // Show results
            if (projectSectionsNavigatorTDS.LFS_PROJECT_SECTIONS_NAVIGATOR.DefaultView.Count > 0)
            {
                // ... Store data
                Session["lfsProjectSectionsNavigatorTDS"] = projectSectionsNavigatorTDS;

                // ... Go to the results page
                Response.Redirect("./project_sections_navigator2.aspx?source_page=project_sections_navigator.aspx&project_id=" + hdfProjectId.Value + GetNavigatorState() + "&origin=" + (string)ViewState["origin"] + "&update=" + (string)ViewState["update"] + "&data_changed=" + hdfDataChanged.Value + "&state=" + (string)ViewState["state"] + "&update_section=no&active_tab=" + (string)ViewState["active_tab"]);
            }
            else
            {
                ProjectGateway projectGateway = new ProjectGateway(projectTDS);
                lblTitleProjectName.Text = projectGateway.GetName(int.Parse(hdfProjectId.Value)) + " (" + projectGateway.GetProjectNumber(int.Parse(hdfProjectId.Value)) + ")";
                tNoResults.Visible = true;
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            if (!IsPostBack)
            {
                // Security check
                if (!(Convert.ToBoolean(Session["sgLFS_CWP_JUNCTIONLINING_VIEW"])))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                }

                // Validate query string
                if (((string)Request.QueryString["source_page"] == null) || ((string)Request.QueryString["client_id"] == null) || ((string)Request.QueryString["project_id"] == null))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in jls_navigator2.aspx");
                }

                // Tag Page
                hdfCompanyId.Value = Session["companyID"].ToString();
                hdfCurrentProjectId.Value = Request.QueryString["project_id"].ToString();
                hdfCurrentClientId.Value = Request.QueryString["client_id"].ToString();

                // Prepare initial data
                // ... For sortByList
                odsSortByList.DataBind();
                ddlSortBy.DataSourceID = "odsSortByList";
                ddlSortBy.DataValueField = "SortID";
                ddlSortBy.DataTextField = "Name";
                ddlSortBy.DataBind();

                // ... For
                odsViewForDisplayList.DataBind();
                ddlCondition1.DataSourceID = "odsViewForDisplayList";
                ddlCondition1.DataValueField = "ConditionID";
                ddlCondition1.DataTextField = "Name";
                ddlCondition1.DataBind();

                // ... for client
                int currentClientId = Int32.Parse(hdfCurrentClientId.Value.ToString());
                int companyId = Int32.Parse(hdfCompanyId.Value);

                CompaniesGateway companiesGateway = new CompaniesGateway();
                companiesGateway.LoadByCompaniesId(currentClientId, companyId);
                lblTitleClientName.Text = "Client: " + companiesGateway.GetName(currentClientId);

                // ... for project
                int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());
                ProjectGateway projectGateway = new ProjectGateway();
                projectGateway.LoadByProjectId(currentProjectId);
                string name = projectGateway.GetName(currentProjectId);
                if (name.Length > 23) name = name.Substring(0, 20) + "...";
                lblTitleProjectName.Text = " > Project: " + name + " (" + projectGateway.GetProjectNumber(currentProjectId) + ")";

                // If coming from

                // ... jls_navigator.aspx or jls_navigator2.aspx
                if ((Request.QueryString["source_page"] == "jls_navigator.aspx") || (Request.QueryString["source_page"] == "jls_navigator2.aspx"))
                {
                    RestoreNavigatorState();

                    jlsNavigatorTDS = (JlsNavigatorTDS)Session["jlsNavigatorTDS"];
                }

                // ... flat_section_jls_edit.aspx, flat_section_jls_summary.aspx or jls_delete.aspx
                if ((Request.QueryString["source_page"] == "flat_section_jls_edit.aspx") || (Request.QueryString["source_page"] == "flat_section_jls_summary.aspx") || (Request.QueryString["source_page"] == "jls_delete.aspx"))
                {
                    RestoreNavigatorState();

                    if (Request.QueryString["update"] == "no")
                    {
                        jlsNavigatorTDS = (JlsNavigatorTDS)Session["jlsNavigatorTDS"];
                    }
                    else
                    {
                        // ... Delete store data
                        Session.Contents.Remove("jlsNavigatorTDS");

                        // ... Search data with updates
                        jlsNavigatorTDS = SubmitSearch();

                        // ... store datasets
                        Session["jlsNavigatorTDS"] = jlsNavigatorTDS;

                        // ... control of existing records
                        if (jlsNavigatorTDS.JlsNavigator.Rows.Count == 0)
                        {
                            string url = "./jls_navigator.aspx?source_page=jls_navigator2.aspx&client_id=" + hdfCurrentClientId.Value + "&project_id=" + hdfCurrentProjectId.Value + GetNavigatorState() + "&no_results=yes";
                            Response.Redirect(url);
                        }
                    }
                }

                // For the grid
                grdJLNavigator.DataSource = jlsNavigatorTDS.JlsNavigator;
                grdJLNavigator.DataBind();

                // ... for the total rows
                if (jlsNavigatorTDS.JlsNavigator.Rows.Count > 0)
                {
                    lblTotalRows.Text = "Total Rows: " + jlsNavigatorTDS.JlsNavigator.Rows.Count;
                    lblTotalRows.Visible = true;
                }
                else
                {
                    lblTotalRows.Visible = false;
                }
            }
            else
            {
                // Restore TDS
                jlsNavigatorTDS = (JlsNavigatorTDS)Session["jlsNavigatorTDS"];

                // ... for the total rows
                if (jlsNavigatorTDS.JlsNavigator.Rows.Count > 0)
                {
                    lblTotalRows.Text = "Total Rows: " + jlsNavigatorTDS.JlsNavigator.Rows.Count;
                    lblTotalRows.Visible = true;
                }
                else
                {
                    lblTotalRows.Visible = false;
                }
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            if (!IsPostBack)
            {
                // Security check
                if (!(Convert.ToBoolean(Session["sgLFS_CWP_MANHOLEREHABILITATION_VIEW"])))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                }

                // Validate query string
                if (((string)Request.QueryString["source_page"] == null) || ((string)Request.QueryString["client_id"] == null) || ((string)Request.QueryString["project_id"] == null) || ((string)Request.QueryString["in_project"] == null))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in mr_navigator2.aspx");
                }

                // Tag Page
                hdfCompanyId.Value = Session["companyID"].ToString();
                hdfCurrentProjectId.Value = Request.QueryString["project_id"].ToString();
                hdfCurrentClientId.Value = Request.QueryString["client_id"].ToString();
                hdfInProject.Value = Request.QueryString["in_project"].ToString();
                hdfWorkType.Value = "Manhole Rehabilitation";

                // Prepare initial data
                // ... For sortByList
                odsSortByList.DataBind();
                ddlSortBy.DataSourceID = "odsSortByList";
                ddlSortBy.DataValueField = "SortID";
                ddlSortBy.DataTextField = "Name";
                ddlSortBy.DataBind();

                // ... For
                odsViewForDisplayList.DataBind();
                ddlCondition1.DataSourceID = "odsViewForDisplayList";
                ddlCondition1.DataValueField = "ConditionID";
                ddlCondition1.DataTextField = "Name";
                ddlCondition1.DataBind();

                // ... For view ddl
                int companyId = Int32.Parse(hdfCompanyId.Value.Trim());
                string workType = hdfWorkType.Value;
                int loginId = Convert.ToInt32(Session["loginID"]);
                string viewTypeGlobal = "";
                string viewTypePersonal = "Personal";

                // Global Views check
                if (Convert.ToBoolean(Session["sgLFS_GLOBALVIEWS_VIEW"]))
                {
                    viewTypeGlobal = "Global";
                }

                WorkViewList workViewList = new WorkViewList();
                workViewList.LoadAndAddItem(workType, viewTypeGlobal, viewTypePersonal, loginId, companyId);
                ddlView.DataSource = workViewList.Table;
                ddlView.DataValueField = "ViewID";
                ddlView.DataTextField = "Name";
                ddlView.DataBind();
                ddlView.SelectedIndex = 1;

                // Validate top information
                if ((hdfCurrentClientId.Value != "0") && (hdfCurrentProjectId.Value != "0"))
                {
                    // ... for client
                    int currentClientId = Int32.Parse(hdfCurrentClientId.Value.ToString());

                    CompaniesGateway companiesGateway = new CompaniesGateway();
                    companiesGateway.LoadByCompaniesId(currentClientId, companyId);
                    lblTitleClientName.Text = "Client: " + companiesGateway.GetName(currentClientId);

                    // ... for project
                    int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());
                    ProjectGateway projectGateway = new ProjectGateway();
                    projectGateway.LoadByProjectId(currentProjectId);
                    string name = projectGateway.GetName(currentProjectId);
                    if (name.Length > 23) name = name.Substring(0, 20) + "...";
                    lblTitleProjectName.Text = " > Project: " + name + " (" + projectGateway.GetProjectNumber(currentProjectId) + ")";
                }
                else
                {
                    lblTitleClientName.Text = "";
                    lblTitleProjectName.Text = "";
                }

                // If coming from
                // ... mr_navigator.aspx or mr_navigator2.aspx
                if ((Request.QueryString["source_page"] == "mr_navigator.aspx") || (Request.QueryString["source_page"] == "mr_navigator2.aspx"))
                {
                    RestoreNavigatorState();

                    mrNavigatorTDS = (MrNavigatorTDS)Session["mrNavigatorTDS"];
                }

                // ... mr_edit.aspx, mr_summary.aspx or mr_delete.aspx
                if ((Request.QueryString["source_page"] == "mr_edit.aspx") || (Request.QueryString["source_page"] == "mr_summary.aspx") || (Request.QueryString["source_page"] == "mr_delete.aspx"))
                {
                    RestoreNavigatorState();

                    if (Request.QueryString["update"] == "no")
                    {
                        mrNavigatorTDS = (MrNavigatorTDS)Session["mrNavigatorTDS"];
                    }
                    else
                    {
                        // ... Delete store data
                        Session.Contents.Remove("mrNavigatorTDS");

                        // ... Search data with updates
                        if (hdfBtnOrigin.Value == "Search")
                        {
                            mrNavigatorTDS = SubmitSearch();
                        }
                        else
                        {
                            if (hdfBtnOrigin.Value == "Go")
                            {
                                mrNavigatorTDS = SubmitSearchForViews();
                            }
                        }

                        // ... store datasets
                        Session["mrNavigatorTDS"] = mrNavigatorTDS;
                    }
                }

                // ... mr_delete.aspx, mr_summary.aspx or mr_edit.aspx
                if ((Request.QueryString["source_page"] == "mr_delete.aspx") || (Request.QueryString["source_page"] == "mr_summary.aspx") || (Request.QueryString["source_page"] == "mr_edit.aspx"))
                {
                    if (mrNavigatorTDS.MrNavigator.Rows.Count == 0)
                    {
                        string url = "./mr_navigator.aspx?source_page=mr_navigator2.aspx&client_id=" + hdfCurrentClientId.Value + "&project_id=" + hdfCurrentProjectId.Value + "&work_type=" + hdfWorkType.Value + "&in_project=" + hdfInProject.Value + GetNavigatorState() + "&no_results=yes";
                        Response.Redirect(url);
                    }
                }

                // For the grid
                grdMRNavigator.DataSource = mrNavigatorTDS.MrNavigator;
                grdMRNavigator.DataBind();

                //... for the total rows
                if (mrNavigatorTDS.MrNavigator.Rows.Count > 0)
                {
                    lblTotalRows.Text = "Total Rows: " + mrNavigatorTDS.MrNavigator.Rows.Count;
                    lblTotalRows.Visible = true;
                }
                else
                {
                    lblTotalRows.Visible = false;
                }
            }
            else
            {
                // Restore TDS
                mrNavigatorTDS = (MrNavigatorTDS)Session["mrNavigatorTDS"];

                // ... for the total rows
                if (mrNavigatorTDS.MrNavigator.Rows.Count > 0)
                {
                    lblTotalRows.Text = "Total Rows: " + mrNavigatorTDS.MrNavigator.Rows.Count;
                    lblTotalRows.Visible = true;
                }
                else
                {
                    lblTotalRows.Visible = false;
                }
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            if (!IsPostBack)
            {
                // Validate query string
                if (((string)Request.QueryString["source_page"] == null) && ((string)Request.QueryString["others"] == null) && ((string)Request.QueryString["employee_id"] == null) && ((string)Request.QueryString["period_id"] == null) && ((string)Request.QueryString["projecttime_id"] == null))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in timesheet_summary.aspx");
                }

                // Security check
                if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_FULL_EDITING"]))
                {
                    if (Request.QueryString["others"] == "no")
                    {
                        if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_VIEW"]))
                        {
                            if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_MANAGEMENT"]))
                            {
                                if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_MANAGEMENT_WED"]))
                                {
                                    Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                                }
                            }
                        }
                    }
                    else
                    {
                        if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_VIEW"]))
                        {
                            if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_MANAGEMENT"]))
                            {
                                if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_MY_TIMESHEETS_MANAGEMENT_WED"]))
                                {
                                    if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_OTHERS_TIMESHEETS_VIEW"]))
                                    {
                                        if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_OTHERS_TIMESHEETS_MANAGEMENT"]))
                                        {
                                            if (!Convert.ToBoolean(Session["sgLFS_LABOUR_HOURS_OTHERS_TIMESHEETS_MANAGEMENT_WED"]))
                                            {
                                                Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                // Initialize viewstate's variables
                ViewState["others"] = Request.QueryString["others"];
                ViewState["employee_id"] = int.Parse(Request.QueryString["employee_id"]);
                ViewState["period_id"] = int.Parse(Request.QueryString["period_id"]);
                ViewState["projecttime_id"] = int.Parse(Request.QueryString["projecttime_id"]);
                System.Configuration.AppSettingsReader appSettingReader = new System.Configuration.AppSettingsReader();
                ViewState["LHMode"] = appSettingReader.GetValue("LABOUR_HOURS_OPERATION_MODE", typeof(System.String)).ToString();

                // Get ProjectTime record
                projectTimeTDS =  new ProjectTimeTDS();

                ProjectTimeGateway projectTimeGateway = new ProjectTimeGateway(projectTimeTDS);
                projectTimeGateway.LoadByProjectTimeId((int)ViewState["projecttime_id"]);

                // Store datasets
                Session["projectTimeTDS"] = projectTimeTDS;

                // Databind
                tbxDate.DataBind();
                tbxWorkingDetails.DataBind();
                tbxStartTime.DataBind();
                tbxEndTime.DataBind();
                tbxLunch.DataBind();
                tbxComments.DataBind();
                tbxState.DataBind();

                // Prepare initial data for client
                StoreNavigatorState();

                EmployeeGateway employeeGateway = new EmployeeGateway(new DataSet());
                employeeGateway.LoadByEmployeeId((int)ViewState["employee_id"]);
                tbxEmployee.Text = employeeGateway.GetFullName((int)ViewState["employee_id"]);

                int companyId = Int32.Parse(Session["companyID"].ToString());

                CompaniesGateway companiesGateway = new CompaniesGateway(new DataSet());
                companiesGateway.LoadAllByCompaniesId(projectTimeGateway.GetCompaniesId((int)ViewState["projecttime_id"]), companyId);
                tbxClient.Text = companiesGateway.GetName(projectTimeGateway.GetCompaniesId((int)ViewState["projecttime_id"]));

                ProjectGateway projectGateway = new ProjectGateway(new DataSet());
                projectGateway.LoadByProjectId(projectTimeGateway.GetProjectId((int)ViewState["projecttime_id"]));
                tbxProject.Text = projectGateway.GetName(projectTimeGateway.GetProjectId((int)ViewState["projecttime_id"])) + "(" + projectGateway.GetProjectNumber(projectTimeGateway.GetProjectId((int)ViewState["projecttime_id"])) + ")";

                if (projectGateway.GetFairWageApplies(projectTimeGateway.GetProjectId((int)ViewState["projecttime_id"])))
                {
                    tbxJobClassType.Visible = true;
                    lblJobClassType.Visible = true;
                    tbxJobClassType.Text = projectTimeGateway.GetJobClassType((int)ViewState["projecttime_id"]);
                }
                else
                {
                    tbxJobClassType.Visible = false;
                    lblJobClassType.Visible = false;
                }

                if (projectTimeGateway.GetMealsCountry((int)ViewState["projecttime_id"]).HasValue)
                {
                    CountryGateway countryGateway = new CountryGateway(new DataSet());
                    countryGateway.LoadByCountryId((Int64)projectTimeGateway.GetMealsCountry((int)ViewState["projecttime_id"]));
                    tbxMealsCountry.Text = countryGateway.GetName((Int64)projectTimeGateway.GetMealsCountry((int)ViewState["projecttime_id"]));
                }

                //if (projectTimeGateway.GetMealsAllowance((int)ViewState["projecttime_id"]) > 0)
                //{
                //    cbxMealsAllowance.Checked = true;
                //}

                //if (projectTimeGateway.GetFairWage((int)ViewState["projecttime_id"]))
                //{
                //    cbxFairWage.Checked = true;
                //}

                if (projectTimeGateway.GetUnitId((int)ViewState["projecttime_id"]).HasValue)
                {
                    UnitsGateway unitGateway = new UnitsGateway(new DataSet());
                    unitGateway.LoadByUnitId((int)projectTimeGateway.GetUnitId((int)ViewState["projecttime_id"]), Convert.ToInt32(Session["companyID"]));
                    tbxUnit.Text = unitGateway.GetUnitCode((int)projectTimeGateway.GetUnitId((int)ViewState["projecttime_id"]));
                }

                if (projectTimeGateway.GetTowedUnitId((int)ViewState["projecttime_id"]).HasValue)
                {
                    UnitsGateway unitGateway = new UnitsGateway(new DataSet());
                    unitGateway.LoadByUnitId((int)projectTimeGateway.GetTowedUnitId((int)ViewState["projecttime_id"]), Convert.ToInt32(Session["companyID"]));
                    tbxTowed.Text = unitGateway.GetUnitCode((int)projectTimeGateway.GetTowedUnitId((int)ViewState["projecttime_id"]));
                }

                tbxTypeOfWork.Text = "";
                if (projectTimeGateway.GetWork((int)ViewState["projecttime_id"]) != "")
                {
                    tbxTypeOfWork.Text = projectTimeGateway.GetWork((int)ViewState["projecttime_id"]);
                }

                tbxFunction.Text = "";
                if (projectTimeGateway.GetFunction((int)ViewState["projecttime_id"]) != "")
                {
                    tbxFunction.Text = projectTimeGateway.GetFunction((int)ViewState["projecttime_id"]);
                }
            }
            else
            {
                // Restore datasets
                projectTimeTDS = (ProjectTimeTDS)Session["projectTimeTDS"];
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            if (!IsPostBack)
            {
                // Security check
                if (!Convert.ToBoolean(Session["sgLFS_CWP_POINTREPAIRS_VIEW"]))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                }

                // Validate query string
                if (((string)Request.QueryString["source_page"] == null) || ((string)Request.QueryString["client_id"] == null) || ((string)Request.QueryString["project_id"] == null))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in pr_lining_plan.aspx");
                }

                // Tag Page
                hdfCompanyId.Value = Session["companyID"].ToString();
                hdfCurrentProjectId.Value = Request.QueryString["project_id"].ToString();
                hdfCurrentClientId.Value = Request.QueryString["client_id"].ToString();
                hdfWorkType.Value = "Point Repairs";

                // Prepare initial data

                // ... for client
                int currentClientId = Int32.Parse(hdfCurrentClientId.Value.ToString());
                int companyId = Int32.Parse(hdfCompanyId.Value);

                CompaniesGateway companiesGateway = new CompaniesGateway();
                companiesGateway.LoadByCompaniesId(currentClientId, companyId);
                lblTitleClientName.Text = "Client: " + companiesGateway.GetName(currentClientId);

                // ... for project
                int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());
                ProjectGateway projectGateway = new ProjectGateway();
                projectGateway.LoadByProjectId(currentProjectId);
                string name = projectGateway.GetName(currentProjectId);
                if (name.Length > 23) name = name.Substring(0, 20) + "...";
                lblTitleProjectName.Text = " > Project: " + name + " (" + projectGateway.GetProjectNumber(currentProjectId) + ") > Lining Plan";

                // ... for the grid
                prLiningPlanTDS = new PlLiningPlanTDS();
                int projectId = Int32.Parse(hdfCurrentProjectId.Value);

                PrLiningPlanGateway prLiningPlanGateway = new PrLiningPlanGateway(prLiningPlanTDS);
                prLiningPlanGateway.ClearBeforeFill = false;
                prLiningPlanGateway.Load(projectId, companyId);

                grdLiningPlan.DataSource = prLiningPlanGateway.Table;
                grdLiningPlan.DataBind();

                // Check results
                if (prLiningPlanTDS.PlLiningPlan.Rows.Count > 0)
                {
                    tPreview.Visible = true;
                    tdNoResults.Visible = false;
                    tbFooterToolbar.Visible = true;
                }
                else
                {
                    tPreview.Visible = false;
                    tdNoResults.Visible = true;
                    tbFooterToolbar.Visible = false;
                }

                // Check results
                if (prLiningPlanTDS.PlLiningPlan.Rows.Count == 1)
                {
                    tbFooterToolbar.Visible = false;
                }

                // Store dataset
                Session["prLiningPlanTDS"] = prLiningPlanTDS;
            }
            else
            {
                // Restore dataset
                prLiningPlanTDS = (PlLiningPlanTDS)Session["prLiningPlanTDS"];

                // ... for the grid
                PrLiningPlanGateway prLiningPlanGateway = new PrLiningPlanGateway(prLiningPlanTDS);
                grdLiningPlan.DataSource = prLiningPlanGateway.Table;
                grdLiningPlan.DataBind();
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            if (!IsPostBack)
            {
                // Security check
                if (!(Convert.ToBoolean(Session["sgLFS_PROJECTS_VIEW"]) && Convert.ToBoolean(Session["sgLFS_PROJECTS_EDIT"])))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                }

                // Validate query string
                if (((string)Request.QueryString["source_page"] == null) || ((string)Request.QueryString["project_id"] == null))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in project_edit.aspx");
                }

                // Tag page
                hdfCompanyId.Value = Session["companyID"].ToString();
                hdfProjectId.Value = Request.QueryString["project_id"];
                hdfLoginId.Value = Convert.ToInt32(Session["loginID"]).ToString();
                hdfDataChanged.Value = Request.QueryString["data_changed"];
                hdfDataChangedMessage.Value = "Changes made to this project will not be saved.";

                // Prepare initial data
                Session.Remove("projectNotesDummy");
                Session.Remove("projectServicesDummy");
                Session.Remove("projectTypeOfWorkFunctionClassificationDummy");
                Session.Remove("projectJobClassClassificationDummy");
                Session.Remove("projectBudgetDummy");
                Session.Remove("subcontractorsBudgetDummy");
                Session.Remove("hotelsBudgetDummy");
                Session.Remove("bondingsBudgetDummy");
                Session.Remove("insurancesBudgetDummy");
                Session.Remove("otherCostsBudgetDummy");

                Session["fairWage"] = "None";

                // ... Set initial tab
                if ((string)Session["dialogOpenedProjects"] != "1")
                {
                    hdfActiveTab.Value = Request.QueryString["active_tab"];
                }
                else
                {
                    hdfActiveTab.Value = (string)Session["activeTabProjects"];
                }

                // ... For Library
                if (Session["lfsLibraryTDS"] != null)
                {
                    libraryTDS = (LibraryTDS)Session["lfsLibraryTDS"];
                }
                else
                {
                    libraryTDS = new LibraryTDS();
                }

                // If coming from
                // ... projects2.aspx or project_add.aspx
                if (Request.QueryString["source_page"] == "projects2.aspx" || Request.QueryString["source_page"] == "project_add.aspx")
                {
                    // Store Navigator State, Update control and Origin
                    StoreNavigatorState();
                    ViewState["update"] = "no";
                    ViewState["origin"] = "navigator";

                    // Get Project Id
                    int projectId = int.Parse(hdfProjectId.Value);

                    // ... Attachment control
                    if (Session["fromAttachment"] != null)
                    {
                        if (Session["fromAttachment"].ToString() == "yes")
                        {
                            // Restore dataset
                            projectTDS = (ProjectTDS)Session["lfsProjectTDS"];
                            projectNavigatorTDS = (ProjectNavigatorTDS)Session["projectNavigatorTDS"];
                            projectNotes = (ProjectNavigatorTDS.ProjectNotesDataTable)Session["projectNotes"];
                            projectServices = (ProjectNavigatorTDS.ProjectServiceDataTable)Session["projectServices"];
                            projectJobClassClassification = (ProjectNavigatorTDS.LFS_PROJECT_JOB_CLASS_TYPE_RATEDataTable)Session["projectJobClassClassification"];
                            projectTypeOfWorkFunctionClassification = (ProjectNavigatorTDS.LFS_PROJECT_WORK_FUNCTION_FAIR_WAGEDataTable)Session["projectTypeOfWorkFunctionClassification"];
                            projectBudget = (ProjectNavigatorTDS.ProjectWorkFunctionBudgetDataTable)Session["projectBudget"];
                            unitsBudget = (ProjectNavigatorTDS.ProjectUnitsBudgetDataTable)Session["unitsBudget"];
                            materialsBudget = (ProjectNavigatorTDS.ProjectMaterialsBudgetDataTable)Session["materialsBudget"];
                            subcontractorsBudget = (ProjectNavigatorTDS.ProjectSubcontractorsBudgetDataTable)Session["subcontractorsBudget"];
                            hotelsBudget = (ProjectNavigatorTDS.ProjectHotelsBudgetDataTable)Session["hotelsBudget"];
                            bondingsBudget = (ProjectNavigatorTDS.ProjectBondingsBudgetDataTable)Session["bondingsBudget"];
                            insurancesBudget = (ProjectNavigatorTDS.ProjectInsurancesBudgetDataTable)Session["insurancesBudget"];
                            otherCostsBudget = (ProjectNavigatorTDS.ProjectOtherCostsBudgetDataTable)Session["otherCostsBudget"];
                        }

                        Session.Remove("fromAttachment");
                    }
                    else
                    {
                        // Get dataset
                        projectTDS = new ProjectTDS();
                        projectNavigatorTDS = new ProjectNavigatorTDS();
                        projectNotes = new ProjectNavigatorTDS.ProjectNotesDataTable();
                        projectServices = new ProjectNavigatorTDS.ProjectServiceDataTable();
                        projectTypeOfWorkFunctionClassification = new ProjectNavigatorTDS.LFS_PROJECT_WORK_FUNCTION_FAIR_WAGEDataTable();
                        projectJobClassClassification = new ProjectNavigatorTDS.LFS_PROJECT_JOB_CLASS_TYPE_RATEDataTable();
                        projectBudget = new ProjectNavigatorTDS.ProjectWorkFunctionBudgetDataTable();
                        unitsBudget = new ProjectNavigatorTDS.ProjectUnitsBudgetDataTable();
                        materialsBudget = new ProjectNavigatorTDS.ProjectMaterialsBudgetDataTable();
                        subcontractorsBudget = new ProjectNavigatorTDS.ProjectSubcontractorsBudgetDataTable();
                        hotelsBudget = new ProjectNavigatorTDS.ProjectHotelsBudgetDataTable();
                        bondingsBudget = new ProjectNavigatorTDS.ProjectBondingsBudgetDataTable();
                        insurancesBudget = new ProjectNavigatorTDS.ProjectInsurancesBudgetDataTable();
                        otherCostsBudget = new ProjectNavigatorTDS.ProjectOtherCostsBudgetDataTable();

                        // Get General Data
                        ProjectGateway projectGatewayForLoad = new ProjectGateway(projectTDS);
                        projectGatewayForLoad.LoadByProjectId(projectId);

                        // Get job info
                        ProjectJobInfoGateway projectJobInfoGateway = new ProjectJobInfoGateway(projectNavigatorTDS);
                        projectJobInfoGateway.LoadAllByProjectId(projectId);

                        // Get Sale/Billing/Pricing
                        ProjectSaleBillingPricingGateway projectSaleBillingPricingGatewayForLoad = new ProjectSaleBillingPricingGateway(projectTDS);
                        projectSaleBillingPricingGatewayForLoad.LoadAllByProjectId(projectId);

                        // ... Get Sale/Billing/Pricing - Services
                        ProjectNavigatorProjectService projectNavigatorProjectService = new ProjectNavigatorProjectService(projectNavigatorTDS);
                        projectNavigatorProjectService.LoadAllByProjectId(projectId);
                        projectNavigatorProjectService.UpdateForLoad();

                        // Get Costing Updates
                        ProjectCostingUpdatesGateway projectCostingUpdatesGatewayForLoad = new ProjectCostingUpdatesGateway(projectTDS);
                        projectCostingUpdatesGatewayForLoad.LoadByProjectId(projectId);

                        // Get Project Terms
                        ProjectTermsPOGateway projectTermsPOGatewayForLoad = new ProjectTermsPOGateway(projectTDS);
                        projectTermsPOGatewayForLoad.LoadByProjectId(projectId);

                        // Get Technical
                        ProjectTechnicalGateway projectTechnicalGatewayForLoad = new ProjectTechnicalGateway(projectTDS);
                        projectTechnicalGatewayForLoad.LoadByProjectId(projectId);

                        // Get Engineer Subcontractors
                        ProjectEngineerSubcontractorsGateway projectEngineerSubcontractorsGatewayForLoad = new ProjectEngineerSubcontractorsGateway(projectTDS);
                        projectEngineerSubcontractorsGatewayForLoad.LoadAllByProjectId(projectId);

                        // ... Get Subcontractors
                        ProjectSubcontractorGateway projectSubcontractorGatewayForLoad = new ProjectSubcontractorGateway(projectTDS);
                        projectSubcontractorGatewayForLoad.LoadAllByProjectId(projectId);

                        // Cost Exceptions
                        // ... Get Type Of Work & Function Classification
                        ProjectNavigatorProjectWorkFunctionFairWage projectNavigatorProjectWorkFunctionFairWage = new ProjectNavigatorProjectWorkFunctionFairWage(projectNavigatorTDS);
                        projectNavigatorProjectWorkFunctionFairWage.LoadAllByProjectId(projectId);

                        // ... Get Job Class Classification
                        ProjectNavigatorProjectJobClassTypeRate projectNavigatorProjectJobClassTypeRate = new ProjectNavigatorProjectJobClassTypeRate(projectNavigatorTDS);
                        projectNavigatorProjectJobClassTypeRate.LoadAllByProjectId(projectId);

                        // Get Budget
                        ProjectNavigatorProjectWorkFunctionBudget projectNavigatorProjectWorkFunctionBudget = new ProjectNavigatorProjectWorkFunctionBudget(projectNavigatorTDS);
                        projectNavigatorProjectWorkFunctionBudget.LoadAllByProjectId(projectId);

                        // Get Units Budget
                        ProjectNavigatorProjectUnitsBudget projectNavigatorProjectUnitsBudget = new ProjectNavigatorProjectUnitsBudget(projectNavigatorTDS);
                        projectNavigatorProjectUnitsBudget.LoadAllByProjectId(projectId);

                        // Get Materials Budget
                        ProjectNavigatorProjectMaterialsBudget projectNavigatorProjectMaterialsBudget = new ProjectNavigatorProjectMaterialsBudget(projectNavigatorTDS);
                        projectNavigatorProjectMaterialsBudget.LoadAllByProjectId(projectId);

                        // Get Subcontractors Budget
                        ProjectNavigatorProjectSubcontractorsBudget projectNavigatorProjectSubcontractorsBudget = new ProjectNavigatorProjectSubcontractorsBudget(projectNavigatorTDS);
                        projectNavigatorProjectSubcontractorsBudget.LoadAllByProjectId(projectId);

                        // Get Hotels Budget
                        ProjectNavigatorProjectHotelsBudget projectNavigatorProjectHotelsBudget = new ProjectNavigatorProjectHotelsBudget(projectNavigatorTDS);
                        projectNavigatorProjectHotelsBudget.LoadAllByProjectId(projectId);

                        // Get Bondings Budget
                        ProjectNavigatorProjectBondingsBudget projectNavigatorProjectBondingsBudget = new ProjectNavigatorProjectBondingsBudget(projectNavigatorTDS);
                        projectNavigatorProjectBondingsBudget.LoadAllByProjectId(projectId);

                        // Get Insurances Budget
                        ProjectNavigatorProjectInsurancesBudget projectNavigatorProjectInsurancesBudget = new ProjectNavigatorProjectInsurancesBudget(projectNavigatorTDS);
                        projectNavigatorProjectInsurancesBudget.LoadAllByProjectId(projectId);

                        // Get Other Costs Budget
                        ProjectNavigatorProjectOtherCostsBudget projectNavigatorProjectOtherCostsBudget = new ProjectNavigatorProjectOtherCostsBudget(projectNavigatorTDS);
                        projectNavigatorProjectOtherCostsBudget.LoadAllByProjectId(projectId);

                        // Get Notes
                        ProjectNavigatorProjectNotes projectNavigatorProjectNotes = new ProjectNavigatorProjectNotes(projectNavigatorTDS);
                        projectNavigatorProjectNotes.LoadAllByProjectId(projectId);

                        // Store dataset
                        Session["lfsProjectTDS"] = projectTDS;
                        Session["projectNavigatorTDS"] = projectNavigatorTDS;
                        Session["projectNotes"] = projectNavigatorTDS.ProjectNotes;
                        Session["projectServices"] = projectNavigatorTDS.ProjectService;
                        Session["projectTypeOfWorkFunctionClassification"] = projectNavigatorTDS.LFS_PROJECT_WORK_FUNCTION_FAIR_WAGE;
                        Session["projectJobClassClassification"] = projectNavigatorTDS.LFS_PROJECT_JOB_CLASS_TYPE_RATE;
                        Session["projectBudget"] = projectNavigatorTDS.ProjectWorkFunctionBudget;
                        Session["unitsBudget"] = projectNavigatorTDS.ProjectUnitsBudget;
                        Session["materialsBudget"] = projectNavigatorTDS.ProjectMaterialsBudget;
                        Session["subcontractorsBudget"] = projectNavigatorTDS.ProjectSubcontractorsBudget;
                        Session["hotelsBudget"] = projectNavigatorTDS.ProjectHotelsBudget;
                        Session["bondingsBudget"] = projectNavigatorTDS.ProjectBondingsBudget;
                        Session["insurancesBudget"] = projectNavigatorTDS.ProjectInsurancesBudget;
                        Session["otherCostsBudget"] = projectNavigatorTDS.ProjectOtherCostsBudget;
                    }

                    //grdNotes.DataBind();
                    //grdServices.DataBind();
                    grdTypeOfWorkFunctionClassification.DataBind();
                    grdJobClassClassification.DataBind();
                    grdBudget.DataBind();
                    /*grdSubcontractorsBudget.DataBind();
                    grdHotelsBudget.DataBind();
                    grdBondingsBudget.DataBind();
                    grdInsurancesBudget.DataBind();*/
                    grdOtherCostsBudget.DataBind();
                }

                // ... project_summary.aspx or project_edit.aspx
                if ((Request.QueryString["source_page"] == "project_summary.aspx") || (Request.QueryString["source_page"] == "project_edit.aspx") || (Request.QueryString["source_page"] == "lm"))
                {
                    // Store Navigator State, update control and origin
                    StoreNavigatorState();
                    ViewState["update"] = Request.QueryString["update"];
                    ViewState["origin"] = Request.QueryString["origin"]; //summary

                    // Restore dataset
                    projectTDS = (ProjectTDS)Session["lfsProjectTDS"];
                    projectNavigatorTDS = (ProjectNavigatorTDS)Session["projectNavigatorTDS"];
                    projectNotes = (ProjectNavigatorTDS.ProjectNotesDataTable)Session["projectNotes"];
                    projectServices = (ProjectNavigatorTDS.ProjectServiceDataTable)Session["projectServices"];
                    projectJobClassClassification = (ProjectNavigatorTDS.LFS_PROJECT_JOB_CLASS_TYPE_RATEDataTable)Session["projectJobClassClassification"];
                    projectTypeOfWorkFunctionClassification = (ProjectNavigatorTDS.LFS_PROJECT_WORK_FUNCTION_FAIR_WAGEDataTable)Session["projectTypeOfWorkFunctionClassification"];
                    projectBudget = (ProjectNavigatorTDS.ProjectWorkFunctionBudgetDataTable)Session["projectBudget"];
                    unitsBudget = (ProjectNavigatorTDS.ProjectUnitsBudgetDataTable)Session["unitsBudget"];
                    materialsBudget = (ProjectNavigatorTDS.ProjectMaterialsBudgetDataTable)Session["materialsBudget"];
                    subcontractorsBudget = (ProjectNavigatorTDS.ProjectSubcontractorsBudgetDataTable)Session["subcontractorsBudget"];
                    hotelsBudget = (ProjectNavigatorTDS.ProjectHotelsBudgetDataTable)Session["hotelsBudget"];
                    bondingsBudget = (ProjectNavigatorTDS.ProjectBondingsBudgetDataTable)Session["bondingsBudget"];
                    insurancesBudget = (ProjectNavigatorTDS.ProjectInsurancesBudgetDataTable)Session["insurancesBudget"];
                    otherCostsBudget = (ProjectNavigatorTDS.ProjectOtherCostsBudgetDataTable)Session["otherCostsBudget"];

                    // Get Project Id
                    int projectId = int.Parse(hdfProjectId.Value);

                    if (ViewState["update"].ToString().Trim() == "yes")
                    {
                        // Get General Data
                        ProjectGateway projectGatewayForLoad = new ProjectGateway(projectTDS);
                        projectGatewayForLoad.LoadByProjectId(projectId);

                        // Get job info
                        ProjectJobInfoGateway projectJobInfoGateway = new ProjectJobInfoGateway(projectNavigatorTDS);
                        projectJobInfoGateway.LoadAllByProjectId(projectId);

                        // Get Sale/Billing/Pricing
                        ProjectSaleBillingPricingGateway projectSaleBillingPricingGatewayForLoad = new ProjectSaleBillingPricingGateway(projectTDS);
                        projectSaleBillingPricingGatewayForLoad.LoadAllByProjectId(projectId);

                        // ... Get Sale/Billing/Pricing - Services
                        ProjectNavigatorProjectService projectNavigatorProjectService = new ProjectNavigatorProjectService(projectNavigatorTDS);
                        projectNavigatorProjectService.LoadAllByProjectId(projectId);
                        projectNavigatorProjectService.UpdateForLoad();

                        // Get Costing Updates
                        ProjectCostingUpdatesGateway projectCostingUpdatesGatewayForLoad = new ProjectCostingUpdatesGateway(projectTDS);
                        projectCostingUpdatesGatewayForLoad.LoadByProjectId(projectId);

                        // Get Project Terms
                        ProjectTermsPOGateway projectTermsPOGatewayForLoad = new ProjectTermsPOGateway(projectTDS);
                        projectTermsPOGatewayForLoad.LoadByProjectId(projectId);

                        // Get Technical
                        ProjectTechnicalGateway projectTechnicalGatewayForLoad = new ProjectTechnicalGateway(projectTDS);
                        projectTechnicalGatewayForLoad.LoadByProjectId(projectId);

                        // Get Engineer Subcontractors
                        ProjectEngineerSubcontractorsGateway projectEngineerSubcontractorsGatewayForLoad = new ProjectEngineerSubcontractorsGateway(projectTDS);
                        projectEngineerSubcontractorsGatewayForLoad.LoadAllByProjectId(projectId);

                        // ... Get Subcontractors
                        ProjectSubcontractorGateway projectSubcontractorGatewayForLoad = new ProjectSubcontractorGateway(projectTDS);
                        projectSubcontractorGatewayForLoad.LoadAllByProjectId(projectId);

                        // Cost Exceptions
                        // ... Get Type Of Work & Function Classification
                        ProjectNavigatorProjectWorkFunctionFairWage projectNavigatorProjectWorkFunctionFairWage = new ProjectNavigatorProjectWorkFunctionFairWage(projectNavigatorTDS);
                        projectNavigatorProjectWorkFunctionFairWage.LoadAllByProjectId(projectId);

                        // ... Get Job Class Classification
                        ProjectNavigatorProjectJobClassTypeRate projectNavigatorProjectJobClassTypeRate = new ProjectNavigatorProjectJobClassTypeRate(projectNavigatorTDS);
                        projectNavigatorProjectJobClassTypeRate.LoadAllByProjectId(projectId);

                        // Get Budget
                        ProjectNavigatorProjectWorkFunctionBudget projectNavigatorProjectWorkFunctionBudget = new ProjectNavigatorProjectWorkFunctionBudget(projectNavigatorTDS);
                        projectNavigatorProjectWorkFunctionBudget.LoadAllByProjectId(projectId);

                        // Get Units Budget
                        ProjectNavigatorProjectUnitsBudget projectNavigatorProjectUnitsBudget = new ProjectNavigatorProjectUnitsBudget(projectNavigatorTDS);
                        projectNavigatorProjectUnitsBudget.LoadAllByProjectId(projectId);

                        // Get Materials Budget
                        ProjectNavigatorProjectMaterialsBudget projectNavigatorProjectMaterialsBudget = new ProjectNavigatorProjectMaterialsBudget(projectNavigatorTDS);
                        projectNavigatorProjectMaterialsBudget.LoadAllByProjectId(projectId);

                        // Get Subcontractors Budget
                        ProjectNavigatorProjectSubcontractorsBudget projectNavigatorProjectSubcontractorsBudget = new ProjectNavigatorProjectSubcontractorsBudget(projectNavigatorTDS);
                        projectNavigatorProjectSubcontractorsBudget.LoadAllByProjectId(projectId);

                        // Get Hotels Budget
                        ProjectNavigatorProjectHotelsBudget projectNavigatorProjectHotelsBudget = new ProjectNavigatorProjectHotelsBudget(projectNavigatorTDS);
                        projectNavigatorProjectHotelsBudget.LoadAllByProjectId(projectId);

                        // Get Bondings Budget
                        ProjectNavigatorProjectBondingsBudget projectNavigatorProjectBondingsBudget = new ProjectNavigatorProjectBondingsBudget(projectNavigatorTDS);
                        projectNavigatorProjectBondingsBudget.LoadAllByProjectId(projectId);

                        // Get Insurances Budget
                        ProjectNavigatorProjectInsurancesBudget projectNavigatorProjectInsurancesBudget = new ProjectNavigatorProjectInsurancesBudget(projectNavigatorTDS);
                        projectNavigatorProjectInsurancesBudget.LoadAllByProjectId(projectId);

                        // Get Other Costs Budget
                        ProjectNavigatorProjectOtherCostsBudget projectNavigatorProjectOtherCostsBudget = new ProjectNavigatorProjectOtherCostsBudget(projectNavigatorTDS);
                        projectNavigatorProjectOtherCostsBudget.LoadAllByProjectId(projectId);

                        // Get Notes
                        ProjectNavigatorProjectNotes projectNavigatorProjectNotes = new ProjectNavigatorProjectNotes(projectNavigatorTDS);
                        projectNavigatorProjectNotes.LoadAllByProjectId(projectId);

                        //grdNotes.DataBind();
                        //grdServices.DataBind();
                        grdTypeOfWorkFunctionClassification.DataBind();
                        grdJobClassClassification.DataBind();
                        grdBudget.DataBind();
                        /*grdSubcontractorsBudget.DataBind();
                        grdHotelsBudget.DataBind();
                        grdBondingsBudget.DataBind();
                        grdInsurancesBudget.DataBind();*/
                        grdOtherCostsBudget.DataBind();

                        // Store dataset
                        Session["lfsProjectTDS"] = projectTDS;
                        Session["projectNavigatorTDS"] = projectNavigatorTDS;
                        Session["projectNotes"] = projectNavigatorTDS.ProjectNotes;
                        Session["projectServices"] = projectNavigatorTDS.ProjectService;
                        Session["projectTypeOfWorkFunctionClassification"] = projectNavigatorTDS.LFS_PROJECT_WORK_FUNCTION_FAIR_WAGE;
                        Session["projectJobClassClassification"] = projectNavigatorTDS.LFS_PROJECT_JOB_CLASS_TYPE_RATE;
                        Session["projectBudget"] = projectNavigatorTDS.ProjectWorkFunctionBudget;
                        Session["unitsBudget"] = projectNavigatorTDS.ProjectUnitsBudget;
                        Session["materialsBudget"] = projectNavigatorTDS.ProjectMaterialsBudget;
                        Session["subcontractorsBudget"] = projectNavigatorTDS.ProjectSubcontractorsBudget;
                        Session["hotelsBudget"] = projectNavigatorTDS.ProjectHotelsBudget;
                        Session["bondingsBudget"] = projectNavigatorTDS.ProjectBondingsBudget;
                        Session["insurancesBudget"] = projectNavigatorTDS.ProjectInsurancesBudget;
                        Session["otherCostsBudget"] = projectNavigatorTDS.ProjectOtherCostsBudget;
                    }
                }

                // Data for current project
                ProjectGateway projectGateway = new ProjectGateway(projectTDS);

                // ... for project
                int currentProjectId = Int32.Parse(hdfProjectId.Value.ToString());
                string name = projectGateway.GetName(currentProjectId);
                if (name.Length > 23) name = name.Substring(0, 20) + "...";
                lblTitleProjectName.Text = name + " (" + projectGateway.GetProjectNumber(currentProjectId) + ")";

                // ... for client
                int companyId = Int32.Parse(hdfCompanyId.Value);
                int currentClientId = projectGateway.GetClientID(Int32.Parse(hdfProjectId.Value.ToString()));
                CompaniesGateway companiesGateway = new CompaniesGateway();
                companiesGateway.LoadAllByCompaniesId(currentClientId, companyId);
                lblTitleClientName.Text = "Client: " + companiesGateway.GetName(currentClientId);

                // Load Data
                LoadData();

                // Store Dataset
                Session["lfsProjectTDS"] = projectTDS;

                //// ... For total cost at services
                //ProjectNavigatorProjectService projectNavigatorProjectServiceForCost = new ProjectNavigatorProjectService(projectNavigatorTDS);
                //tbxTotalCost.Text = Decimal.Round(projectNavigatorProjectServiceForCost.GetTotalCost(), 2).ToString();
            }
            else
            {
                // Restore dataset
                projectTDS = (ProjectTDS)Session["lfsProjectTDS"];
                projectNavigatorTDS = (ProjectNavigatorTDS)Session["projectNavigatorTDS"];
                projectNotes = (ProjectNavigatorTDS.ProjectNotesDataTable)Session["projectNotes"];
                projectServices = (ProjectNavigatorTDS.ProjectServiceDataTable)Session["projectServices"];
                projectJobClassClassification = (ProjectNavigatorTDS.LFS_PROJECT_JOB_CLASS_TYPE_RATEDataTable)Session["projectJobClassClassification"];
                projectTypeOfWorkFunctionClassification = (ProjectNavigatorTDS.LFS_PROJECT_WORK_FUNCTION_FAIR_WAGEDataTable)Session["projectTypeOfWorkFunctionClassification"];
                projectBudget = (ProjectNavigatorTDS.ProjectWorkFunctionBudgetDataTable)Session["projectBudget"];
                unitsBudget = (ProjectNavigatorTDS.ProjectUnitsBudgetDataTable)Session["unitsBudget"];
                materialsBudget = (ProjectNavigatorTDS.ProjectMaterialsBudgetDataTable)Session["materialsBudget"];
                subcontractorsBudget = (ProjectNavigatorTDS.ProjectSubcontractorsBudgetDataTable)Session["subcontractorsBudget"];
                hotelsBudget = (ProjectNavigatorTDS.ProjectHotelsBudgetDataTable)Session["hotelsBudget"];
                bondingsBudget = (ProjectNavigatorTDS.ProjectBondingsBudgetDataTable)Session["bondingsBudget"];
                insurancesBudget = (ProjectNavigatorTDS.ProjectInsurancesBudgetDataTable)Session["insurancesBudget"];
                otherCostsBudget = (ProjectNavigatorTDS.ProjectOtherCostsBudgetDataTable)Session["otherCostsBudget"];

                tbxProjectNumber.DataBind();

                if (Session["lfsLibraryTDS"] != null)
                {
                    libraryTDS = (LibraryTDS)Session["lfsLibraryTDS"];
                }
                else
                {
                    libraryTDS = new LibraryTDS();
                }
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // METHODS
        //
        private void Save()
        {
            bool existsAtGrid = false;

            // Validate page
            if (Page.IsValid)
            {
                SelectProjectLastUsedProjectsGateway selectProjectLastUsedProjectsVerifyGateway = new SelectProjectLastUsedProjectsGateway(selectProjectTDS);
                if (selectProjectLastUsedProjectsVerifyGateway.Table.Rows.Count > 0)
                {
                    // If exists the project in the grid
                    foreach (GridViewRow row in grdProjects.Rows)
                    {
                        // Grid Data
                        int gridClientId = Int32.Parse(((Label)row.FindControl("lblClientId")).Text.Trim());
                        int gridProjectId = Int32.Parse(((Label)row.FindControl("lblProjectId")).Text.Trim());
                        int gridUserId = Int32.Parse(((Label)row.FindControl("lblUserId")).Text.Trim());
                        int gridCompanyId = Int32.Parse(((Label)row.FindControl("lblCompanyId")).Text.Trim());
                        DateTime gridLastLoggedInDate = DateTime.Parse(((Label)row.FindControl("lblLastLoggedInDate")).Text.Trim());
                        string workType = hdfWorkType.Value;

                        // New Data
                        DateTime newLastLoggedInDate = DateTime.Now;

                        if ((gridClientId.ToString() == ddlClient.SelectedValue) && (gridProjectId.ToString() == ddlProject.SelectedValue) && (gridUserId == Int32.Parse(hdfLoginId.Value)) && (gridCompanyId == Int32.Parse(hdfCompanyId.Value)))
                        {
                            // Update if exists
                            SelectProjectLastUsedProjects model = new SelectProjectLastUsedProjects(selectProjectTDS);
                            model.UpdateLogginDate(gridClientId, gridProjectId, gridUserId, gridLastLoggedInDate, gridCompanyId, false, workType, newLastLoggedInDate);
                            existsAtGrid = true;
                        }

                        Session["selectProjectTDS"] = selectProjectTDS;
                        Session["lastUsedProjects"] = selectProjectTDS.LastUsedProjects;

                        grdProjects.DataBind();
                        grdProjects.PageIndex = grdProjects.PageCount - 1;
                    }
                }

                // If doesn't exists at grid
                if (!existsAtGrid)
                {
                    if (grdProjects.Rows.Count < 5)
                    {
                        // Add data if exist at grid's foot
                        GrdProjectAdd();
                    }
                    else
                    {
                        int index = 1;
                        foreach (GridViewRow row in grdProjects.Rows)
                        {
                            if (index == 5)
                            {
                                // Grid Data
                                int gridClientId = Int32.Parse(((Label)row.FindControl("lblClientId")).Text.Trim());
                                int gridProjectId = Int32.Parse(((Label)row.FindControl("lblProjectId")).Text.Trim());
                                int gridUserId = Int32.Parse(((Label)row.FindControl("lblUserId")).Text.Trim());
                                int gridCompanyId = Int32.Parse(((Label)row.FindControl("lblCompanyId")).Text.Trim());
                                DateTime gridLastLoggedInDate = DateTime.Parse(((Label)row.FindControl("lblLastLoggedInDate")).Text.Trim());
                                string workType = hdfWorkType.Value;

                                // New Data
                                int newProjectId = Int32.Parse(ddlProject.SelectedValue);
                                int newClientId = Int32.Parse(ddlClient.SelectedValue);
                                int newCompanyId = Int32.Parse(hdfCompanyId.Value);
                                int newUserId = Convert.ToInt32(Session["loginID"]);
                                DateTime newLastLoggedInDate = DateTime.Now;
                                string newWorkType = hdfWorkType.Value;

                                ProjectGateway projectGateway = new ProjectGateway();
                                projectGateway.LoadByProjectId(newProjectId);
                                string newProjectName = projectGateway.GetName(newProjectId) + " (" + projectGateway.GetProjectNumber(newProjectId) + ")";

                                int companyId = Int32.Parse(hdfCompanyId.Value);
                                CompaniesGateway companiesGateway = new CompaniesGateway();
                                companiesGateway.LoadByCompaniesId(newClientId, companyId);
                                string newClientName = companiesGateway.GetName(newClientId);

                                // Update if exists
                                SelectProjectLastUsedProjects model = new SelectProjectLastUsedProjects(selectProjectTDS);
                                model.Update(gridClientId, gridProjectId, gridUserId, gridCompanyId, workType, newClientId, newProjectId, newUserId, newLastLoggedInDate, newCompanyId, false, newWorkType, newProjectName, newClientName);
                            }

                            index = index + 1;
                        }

                        Session["selectProjectTDS"] = selectProjectTDS;
                        Session["lastUsedProjects"] = selectProjectTDS.LastUsedProjects;

                        grdProjects.DataBind();
                        grdProjects.PageIndex = grdProjects.PageCount - 1;
                    }
                }

                // Update data at bd
                UpdateDatabase();
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            if (!IsPostBack)
            {
                // Security check
                if (!(Convert.ToBoolean(Session["sgLFS_CWP_POINTREPAIRS_VIEW"]) && Convert.ToBoolean(Session["sgLFS_CWP_POINTREPAIRS_EDIT"])))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                }

                // Validate query string
                if (((string)Request.QueryString["source_page"] == null) || ((string)Request.QueryString["client_id"] == null) || ((string)Request.QueryString["project_id"] == null) ||  ((string)Request.QueryString["asset_id"] == null) || ((string)Request.QueryString["active_tab"] == null))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in pr_summary.aspx");
                }

                // Tag Page
                TagPage();

                // If coming from
                int companyId = Int32.Parse(hdfCompanyId.Value.Trim());
                int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());
                int assetId = Int32.Parse(hdfAssetId.Value.Trim());
                int workId = Int32.Parse(hdfWorkId.Value);

                Session.Remove("pointRepairsRepairsTempDummy");
                Session.Remove("pointRepairsCommentsTempDummy");

                // ... pr_navigator2.aspx
                if (Request.QueryString["source_page"] == "pr_navigator2.aspx")
                {
                    StoreNavigatorState();
                    ViewState["update"] = "no";

                    // ... Set initial tab
                    if ((string)Session["dialogOpenedPr"] != "1")
                    {
                        hdfActiveTab.Value = Request.QueryString["active_tab"];

                        pointRepairsTDS = new PointRepairsTDS();
                        pointRepairsRepairsTemp = new PointRepairsTDS.RepairDetailsDataTable();
                        pointRepairsCommentsTemp = new PointRepairsTDS.CommentDetailsDataTable();

                        PointRepairsSectionDetails pointRepairsSectionDetails = new PointRepairsSectionDetails(pointRepairsTDS);
                        pointRepairsSectionDetails.LoadByWorkId(workId, companyId);

                        PointRepairsWorkDetails pointRepairsWorkDetails = new PointRepairsWorkDetails(pointRepairsTDS);
                        pointRepairsWorkDetails.LoadByWorkIdAssetId(workId, assetId, companyId);

                        PointRepairsRepairDetails pointRepairsRepairDetails = new PointRepairsRepairDetails(pointRepairsTDS);
                        pointRepairsRepairDetails.LoadAllByWorkId(workId, companyId);

                        PointRepairsCommentDetails pointRepairsCommentDetails = new PointRepairsCommentDetails(pointRepairsTDS);
                        pointRepairsCommentDetails.LoadAllByWorkIdWorkType(workId, companyId, "Point Repairs");
                    }
                    else
                    {
                        hdfActiveTab.Value = (string)Session["activeTabPr"];

                        // Restore datasets
                        pointRepairsTDS = (PointRepairsTDS)Session["pointRepairsTDS"];
                        pointRepairsRepairsTemp = (PointRepairsTDS.RepairDetailsDataTable)Session["pointRepairsRepairsTemp"];
                        pointRepairsCommentsTemp = (PointRepairsTDS.CommentDetailsDataTable)Session["pointRepairsCommentsTemp"];
                    }

                    tcPrDetails.ActiveTabIndex = Int32.Parse(hdfActiveTab.Value);

                    Session["filterExpression"] = "Deleted = 0";

                    // Store dataset
                    Session["pointRepairsTDS"] = pointRepairsTDS;
                    Session["pointRepairsRepairsTemp"] = pointRepairsRepairsTemp;
                    Session["pointRepairsCommentsTemp"] = pointRepairsCommentsTemp;
                }

                // ... pr_delete.aspx or pr_edit.aspx
                if ((Request.QueryString["source_page"] == "pr_delete.aspx") || (Request.QueryString["source_page"] == "pr_edit.aspx"))
                {
                    StoreNavigatorState();
                    ViewState["update"] = Request.QueryString["update"];

                    // Restore dataset
                    pointRepairsTDS = (PointRepairsTDS)Session["pointRepairsTDS"];
                    pointRepairsRepairsTemp = (PointRepairsTDS.RepairDetailsDataTable)Session["pointRepairsRepairsTemp"];
                    pointRepairsCommentsTemp = (PointRepairsTDS.CommentDetailsDataTable)Session["pointRepairsCommentsTemp"];

                    // ... Set initial tab
                    if ((string)Session["dialogOpenedPr"] != "1")
                    {
                        hdfActiveTab.Value = Request.QueryString["active_tab"];
                    }
                    else
                    {
                        hdfActiveTab.Value = (string)Session["activeTabPr"];
                    }

                    tcPrDetails.ActiveTabIndex = Int32.Parse(hdfActiveTab.Value);

                    ApplyFilter();

                    switch ((string)Session["filterExpression"])
                    {
                        case "Deleted = 0":
                            ddlFilter.SelectedIndex = 0;
                            break;

                        case "Type='Robotic Reaming' AND Deleted = 0":
                            ddlFilter.SelectedIndex = 1;
                            break;

                        case "Type='Point Lining' AND Deleted = 0":
                            ddlFilter.SelectedIndex = 2;
                            break;

                        case "Type='Grouting' AND Deleted = 0":
                            ddlFilter.SelectedIndex = 3;
                            break;

                        default:
                            ddlFilter.SelectedIndex = 0;
                            break;
                    }
                }

                // Prepare initial data
                // ... for client
                int currentClientId = Int32.Parse(hdfCurrentClientId.Value.ToString());

                CompaniesGateway companiesGateway = new CompaniesGateway();
                companiesGateway.LoadByCompaniesId(currentClientId, companyId);
                lblTitleClientName.Text = "Client: " + companiesGateway.GetName(currentClientId);

                // ... for project
                ProjectGateway projectGateway = new ProjectGateway();
                projectGateway.LoadByProjectId(currentProjectId);
                string name = projectGateway.GetName(currentProjectId);
                if (name.Length > 23) name = name.Substring(0, 20) + "...";
                lblTitleProjectName.Text = " > Project: " + name + " (" + projectGateway.GetProjectNumber(currentProjectId) + ") > Selected Section";

                // ... Data for current point repairs work
                LoadPointRepairsData(currentProjectId, assetId, companyId);
            }
            else
            {
                // Restore datasets
                pointRepairsTDS = (PointRepairsTDS)Session["pointRepairsTDS"];
                pointRepairsRepairsTemp = (PointRepairsTDS.RepairDetailsDataTable)Session["pointRepairsRepairsTemp"];
                pointRepairsCommentsTemp = (PointRepairsTDS.CommentDetailsDataTable)Session["pointRepairsCommentsTemp"];

                // Set initial tab
                int activeTab = Int32.Parse(hdfActiveTab.Value);
                tcPrDetails.ActiveTabIndex = activeTab;

                ApplyFilter();
            }
        }
        private void InsertProject(int projectId)
        {
            // ... Data for current project
            ProjectGateway projectGateway = new ProjectGateway(projectTDS);
            projectGateway.LoadByProjectId(projectId);

            // ... Definition of general variables
            Int64 countryId = projectGateway.GetCountryID(projectId);
            int officeId = projectGateway.GetOfficeID(projectId);
            Int64? provinceId = projectGateway.GetProvinceID(projectId);
            Int64? cityId = projectGateway.GetCityID(projectId);
            Int64? countyId = projectGateway.GetCountyID(projectId);
            int? projectLeadId = null; if (projectGateway.GetProjectLeadID(projectId).HasValue) projectLeadId = (int)projectGateway.GetProjectLeadID(projectId);
            int salesmanId = projectGateway.GetSalesmanID(projectId);
            bool deleted = false;
            int? clientPrimaryContactID = null; if (projectGateway.GetClientPrimaryContactID(projectId).HasValue) clientPrimaryContactID = (int)projectGateway.GetClientPrimaryContactID(projectId);
            int? clientSecondaryContactID = null; if (projectGateway.GetClientSecondaryContactID(projectId).HasValue) clientSecondaryContactID = (int)projectGateway.GetClientSecondaryContactID(projectId);
            int? OriginalProjectID = projectId;
            int? projectNumberCopy = null; if (projectGateway.GetLastProjectNumberCopy(projectId).HasValue) projectNumberCopy = (int)projectGateway.GetLastProjectNumberCopy(projectId) + 1; else projectNumberCopy = 1;
            string projectNumber = projectGateway.GetProjectNumber(projectId) + "-" + projectNumberCopy.ToString();
            string projectType = "Proposal";
            string projectState = projectGateway.GetProjectState(projectId);
            string name = projectGateway.GetName(projectId);
            string description = projectGateway.GetDescription(projectId);
            DateTime? proposalDate = null; if (projectGateway.GetProposalDate(projectId).HasValue) proposalDate = projectGateway.GetProposalDate(projectId);
            DateTime? startDate = null; if (projectGateway.GetStartDate(projectId).HasValue) startDate = projectGateway.GetStartDate(projectId);
            DateTime? endDate = null; if (projectGateway.GetEndDate(projectId).HasValue) endDate = projectGateway.GetEndDate(projectId);
            int clientId = projectGateway.GetClientID(projectId);
            string clientProjectNumber = projectGateway.GetClientProjectNumber(projectId);
            int? libraryCategoriesId = null; if (projectGateway.GetLibraryCategoriesId(projectId).HasValue) libraryCategoriesId = (int)projectGateway.GetLibraryCategoriesId(projectId);
            bool fairWageApplies = projectGateway.GetFairWageApplies(projectId);

            // ... Insert Project
            Project project = new Project(projectTDS);
            project.Insert(countryId, officeId, projectLeadId, salesmanId, projectNumber, projectType, projectState, name, description, proposalDate, startDate, endDate, clientId, clientPrimaryContactID, clientSecondaryContactID, clientProjectNumber, deleted, OriginalProjectID, projectNumberCopy, libraryCategoriesId, provinceId, cityId, Int32.Parse(hdfCompanyId.Value.Trim()), countyId, fairWageApplies);

            // ... Insert History
            ProjectHistory projectHistory = new ProjectHistory(projectTDS);
            projectHistory.Insert(0, 1, projectState, DateTime.Now, Convert.ToInt32(Session["loginID"]), Int32.Parse(hdfCompanyId.Value.Trim()));
        }
        protected void btnExportList_Click(object sender, EventArgs e)
        {
            string url = "";

            string headerValues = "";
            int totalColumnsExport = 53;
            int totalColumnsPreview = 52;
            string client = "";
            string name = "";
            string project = "";
            string title = "Rehab Assessment Search Results";
            string columnsForReport = "";
            int j;

            // ... for client
            int currentClientId = Int32.Parse(hdfCurrentClientId.Value.ToString());
            int companyId = Int32.Parse(hdfCompanyId.Value.Trim());

            CompaniesGateway companiesGateway = new CompaniesGateway();
            companiesGateway.LoadByCompaniesId(currentClientId, companyId);
            client += "Client: " + companiesGateway.GetName(currentClientId);

            // ... for project
            int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());
            ProjectGateway projectGateway = new ProjectGateway();
            projectGateway.LoadByProjectId(currentProjectId);
            project = projectGateway.GetName(currentProjectId);
            name = client + " > Project: " + project + " (" + projectGateway.GetProjectNumber(currentProjectId) + ")";

            // ... for title view
            if (hdfBtnOrigin.Value == "Go")
            {
                int viewId = Int32.Parse(ddlView.SelectedValue.Trim());

                // ... Load name view
                WorkViewGateway workViewGateway = new WorkViewGateway();
                workViewGateway.LoadByViewId(viewId, companyId);

                title = workViewGateway.GetName(viewId);
            }

            // ... For comments option
            string comments = "None";

            headerValues = "";
            columnsForReport = "";

            // Establishing header values
            if (grdRANavigator.Columns[2].Visible) headerValues += "ID (Section)";
            if (grdRANavigator.Columns[3].Visible) headerValues += " * Old CWP ID";
            if (grdRANavigator.Columns[4].Visible) headerValues += " * Sub Area";
            if (grdRANavigator.Columns[5].Visible) headerValues += " * Street";
            if (grdRANavigator.Columns[6].Visible) headerValues += " * USMH";
            if (grdRANavigator.Columns[7].Visible) headerValues += " * DSMH";
            if (grdRANavigator.Columns[8].Visible) headerValues += " * Pre-Flush Date";
            if (grdRANavigator.Columns[9].Visible) headerValues += " * Pre-Video Date";
            if (grdRANavigator.Columns[10].Visible) headerValues += " * Map Size";
            if (grdRANavigator.Columns[11].Visible) headerValues += " * Map Length";
            if (grdRANavigator.Columns[12].Visible) headerValues += " * Thickness";
            if (grdRANavigator.Columns[13].Visible) headerValues += " * Size_";
            if (grdRANavigator.Columns[14].Visible) headerValues += " * Length";
            if (grdRANavigator.Columns[15].Visible) headerValues += " * Comments";
            if (grdRANavigator.Columns[16].Visible) headerValues += " * VideoLength";
            if (grdRANavigator.Columns[17].Visible) headerValues += " * Laterals";
            if (grdRANavigator.Columns[18].Visible) headerValues += " * LiveLaterals";
            if (grdRANavigator.Columns[19].Visible) headerValues += " * ClientID";
            if (grdRANavigator.Columns[20].Visible) headerValues += " * P1Date";
            if (grdRANavigator.Columns[21].Visible) headerValues += " * CXIsRemoved";
            if (grdRANavigator.Columns[22].Visible) headerValues += " * M1Date";
            if (grdRANavigator.Columns[23].Visible) headerValues += " * MeasurementTakenBy";
            if (grdRANavigator.Columns[24].Visible) headerValues += " * MaterialType";
            if (grdRANavigator.Columns[25].Visible) headerValues += " * USMHAddress";
            if (grdRANavigator.Columns[26].Visible) headerValues += " * USMHDepth";
            if (grdRANavigator.Columns[27].Visible) headerValues += " * USMHMouth12";
            if (grdRANavigator.Columns[28].Visible) headerValues += " * USMHMouth1";
            if (grdRANavigator.Columns[29].Visible) headerValues += " * USMHMouth2";
            if (grdRANavigator.Columns[30].Visible) headerValues += " * USMHMouth3";
            if (grdRANavigator.Columns[31].Visible) headerValues += " * USMHMouth4";
            if (grdRANavigator.Columns[32].Visible) headerValues += " * USMHMouth5";
            if (grdRANavigator.Columns[33].Visible) headerValues += " * DSMHAddress";
            if (grdRANavigator.Columns[34].Visible) headerValues += " * DSMHDepth";
            if (grdRANavigator.Columns[35].Visible) headerValues += " * DSMHMouth12";
            if (grdRANavigator.Columns[36].Visible) headerValues += " * DSMHMouth1";
            if (grdRANavigator.Columns[37].Visible) headerValues += " * DSMHMouth2";
            if (grdRANavigator.Columns[38].Visible) headerValues += " * DSMHMouth3";
            if (grdRANavigator.Columns[39].Visible) headerValues += " * DSMHMouth4";
            if (grdRANavigator.Columns[40].Visible) headerValues += " * DSMHMouth5";
            if (grdRANavigator.Columns[41].Visible) headerValues += " * TrafficControl";
            if (grdRANavigator.Columns[42].Visible) headerValues += " * SiteDetails";
            if (grdRANavigator.Columns[43].Visible) headerValues += " * PipeSizeChange";
            if (grdRANavigator.Columns[44].Visible) headerValues += " * StandardBypass";
            if (grdRANavigator.Columns[45].Visible) headerValues += " * StandardBypassComments";
            if (grdRANavigator.Columns[46].Visible) headerValues += " * TrafficControlDetails";
            if (grdRANavigator.Columns[47].Visible) headerValues += " * MeasurementType";
            if (grdRANavigator.Columns[48].Visible) headerValues += " * MeasurementFromMH";
            if (grdRANavigator.Columns[49].Visible) headerValues += " * VideoDoneFromMH";
            if (grdRANavigator.Columns[50].Visible) headerValues += " * VideoDoneToMH";
            if (grdRANavigator.Columns[51].Visible) headerValues += " * RoboticPrepCompleted";
            if (grdRANavigator.Columns[52].Visible) headerValues += " * RoboticPrepCompleted Date";

            // Establishing columns to display
            string[] columnsExcel = headerValues.Split('*');

            // ... for visible columns
            for (int i = 0; i < columnsExcel.Length; i++)
            {
                j = i + 1;
                columnsForReport += "&header" + j + "=" + columnsExcel[i].Trim();
            }

            // ... For not visible columns
            for (int i = columnsExcel.Length; i < totalColumnsExport; i++)
            {
                j = i + 1;
                columnsForReport += "&header" + j + "=None";
            }

            // Report call
            Page.Validate();
            if (Page.IsValid)
            {
                PostPageChanges();
                title = title.Replace("'", "%27");
                Response.Write("<script language='javascript'> {window.open('./ra_print_search_results_report.aspx?" + columnsForReport + "&comments=" + comments + "&totalColumnsPreview=" + totalColumnsPreview + "&totalColumnsExport=" + totalColumnsExport + "&totalSelectedColumns=" + columnsExcel.Length + "&name=" + Server.UrlEncode(name) + "&title=" + Server.UrlEncode(title) + "&format=excel', '_blank', 'toolbar=no, location=no, directories=no, status=yes, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=800, height=680');}</script>");
            }

            if (url != "") Response.Redirect(url);
        }
        // ////////////////////////////////////////////////////////////////////////
        // PRIVATE METHODS
        //
        private void Save()
        {
            bool exists = false;

            // Validate page
            if (Page.IsValid)
            {
                int projectIdToSave = Int32.Parse(hdfSelectedProjectId.Value);

                ProjectSelectProjectLastUsedProjectsGateway projectSelectProjectLastUsedProjectsVerifyGateway = new ProjectSelectProjectLastUsedProjectsGateway(projectSelectProjectTDS);
                ProjectSelectProjectLastUsedProjects projectSelectProjectLastUsedProjectsVerify = new ProjectSelectProjectLastUsedProjects(projectSelectProjectLastUsedProjectsVerifyGateway.Data);
                exists = projectSelectProjectLastUsedProjectsVerify.ExistProject(projectIdToSave);

                if (exists)
                {
                    // New Data
                    DateTime newLastLoggedInDate = DateTime.Now;

                    // Update if exists
                    ProjectSelectProjectLastUsedProjects model = new ProjectSelectProjectLastUsedProjects(projectSelectProjectTDS);
                    model.UpdateLogginDate(projectIdToSave, newLastLoggedInDate);

                    Session["projectSelectProjectTDS"] = projectSelectProjectTDS;
                    Session["projectLastUsedProjects"] = projectSelectProjectTDS.LastUsedProjects;
                }

                // If doesn't exists at grid
                if (!exists)
                {
                    if (projectSelectProjectLastUsedProjectsVerifyGateway.Table.Rows.Count < 5)
                    {
                        // Add data if exist at grid's
                        ProjectAdd();
                    }
                    else
                    {
                        if (projectSelectProjectLastUsedProjectsVerifyGateway.Table.Rows.Count == 5)
                        {
                            // New Data
                            int newProjectId = Int32.Parse(hdfSelectedProjectId.Value);
                            int newCompanyId = Int32.Parse(hdfCompanyId.Value);
                            int newUserId = Convert.ToInt32(Session["loginID"]);
                            DateTime newLastLoggedInDate = DateTime.Now;

                            ProjectGateway projectGateway = new ProjectGateway();
                            projectGateway.LoadByProjectId(newProjectId);
                            string newProjectName = projectGateway.GetName(newProjectId) + " (" + projectGateway.GetProjectNumber(newProjectId) + ")";

                            // Update if exists
                            ProjectSelectProjectLastUsedProjects model = new ProjectSelectProjectLastUsedProjects(projectSelectProjectTDS);
                            model.Update(newProjectId, newUserId, newLastLoggedInDate, newCompanyId, false, newProjectName);

                            Session["projectSelectProjectTDS"] = projectSelectProjectTDS;
                            Session["projectLastUsedProjects"] = projectSelectProjectTDS.LastUsedProjects;
                        }
                    }
                }

                // Update data at bd
                UpdateDatabase();
            }
        }
        private void ProjectAdd()
        {
            if (Page.IsValid)
            {
                int projectId = Int32.Parse(hdfSelectedProjectId.Value);
                int companyId = Int32.Parse(hdfCompanyId.Value);
                int loginId = Convert.ToInt32(Session["loginID"]);
                DateTime lastLoggedInDate = DateTime.Now;
                bool deleted = false;

                ProjectGateway projectGateway = new ProjectGateway();
                projectGateway.LoadByProjectId(projectId);
                string projectName = projectGateway.GetName(projectId) + " (" + projectGateway.GetProjectNumber(projectId) + ")";

                ProjectSelectProjectLastUsedProjects model = new ProjectSelectProjectLastUsedProjects(projectSelectProjectTDS);
                model.Insert(projectId, loginId, lastLoggedInDate, companyId, deleted, projectName, false);

                Session.Remove("lastUsedProjectsDummy");
                Session["projectSelectProjectTDS"] = projectSelectProjectTDS;
                Session["projectLastUsedProjects"] = projectSelectProjectTDS.LastUsedProjects;
            }
        }
        protected void btnExportList_Click(object sender, EventArgs e)
        {
            mForm7 master = (mForm7)this.Master;
            ScriptManager scriptManager = (ScriptManager)master.FindControl("ScriptManagerMaster7");

            if (!scriptManager.IsInAsyncPostBack)
            {
                string url = "";
                string headerValues = "";
                int totalColumnsExport = 85;
                int totalColumnsPreview = 84;
                string client = "";
                string name = "";
                string project = "";
                string title = "Full Length Lining Search Results";
                string columnsForReport = "";
                int j;

                // ... for client
                int companyId = Int32.Parse(hdfCompanyId.Value);
                int currentClientId = Int32.Parse(hdfCurrentClientId.Value.ToString());
                CompaniesGateway companiesGateway = new CompaniesGateway();
                companiesGateway.LoadByCompaniesId(currentClientId, companyId);
                client += "Client: " + companiesGateway.GetName(currentClientId);

                // ... for project
                int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());
                ProjectGateway projectGateway = new ProjectGateway();
                projectGateway.LoadByProjectId(currentProjectId);
                project = projectGateway.GetName(currentProjectId);
                name = client + " > Project: " + project + " (" + projectGateway.GetProjectNumber(currentProjectId) + ")";

                // ... for title view
                if (hdfBtnOrigin.Value == "Go")
                {
                    int viewId = Int32.Parse(ddlView.SelectedValue.Trim());

                    // ... Load name view
                    WorkViewGateway workViewGateway = new WorkViewGateway();
                    workViewGateway.LoadByViewId(viewId, companyId);

                    title = workViewGateway.GetName(viewId);
                }

                // ... For comments option
                string comments = "None";

                headerValues = "";
                columnsForReport = "";

                // Establishing header values
                if (grdFLNavigator.Columns[2].Visible) headerValues += "ID (Section)";
                if (grdFLNavigator.Columns[3].Visible) headerValues += " * Old CWP ID";
                if (grdFLNavigator.Columns[4].Visible) headerValues += " * Sub Area";
                if (grdFLNavigator.Columns[5].Visible) headerValues += " * Street";
                if (grdFLNavigator.Columns[6].Visible) headerValues += " * USMH";
                if (grdFLNavigator.Columns[7].Visible) headerValues += " * DSMH";
                if (grdFLNavigator.Columns[8].Visible) headerValues += " * Proposed Lining Date";
                if (grdFLNavigator.Columns[9].Visible) headerValues += " * Deadline Lining Date";
                if (grdFLNavigator.Columns[10].Visible) headerValues += " * P1 Date";
                if (grdFLNavigator.Columns[11].Visible) headerValues += " * M1 Date";
                if (grdFLNavigator.Columns[12].Visible) headerValues += " * M2 Date";
                if (grdFLNavigator.Columns[13].Visible) headerValues += " * Install Date";
                if (grdFLNavigator.Columns[14].Visible) headerValues += " * Final Video Date";
                if (grdFLNavigator.Columns[15].Visible) headerValues += " * Confirmed Size";
                if (grdFLNavigator.Columns[16].Visible) headerValues += " * Actual Length";
                if (grdFLNavigator.Columns[17].Visible) headerValues += " * Thickness";
                if (grdFLNavigator.Columns[18].Visible) headerValues += " * Comments";
                if (grdFLNavigator.Columns[19].Visible) headerValues += " * Map Size";
                if (grdFLNavigator.Columns[20].Visible) headerValues += " * Map Length";
                if (grdFLNavigator.Columns[21].Visible) headerValues += " * Video Length";
                if (grdFLNavigator.Columns[22].Visible) headerValues += " * Laterals";
                if (grdFLNavigator.Columns[23].Visible) headerValues += " * Live Laterals";
                if (grdFLNavigator.Columns[24].Visible) headerValues += " * Client ID";
                if (grdFLNavigator.Columns[25].Visible) headerValues += " * Pre-Flush Date";
                if (grdFLNavigator.Columns[26].Visible) headerValues += " * Pre-Video Date";
                if (grdFLNavigator.Columns[27].Visible) headerValues += " * Issue Identified";
                if (grdFLNavigator.Columns[28].Visible) headerValues += " * Issue LFS";
                if (grdFLNavigator.Columns[29].Visible) headerValues += " * Issue Client";
                if (grdFLNavigator.Columns[30].Visible) headerValues += " * Issue Sales";
                if (grdFLNavigator.Columns[31].Visible) headerValues += " * Issue Given To Client";
                if (grdFLNavigator.Columns[32].Visible) headerValues += " * Issue Investigation";
                if (grdFLNavigator.Columns[33].Visible) headerValues += " * Issue Resolved";
                if (grdFLNavigator.Columns[34].Visible) headerValues += " * CXIs Removed";
                if (grdFLNavigator.Columns[35].Visible) headerValues += " * Material Type";
                if (grdFLNavigator.Columns[36].Visible) headerValues += " * USMH Address";
                if (grdFLNavigator.Columns[37].Visible) headerValues += " * USMH Depth";
                if (grdFLNavigator.Columns[38].Visible) headerValues += " * USMH Mouth12";
                if (grdFLNavigator.Columns[39].Visible) headerValues += " * USMH Mouth1";
                if (grdFLNavigator.Columns[40].Visible) headerValues += " * USMH Mouth2";
                if (grdFLNavigator.Columns[41].Visible) headerValues += " * USMH Mouth3";
                if (grdFLNavigator.Columns[42].Visible) headerValues += " * USMH Mouth4";
                if (grdFLNavigator.Columns[43].Visible) headerValues += " * USMH Mouth5";
                if (grdFLNavigator.Columns[44].Visible) headerValues += " * DSMH Address";
                if (grdFLNavigator.Columns[45].Visible) headerValues += " * DSMH Depth";
                if (grdFLNavigator.Columns[46].Visible) headerValues += " * DSMH Mouth12";
                if (grdFLNavigator.Columns[47].Visible) headerValues += " * DSMH Mouth1";
                if (grdFLNavigator.Columns[48].Visible) headerValues += " * DSMH Mouth2";
                if (grdFLNavigator.Columns[49].Visible) headerValues += " * DSMH Mouth3";
                if (grdFLNavigator.Columns[50].Visible) headerValues += " * DSMH Mouth4";
                if (grdFLNavigator.Columns[51].Visible) headerValues += " * DSMH Mouth5";
                if (grdFLNavigator.Columns[52].Visible) headerValues += " * Traffic Control";
                if (grdFLNavigator.Columns[53].Visible) headerValues += " * Site Details";
                if (grdFLNavigator.Columns[54].Visible) headerValues += " * Pipe Size Change";
                if (grdFLNavigator.Columns[55].Visible) headerValues += " * Standard Bypass";
                if (grdFLNavigator.Columns[56].Visible) headerValues += " * Standard Bypass Comments";
                if (grdFLNavigator.Columns[57].Visible) headerValues += " * Traffic Control Details";
                if (grdFLNavigator.Columns[58].Visible) headerValues += " * Measurement Type";
                if (grdFLNavigator.Columns[59].Visible) headerValues += " * Measurement FromMH";
                if (grdFLNavigator.Columns[60].Visible) headerValues += " * Video Done From MH";
                if (grdFLNavigator.Columns[61].Visible) headerValues += " * Video Done To MH";
                if (grdFLNavigator.Columns[62].Visible) headerValues += " * M1 Measurement Taken By";
                if (grdFLNavigator.Columns[63].Visible) headerValues += " * M2 Measurement Taken By";
                if (grdFLNavigator.Columns[64].Visible) headerValues += " * Drop Pipe";
                if (grdFLNavigator.Columns[65].Visible) headerValues += " * Drop Pipe Invert Depth";
                if (grdFLNavigator.Columns[66].Visible) headerValues += " * Capped Laterals";
                if (grdFLNavigator.Columns[67].Visible) headerValues += " * Line With ID";
                if (grdFLNavigator.Columns[68].Visible) headerValues += " * Hydran tAddress";
                if (grdFLNavigator.Columns[69].Visible) headerValues += " * Distance To Inversion MH";
                if (grdFLNavigator.Columns[70].Visible) headerValues += " * Hydro Wire Within 10Ft Of Inversion MH";
                if (grdFLNavigator.Columns[71].Visible) headerValues += " * Surface Grade";
                if (grdFLNavigator.Columns[72].Visible) headerValues += " * Hydro Pulley";
                if (grdFLNavigator.Columns[73].Visible) headerValues += " * Fridge Cart";
                if (grdFLNavigator.Columns[74].Visible) headerValues += " * Two Pump";
                if (grdFLNavigator.Columns[75].Visible) headerValues += " * Six Bypass";
                if (grdFLNavigator.Columns[76].Visible) headerValues += " * Scaffolding";
                if (grdFLNavigator.Columns[77].Visible) headerValues += " * Winch Extention";
                if (grdFLNavigator.Columns[78].Visible) headerValues += " * Extra Generator";
                if (grdFLNavigator.Columns[79].Visible) headerValues += " * Grey Cable Extension";
                if (grdFLNavigator.Columns[80].Visible) headerValues += " * Easement Mats";
                if (grdFLNavigator.Columns[81].Visible) headerValues += " * Ramp Required";
                if (grdFLNavigator.Columns[82].Visible) headerValues += " * Camera Skid";
                if (grdFLNavigator.Columns[83].Visible) headerValues += " * RoboticPrepCompleted";
                if (grdFLNavigator.Columns[84].Visible) headerValues += " * RoboticPrepCompleted Date";

                // Establishing columns to display
                string[] columnsExcel = headerValues.Split('*');

                // ... for visible columns
                for (int i = 0; i < columnsExcel.Length; i++)
                {
                    j = i + 1;
                    columnsForReport += "&header" + j + "=" + columnsExcel[i].Trim();
                }

                // ... For not visible columns
                for (int i = columnsExcel.Length; i < totalColumnsExport; i++)
                {
                    j = i + 1;
                    columnsForReport += "&header" + j + "=None";
                }

                // Report call
                Page.Validate();
                if (Page.IsValid)
                {
                    PostPageChanges();
                    title = title.Replace("'", "%27");
                    Response.Write("<script language='javascript'> {window.open('./fl_print_search_results_report.aspx?" + columnsForReport + "&comments=" + comments + "&totalColumnsPreview=" + totalColumnsPreview + "&totalColumnsExport=" + totalColumnsExport + "&totalSelectedColumns=" + columnsExcel.Length + "&name=" + Server.UrlEncode(name) + "&title=" + Server.UrlEncode(title) + "&format=excel', '_blank', 'toolbar=no, location=no, directories=no, status=yes, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=800, height=680');}</script>");
                }

                if (url != "") Response.Redirect(url);
            }
        }
        protected void btnPrintLateralLocationSheet_Click(object sender, EventArgs e)
        {
            mForm7 master = (mForm7)this.Master;
            ScriptManager scriptManager = (ScriptManager)master.FindControl("ScriptManagerMaster7");

            if (!scriptManager.IsInAsyncPostBack)
            {
                string url = "";
                string client = "";
                string name = "";
                string project = "";
                string title = "Full Length Lining Search Results";

                // ... for client
                int currentClientId = Int32.Parse(hdfCurrentClientId.Value.ToString());
                int companyId = Int32.Parse(hdfCompanyId.Value);
                CompaniesGateway companiesGateway = new CompaniesGateway();
                companiesGateway.LoadByCompaniesId(currentClientId, companyId);
                client += "Client: " + companiesGateway.GetName(currentClientId);

                // ... for project
                int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());
                ProjectGateway projectGateway = new ProjectGateway();
                projectGateway.LoadByProjectId(currentProjectId);
                project = projectGateway.GetName(currentProjectId);
                name = client + " > Project: " + project + " (" + projectGateway.GetProjectNumber(currentProjectId) + ")";

                // ... for title view
                if (hdfBtnOrigin.Value == "Go")
                {
                    int viewId = Int32.Parse(ddlView.SelectedValue.Trim());

                    // ... Load name view
                    WorkViewGateway workViewGateway = new WorkViewGateway();
                    workViewGateway.LoadByViewId(viewId, companyId);

                    title = workViewGateway.GetName(viewId);
                }

                // Report call
                Page.Validate();
                if (Page.IsValid)
                {
                    PostPageChanges();

                    int assetId = GetAssetId();
                    if (assetId > 0)
                    {
                        WorkGateway workGateway = new WorkGateway();
                        workGateway.LoadByProjectIdAssetIdWorkType(Int32.Parse(hdfCurrentProjectId.Value), assetId, "Full Length Lining", Int32.Parse(hdfCompanyId.Value));
                        int workId = workGateway.GetWorkId(assetId, "Full Length Lining", Int32.Parse(hdfCurrentProjectId.Value));

                        FullLengthLiningWorkDetailsGateway fullLengthLiningWorkDetailsGateway = new FullLengthLiningWorkDetailsGateway();
                        fullLengthLiningWorkDetailsGateway.LoadByWorkIdAssetId(workId, assetId, Int32.Parse(hdfCompanyId.Value));
                        string measuredFrom = fullLengthLiningWorkDetailsGateway.GetMeasurementFromMh(workId);

                        Response.Write("<script language='javascript'> {window.open('./../../CWP/Common/lateral_location_sheet_report.aspx?source_page=lm&project_id=" + hdfCurrentProjectId.Value + "&client_id=" + hdfCurrentClientId.Value + "&work_id=" + workId.ToString() + "&measured_from=" + measuredFrom + "&asset_id=" + assetId.ToString() + "', '_blank', 'toolbar=no, location=no, directories=no, status=yes, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=800, height=680');}</script>");
                    }
                    else
                    {
                        cvSelection.IsValid = false;
                    }
                }

                if (url != "") Response.Redirect(url);
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            if (!IsPostBack)
            {
                // Security check
                if (!(Convert.ToBoolean(Session["sgLFS_CWP_JUNCTIONLINING_VIEW"])))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                }

                // Validate query string
                if (((string)Request.QueryString["source_page"] == null) || ((string)Request.QueryString["client_id"] == null) || ((string)Request.QueryString["project_id"] == null))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in jls_navigator.aspx");
                }

                // Tag Page
                hdfCompanyId.Value = Session["companyID"].ToString();
                hdfCurrentProjectId.Value = Request.QueryString["project_id"].ToString();
                hdfCurrentClientId.Value = Request.QueryString["client_id"].ToString();

                // Prepare initial data
                // ... For sortByList
                odsSortByList.DataBind();
                ddlSortBy.DataSourceID = "odsSortByList";
                ddlSortBy.DataValueField = "SortID";
                ddlSortBy.DataTextField = "Name";
                ddlSortBy.DataBind();

                // ... For
                odsViewForDisplayList.DataBind();
                ddlCondition1.DataSourceID = "odsViewForDisplayList";
                ddlCondition1.DataValueField = "ConditionID";
                ddlCondition1.DataTextField = "Name";
                ddlCondition1.DataBind();

                // ... for client
                int currentClientId = Int32.Parse(hdfCurrentClientId.Value.ToString());
                int companyId = Int32.Parse(hdfCompanyId.Value);

                CompaniesGateway companiesGateway = new CompaniesGateway();
                companiesGateway.LoadByCompaniesId(currentClientId, companyId);
                lblTitleClientName.Text = "Client: " + companiesGateway.GetName(currentClientId);

                // ... for project
                int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());
                ProjectGateway projectGateway = new ProjectGateway();
                projectGateway.LoadByProjectId(currentProjectId);
                string name = projectGateway.GetName(currentProjectId);
                if (name.Length > 23) name = name.Substring(0, 20) + "...";
                lblTitleProjectName.Text = " > Project: " + name + " (" + projectGateway.GetProjectNumber(currentProjectId) + ")";

                // If coming from

                // ... Left Menu
                if ((Request.QueryString["source_page"] == "lm") || (Request.QueryString["source_page"] == "select_project.aspx"))
                {
                    tdNoResults.Visible = false;
                }

                // ... jls_navigator2.aspx
                if (Request.QueryString["source_page"] == "jls_navigator2.aspx")
                {
                    RestoreNavigatorState();
                    if ((string)Request.QueryString["no_results"] == "yes")
                    {
                        tdNoResults.Visible = true;
                    }
                    else
                    {
                        tdNoResults.Visible = true;
                    }
                }
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            if (!IsPostBack)
            {
                // Security check
                if (!(Convert.ToBoolean(Session["sgLFS_CWP_FULLLENGTHLINING_VIEW"]) && Convert.ToBoolean(Session["sgLFS_CWP_FULLLENGTHLINING_EDIT"])))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                }

                // Validate query string
                if (((string)Request.QueryString["source_page"] == null) || ((string)Request.QueryString["client_id"] == null) || ((string)Request.QueryString["project_id"] == null) || ((string)Request.QueryString["asset_id"] == null) || ((string)Request.QueryString["active_tab"] == null))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in fl_summary.aspx");
                }

                // Tag Page
                TagPage();

                Session.Remove("flAddLateralsNewDummy");
                Session.Remove("wetOutCatalystsDetailsDummy");

                // If comming from
                int companyId = Int32.Parse(hdfCompanyId.Value.Trim());
                int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());
                int assetId = Int32.Parse(hdfAssetId.Value.Trim());
                string workType = hdfWorkType.Value;
                int workId = Int32.Parse(hdfWorkId.Value);

                // ... fl_navigator2.aspx
                if (Request.QueryString["source_page"] == "fl_navigator2.aspx")
                {
                    StoreNavigatorState();
                    ViewState["update"] = "no";

                    // Set initial tab
                    if ((string)Session["dialogOpenedFll"] != "1")
                    {
                        hdfActiveTab.Value = Request.QueryString["active_tab"];

                        fullLengthLiningTDS = new FullLengthLiningTDS();

                        FullLengthLiningSectionDetails fullLengthLiningSectionDetails = new FullLengthLiningSectionDetails(fullLengthLiningTDS);
                        fullLengthLiningSectionDetails.LoadByWorkId(workId, companyId);

                        FullLengthLiningWorkDetails fullLengthLiningWorkDetails = new FullLengthLiningWorkDetails(fullLengthLiningTDS);
                        fullLengthLiningWorkDetails.LoadByWorkIdAssetId(workId, assetId, companyId);

                        FullLengthLiningLateralDetails fullLengthLiningLateralDetails = new FullLengthLiningLateralDetails(fullLengthLiningTDS);
                        fullLengthLiningLateralDetails.LoadForEdit(workId, assetId, companyId, currentProjectId);

                        FullLengthLiningWetOutCatalystsDetails fullLengthLiningWetOutCatalystsDetails = new FullLengthLiningWetOutCatalystsDetails(fullLengthLiningTDS);
                        fullLengthLiningWetOutCatalystsDetails.LoadAll(workId, companyId);
                    }
                    else
                    {
                        hdfActiveTab.Value = (string)Session["activeTabFll"];

                        // Restore datasets
                        fullLengthLiningTDS = (FullLengthLiningTDS)Session["fullLengthLiningTDS"];
                    }

                    tcFlDetails.ActiveTabIndex = Int32.Parse(hdfActiveTab.Value);

                    // Store dataset
                    Session["fullLengthLiningTDS"] = fullLengthLiningTDS;
                }

                // ... fl_delete.aspx or fl_edit.aspx
                if ((Request.QueryString["source_page"] == "fl_delete.aspx") || (Request.QueryString["source_page"] == "fl_edit.aspx"))
                {
                    StoreNavigatorState();
                    ViewState["update"] = Request.QueryString["update"];

                    // Restore dataset
                    fullLengthLiningTDS = (FullLengthLiningTDS)Session["fullLengthLiningTDS"];

                    // ... Set initial tab
                    if ((string)Session["dialogOpenedFll"] != "1")
                    {
                        hdfActiveTab.Value = Request.QueryString["active_tab"];
                    }
                    else
                    {
                        hdfActiveTab.Value = (string)Session["activeTabFll"];
                    }

                    tcFlDetails.ActiveTabIndex = Int32.Parse(hdfActiveTab.Value);
                }

                // Prepare initial data
                // ... for client
                int currentClientId = Int32.Parse(hdfCurrentClientId.Value.ToString());

                CompaniesGateway companiesGateway = new CompaniesGateway();
                companiesGateway.LoadByCompaniesId(currentClientId, companyId);
                lblTitleClientName.Text = "Client: " + companiesGateway.GetName(currentClientId);

                // ... for project
                ProjectGateway projectGateway = new ProjectGateway();
                projectGateway.LoadByProjectId(currentProjectId);
                string name = projectGateway.GetName(currentProjectId);
                if (name.Length > 23) name = name.Substring(0, 20) + "...";
                lblTitleProjectName.Text = " > Project: " + name + " (" + projectGateway.GetProjectNumber(currentProjectId) + ") > Selected Section";

                // ... for wet out section list
                AssetSewerSectionList assetSewerSectionList = new AssetSewerSectionList();
                assetSewerSectionList.LoadAndAddItem(Int32.Parse(hdfCurrentProjectId.Value), hdfWorkType.Value, "-1", "(All)", Int32.Parse(hdfCompanyId.Value));
                cbxlWetOutDataSectionId.DataSource = assetSewerSectionList.Table;
                cbxlWetOutDataSectionId.DataValueField = "SectionID";
                cbxlWetOutDataSectionId.DataTextField = "FlowOrderID";
                cbxlWetOutDataSectionId.DataBind();

                cbxlInversionDataSectionId.DataSource = assetSewerSectionList.Table;
                cbxlInversionDataSectionId.DataValueField = "SectionID";
                cbxlInversionDataSectionId.DataTextField = "FlowOrderID";
                cbxlInversionDataSectionId.DataBind();

                // ... Data for current full length lining work
                LoadFullLengthLiningData(currentProjectId, assetId, companyId);

                // Databind
                Page.DataBind();

                // Especial load for Run details
                string runDetails = hdfRunDetails.Value;
                WorkFullLengthLiningWetOutGateway workFullLengthLiningWetOutGateway = new WorkFullLengthLiningWetOutGateway();
                workFullLengthLiningWetOutGateway.LoadByWorkId(workId, companyId);

                // ... Verify if work has cipp information to load run details
                if (workFullLengthLiningWetOutGateway.Table.Rows.Count > 0)
                {
                    string[] runDetailsList = runDetails.Split('>');
                    for (int i = 0; i < runDetailsList.Length; i++)
                    {
                        cbxlWetOutDataSectionId.Items.FindByValue(runDetailsList[i]).Selected = true;
                        cbxlInversionDataSectionId.Items.FindByValue(runDetailsList[i]).Selected = true;
                    }
                }
                else
                {
                    if (cbxlWetOutDataSectionId.Items.Count > 1)
                    {
                        cbxlWetOutDataSectionId.Items.FindByValue(hdfSectionId.Value).Selected = true;
                    }
                }
            }
            else
            {
                // Restore datasets
                fullLengthLiningTDS = (FullLengthLiningTDS)Session["fullLengthLiningTDS"];

                // Set initial tab
                int activeTab = Int32.Parse(hdfActiveTab.Value);
                tcFlDetails.ActiveTabIndex = activeTab;

                // Load summary for inversionfield cure record
                int companyId =Int32.Parse(hdfCompanyId.Value);
                int workId = Int32.Parse(hdfWorkId.Value);

                FlInversionFieldCureRecord FlInversionFieldCureRecordForSummary = new FlInversionFieldCureRecord();
                FlInversionFieldCureRecordForSummary.Load(workId, companyId);
                if (FlInversionFieldCureRecordForSummary.Table.Rows.Count > 0)
                {
                    lblInversionDataFieldCureRecordSummary.Text = FlInversionFieldCureRecordForSummary.GetSummary();
                }

            }
        }
        protected void btnExportList_Click(object sender, EventArgs e)
        {
            string url = "";
            string headerValues = "";
            int totalColumnsExport = 40;
            int totalColumnsPreview = 39;
            string client = "";
            string name = "";
            string project = "";
            string title = "Point Repairs Search Results";
            string columnsForReport = "";
            int j;

            // ... for client
            int currentClientId = Int32.Parse(hdfCurrentClientId.Value.ToString());
            int companyId = Int32.Parse(hdfCompanyId.Value.Trim());

            CompaniesGateway companiesGateway = new CompaniesGateway();
            companiesGateway.LoadByCompaniesId(currentClientId, companyId);
            client += "Client: " + companiesGateway.GetName(currentClientId);

            // ... for project
            int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());
            ProjectGateway projectGateway = new ProjectGateway();
            projectGateway.LoadByProjectId(currentProjectId);
            project = projectGateway.GetName(currentProjectId);
            name = client + " > Project: " + project + " (" + projectGateway.GetProjectNumber(currentProjectId) + ")";

            // ... for title view
            if (hdfBtnOrigin.Value == "Go")
            {
                int viewId = Int32.Parse(ddlView.SelectedValue.Trim());

                // ... Load name view
                WorkViewGateway workViewGateway = new WorkViewGateway();
                workViewGateway.LoadByViewId(viewId, companyId);

                title = workViewGateway.GetName(viewId);
            }

            // ... For comments option
            string comments = "None";

            headerValues = "";
            columnsForReport = "";

            // Establishing header values
            if (grdPrNavigator.Columns[2].Visible) headerValues += "ID (Section)";
            if (grdPrNavigator.Columns[3].Visible) headerValues += " * Sub Area";
            if (grdPrNavigator.Columns[4].Visible) headerValues += " * Street";
            if (grdPrNavigator.Columns[5].Visible) headerValues += " * USMH";
            if (grdPrNavigator.Columns[6].Visible) headerValues += " * USMH Address";
            if (grdPrNavigator.Columns[7].Visible) headerValues += " * DSMH";
            if (grdPrNavigator.Columns[8].Visible) headerValues += " * DSMH Address";
            if (grdPrNavigator.Columns[9].Visible) headerValues += " * Map Size";
            if (grdPrNavigator.Columns[10].Visible) headerValues += " * Confirmed Size";
            if (grdPrNavigator.Columns[11].Visible) headerValues += " * Map Length";
            if (grdPrNavigator.Columns[12].Visible) headerValues += " * Steel Tape Length";
            if (grdPrNavigator.Columns[13].Visible) headerValues += " * Video Length";
            if (grdPrNavigator.Columns[14].Visible) headerValues += " * Laterals";
            if (grdPrNavigator.Columns[15].Visible) headerValues += " * Live Laterals";
            if (grdPrNavigator.Columns[16].Visible) headerValues += " * Client ID";
            if (grdPrNavigator.Columns[17].Visible) headerValues += " * Measurements Taken By";
            if (grdPrNavigator.Columns[18].Visible) headerValues += " * Pre-Flush Date";
            if (grdPrNavigator.Columns[19].Visible) headerValues += " * Pre-Video Date";
            if (grdPrNavigator.Columns[20].Visible) headerValues += " * P1 Date";
            if (grdPrNavigator.Columns[21].Visible) headerValues += " * Repair Confirmation Date";
            if (grdPrNavigator.Columns[22].Visible) headerValues += " * Traffic Control";
            if (grdPrNavigator.Columns[23].Visible) headerValues += " * Material";
            if (grdPrNavigator.Columns[24].Visible) headerValues += " * Bypass Required?";
            if (grdPrNavigator.Columns[25].Visible) headerValues += " * Robotic Prep Required?";
            if (grdPrNavigator.Columns[26].Visible) headerValues += " * CXI&rsquo;s Removed";
            if (grdPrNavigator.Columns[27].Visible) headerValues += " * Robotic Distances";
            if (grdPrNavigator.Columns[28].Visible) headerValues += " * Proposed Lining Date";
            if (grdPrNavigator.Columns[29].Visible) headerValues += " * Deadline Lining Date";
            if (grdPrNavigator.Columns[30].Visible) headerValues += " * Final Video";
            if (grdPrNavigator.Columns[31].Visible) headerValues += " * Estimated Joints";
            if (grdPrNavigator.Columns[32].Visible) headerValues += " * Joints Test Sealed";
            if (grdPrNavigator.Columns[33].Visible) headerValues += " * Issue Identified?";
            if (grdPrNavigator.Columns[34].Visible) headerValues += " * LFS Issue?";
            if (grdPrNavigator.Columns[35].Visible) headerValues += " * Client Issue?";
            if (grdPrNavigator.Columns[36].Visible) headerValues += " * Sales Issue?";
            if (grdPrNavigator.Columns[37].Visible) headerValues += " * Issue Given To Client?";
            if (grdPrNavigator.Columns[38].Visible) headerValues += " * Issue Investigation?";
            if (grdPrNavigator.Columns[39].Visible) headerValues += " * Issue Resolved?";
            if (grdPrNavigator.Columns[40].Visible) headerValues += " * Comments";
            if (grdPrNavigator.Columns[41].Visible) headerValues += " * Repair";

            // Establishing columns to display
            string[] columnsExcel = headerValues.Split('*');

            // ... for visible columns
            for (int i = 0; i < columnsExcel.Length; i++)
            {
                j = i + 1;
                columnsForReport += "&header" + j + "=" + columnsExcel[i].Trim();
            }

            // ... For not visible columns
            for (int i = columnsExcel.Length; i < totalColumnsExport; i++)
            {
                j = i + 1;
                columnsForReport += "&header" + j + "=None";
            }

            // Report call
            Page.Validate();
            if (Page.IsValid)
            {
                PostPageChanges();
                title = title.Replace("'", "%27");
                Response.Write("<script language='javascript'> {window.open('./pr_print_search_results_report.aspx?" + columnsForReport + "&comments=" + comments + "&totalColumnsPreview=" + totalColumnsPreview + "&totalColumnsExport=" + totalColumnsExport + "&totalSelectedColumns=" + columnsExcel.Length + "&name=" + Server.UrlEncode(name) + "&title=" + Server.UrlEncode(title) + "&format=excel', '_blank', 'toolbar=no, location=no, directories=no, status=yes, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=800, height=680');}</script>");
            }

            if (url != "") Response.Redirect(url);
        }
        // ////////////////////////////////////////////////////////////////////////
        // INITIAL EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            if (!IsPostBack)
            {
                // Security check
                if (!Convert.ToBoolean(Session["sgLFS_PROJECTS_COSTINGSHEETS_ADMIN"]))
                {
                    if (!(Convert.ToBoolean(Session["sgLFS_PROJECTS_COSTINGSHEETS_VIEW"]) && Convert.ToBoolean(Session["sgLFS_PROJECTS_COSTINGSHEETS_EDIT"])))
                    {
                        Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                    }
                }

                // Validate query string
                if (((string)Request.QueryString["source_page"] == null) || ((string)Request.QueryString["costing_sheet_id"] == null))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in project_combined_costing_sheets_edit.aspx");
                }

                // Tag Page
                hdfCostingSheetId.Value = Request.QueryString["costing_sheet_id"].ToString();
                hdfCompanyId.Value = Session["companyID"].ToString();
                hdfProjectId.Value = Request.QueryString["project_id"];
                hdfDataChanged.Value = Request.QueryString["data_changed"];
                hdfDataChangedMessage.Value = "Changes made to this project will not be saved.";

                ViewState["state"] = Request.QueryString["state"];
                ViewState["active_tab"] = Request.QueryString["active_tab"];
                ViewState["origin"] = Request.QueryString["origin"];
                ViewState["update"] = Request.QueryString["update"];

                projectTDS = (ProjectTDS)Session["lfsProjectTDS"];

                Session.Remove("labourHoursInformationDummy");
                Session.Remove("unitsInformationDummy");
                Session.Remove("subcontractorsInformationDummy");
                Session.Remove("materialsInformationDummy");
                Session.Remove("otherCostsInformationDummy");
                Session.Remove("revenueInformationDummy");

                // If coming from project_combined_costing_sheets_navigator.aspx or project_combined_costing_sheets_add.aspx
                int companyId = Int32.Parse(hdfCompanyId.Value);
                if (Request.QueryString["source_page"] == "project_costing_sheets_navigator.aspx" || Request.QueryString["source_page"] == "project_combined_costing_sheets_add.aspx")
                {
                    // Store Navigator State and Update control
                    StoreNavigatorState();
                    ViewState["update"] = "no";

                    // Get Costing sheet ID
                    int costingSheetId = Int32.Parse(hdfCostingSheetId.Value.Trim());

                    // Get dataset
                    projectTDS = (ProjectTDS)Session["lfsProjectTDS"];
                    projectCostingSheetInformationTDS = new ProjectCostingSheetInformationTDS();
                    labourHoursInformation = new ProjectCostingSheetInformationTDS.CombinedLabourHoursInformationDataTable();
                    unitsInformation = new ProjectCostingSheetInformationTDS.CombinedUnitsInformationDataTable();
                    subcontractorsInformation = new ProjectCostingSheetInformationTDS.CombinedSubcontractorsInformationDataTable();
                    materialsInformation = new ProjectCostingSheetInformationTDS.CombinedMaterialsInformationDataTable();
                    otherCostsInformation = new ProjectCostingSheetInformationTDS.CombinedOtherCostsInformationDataTable();
                    revenueInformation = new ProjectCostingSheetInformationTDS.CombinedRevenueInformationDataTable();

                    // Get General Data
                    ProjectCombinedCostingSheetInformationBasicInformation projectCostingSheetInformationBasicInformation = new ProjectCombinedCostingSheetInformationBasicInformation(projectCostingSheetInformationTDS);
                    projectCostingSheetInformationBasicInformation.LoadByCostingSheetId(costingSheetId, companyId);

                    ProjectCombinedCostingSheetInformationLabourHoursInformationGateway projectCostingSheetInformationLabourHoursInformationGateway = new ProjectCombinedCostingSheetInformationLabourHoursInformationGateway(projectCostingSheetInformationTDS);
                    projectCostingSheetInformationLabourHoursInformationGateway.LoadByCostingSheetId(costingSheetId, companyId);

                    ProjectCombinedCostingSheetInformationUnitsInformationGateway projectCostingSheetInformationUnitsInformationGateway = new ProjectCombinedCostingSheetInformationUnitsInformationGateway(projectCostingSheetInformationTDS);
                    projectCostingSheetInformationUnitsInformationGateway.LoadByCostingSheetId(costingSheetId, companyId);

                    ProjectCombinedCostingSheetInformationSubcontractorsInformationGateway projectCostingSheetInformationSubcontractorsInformationGateway = new ProjectCombinedCostingSheetInformationSubcontractorsInformationGateway(projectCostingSheetInformationTDS);
                    projectCostingSheetInformationSubcontractorsInformationGateway.LoadByCostingSheetId(costingSheetId, companyId);

                    ProjectCombinedCostingSheetInformationMaterialsInformationGateway projectCostingSheetInformationMaterialsInformationGateway = new ProjectCombinedCostingSheetInformationMaterialsInformationGateway(projectCostingSheetInformationTDS);
                    projectCostingSheetInformationMaterialsInformationGateway.LoadByCostingSheetId(costingSheetId, companyId);

                    ProjectCombinedCostingSheetInformationOtherCostsInformationGateway projectCostingSheetInformationOtherCostsInformationGateway = new ProjectCombinedCostingSheetInformationOtherCostsInformationGateway(projectCostingSheetInformationTDS);
                    projectCostingSheetInformationOtherCostsInformationGateway.LoadByCostingSheetId(costingSheetId, companyId);

                    projectCombinedCostingSheetInformationRevenueInformationGateway projectCombinedCostingSheetInformationRevenueInformationGateway = new projectCombinedCostingSheetInformationRevenueInformationGateway(projectCostingSheetInformationTDS);
                    projectCombinedCostingSheetInformationRevenueInformationGateway.LoadByCostingSheetId(costingSheetId, companyId);

                    Session["lfsProjectTDS"] = projectTDS;
                    Session["projectCostingSheetInformationTDS"] = projectCostingSheetInformationTDS;
                    Session["labourHoursInformation"] = projectCostingSheetInformationTDS.CombinedLabourHoursInformation;
                    Session["unitsInformation"] = projectCostingSheetInformationTDS.CombinedUnitsInformation;
                    Session["subcontractorsInformation"] = projectCostingSheetInformationTDS.CombinedSubcontractorsInformation;
                    Session["materialsInformation"] = projectCostingSheetInformationTDS.CombinedMaterialsInformation;
                    Session["otherCostsInformation"] = projectCostingSheetInformationTDS.CombinedOtherCostsInformation;
                    Session["revenueInformation"] = projectCostingSheetInformationTDS.CombinedRevenueInformation;

                    labourHoursInformation = projectCostingSheetInformationTDS.CombinedLabourHoursInformation;
                    unitsInformation = projectCostingSheetInformationTDS.CombinedUnitsInformation;
                    subcontractorsInformation = projectCostingSheetInformationTDS.CombinedSubcontractorsInformation;
                    materialsInformation = projectCostingSheetInformationTDS.CombinedMaterialsInformation;
                    otherCostsInformation = projectCostingSheetInformationTDS.CombinedOtherCostsInformation;
                    revenueInformation = projectCostingSheetInformationTDS.CombinedRevenueInformation;
                }

                // ... project_combined_costing_sheets_add.aspx
                if (Request.QueryString["source_page"] == "project_combined_costing_sheets_add.aspx")
                {
                    ViewState["update"] = "yes";
                }

                // ... left menu, project_combined_costing_sheets_edit.aspx, project_combined_costing_sheets_delete.aspx or project_combined_costing_sheets_state.aspx
                if ((Request.QueryString["source_page"] == "lm") || (Request.QueryString["source_page"] == "project_combined_costing_sheets_summary.aspx") || (Request.QueryString["source_page"] == "project_combined_costing_sheets_delete.aspx") || (Request.QueryString["source_page"] == "project_combined_costing_sheets_state.aspx"))
                {
                    // Store Navigator State and Update control
                    StoreNavigatorState();
                    ViewState["update"] = Request.QueryString["update"];
                }

                // Restore dataset
                projectTDS = (ProjectTDS)Session["lfsProjectTDS"];
                projectCostingSheetInformationTDS = (ProjectCostingSheetInformationTDS)Session["projectCostingSheetInformationTDS"];

                labourHoursInformation = (ProjectCostingSheetInformationTDS.CombinedLabourHoursInformationDataTable)Session["labourHoursInformation"];
                unitsInformation = (ProjectCostingSheetInformationTDS.CombinedUnitsInformationDataTable)Session["unitsInformation"];
                subcontractorsInformation = (ProjectCostingSheetInformationTDS.CombinedSubcontractorsInformationDataTable)Session["subcontractorsInformation"];
                materialsInformation = (ProjectCostingSheetInformationTDS.CombinedMaterialsInformationDataTable)Session["materialsInformation"];
                otherCostsInformation = (ProjectCostingSheetInformationTDS.CombinedOtherCostsInformationDataTable)Session["otherCostsInformation"];
                revenueInformation = (ProjectCostingSheetInformationTDS.CombinedRevenueInformationDataTable)Session["revenueInformation"];

                if (!Convert.ToBoolean(Session["sgLFS_PROJECTS_COSTINGSHEETS_ADMIN"]))
                {
                    // Costing Sheet state check
                    ProjectCombinedCostingSheetInformationBasicInformationGateway projectCostingSheetInformationBasicInformationGatewayForValidate = new ProjectCombinedCostingSheetInformationBasicInformationGateway(projectCostingSheetInformationTDS);
                    string state = projectCostingSheetInformationBasicInformationGatewayForValidate.GetState(Int32.Parse(hdfCostingSheetId.Value));
                    if (state == "Approved")
                    {
                        Response.Redirect("./../../error_page.aspx?error=" + "This costing sheet is approved, you can not edit it.");
                    }
                }

                ProjectGateway projectGateway = new ProjectGateway(projectTDS);
                hdfClientId.Value = projectGateway.GetClientID(Int32.Parse(hdfProjectId.Value.ToString())).ToString();

                // ... for project
                int currentProjectId = Int32.Parse(hdfProjectId.Value.ToString());
                string name = projectGateway.GetName(currentProjectId);
                if (name.Length > 23) name = name.Substring(0, 20) + "...";
                lblTitleProjectName.Text = name + " (" + projectGateway.GetProjectNumber(currentProjectId) + ")";

                // ... for client
                int currentClientId = projectGateway.GetClientID(Int32.Parse(hdfProjectId.Value.ToString()));

                CompaniesGateway companiesGateway = new CompaniesGateway();
                companiesGateway.LoadAllByCompaniesId(currentClientId, companyId);
                lblTitleClientName.Text = "Client: " + companiesGateway.GetName(currentClientId);

                LoadBasicData();
            }
            else
            {
                // Restore dataset
                projectTDS = (ProjectTDS)Session["lfsProjectTDS"];
                projectCostingSheetInformationTDS = (ProjectCostingSheetInformationTDS)Session["projectCostingSheetInformationTDS"];

                labourHoursInformation = (ProjectCostingSheetInformationTDS.CombinedLabourHoursInformationDataTable)Session["labourHoursInformation"];
                unitsInformation = (ProjectCostingSheetInformationTDS.CombinedUnitsInformationDataTable)Session["unitsInformation"];
                subcontractorsInformation = (ProjectCostingSheetInformationTDS.CombinedSubcontractorsInformationDataTable)Session["subcontractorsInformation"];
                materialsInformation = (ProjectCostingSheetInformationTDS.CombinedMaterialsInformationDataTable)Session["materialsInformation"];
                otherCostsInformation = (ProjectCostingSheetInformationTDS.CombinedOtherCostsInformationDataTable)Session["otherCostsInformation"];
                revenueInformation = (ProjectCostingSheetInformationTDS.CombinedRevenueInformationDataTable)Session["revenueInformation"];
            }
        }
        private void GrdProjectAdd()
        {
            if (Page.IsValid)
            {
                int projectId = Int32.Parse(ddlProject.SelectedValue);
                int clientId = Int32.Parse(ddlClient.SelectedValue);
                int companyId = Int32.Parse(hdfCompanyId.Value);
                int loginId = Convert.ToInt32(Session["loginID"]);
                DateTime lastLoggedInDate = DateTime.Now;
                bool deleted = false;
                string workType = hdfWorkType.Value;

                ProjectGateway projectGateway = new ProjectGateway();
                projectGateway.LoadByProjectId(projectId);
                string projectName = projectGateway.GetName(projectId) + " (" + projectGateway.GetProjectNumber(projectId) + ")";

                CompaniesGateway companiesGateway = new CompaniesGateway();
                companiesGateway.LoadByCompaniesId(clientId, companyId);
                string clientName = companiesGateway.GetName(clientId);

                SelectProjectLastUsedProjects model = new SelectProjectLastUsedProjects(selectProjectTDS);
                model.Insert(clientId, projectId, loginId, lastLoggedInDate, companyId, deleted, workType, projectName, clientName, false);

                Session.Remove("lastUsedProjectsDummy");
                Session["selectProjectTDS"] = selectProjectTDS;
                Session["lastUsedProjects"] = selectProjectTDS.LastUsedProjects;

                grdProjects.DataBind();
                grdProjects.PageIndex = grdProjects.PageCount - 1;
            }
        }
        private void Generate()
        {
            mReport1 master = (mReport1)this.Master;
            LiquiForce.LFSLive.BL.CWP.Common.LateralLocationSheetReport lateralLocationSheetReport = new LiquiForce.LFSLive.BL.CWP.Common.LateralLocationSheetReport();
            int companyId = Int32.Parse(hdfCurrentCompanyId.Value);

            // Restore TDS
            JlNavigatorTDS jlNavigatorTDS = (JlNavigatorTDS)Session["jlNavigatorTDS"];

            // Get Data
            lateralLocationSheetReport.LoadByProjectIdJlNavigatorTDS(Int32.Parse(hdfCurrentProjectId.Value), jlNavigatorTDS, companyId);

            // ... set properties to master page
            master.Data = lateralLocationSheetReport.Data;
            master.Table = lateralLocationSheetReport.TableName;

            // Get report
            if (lateralLocationSheetReport.Table.Rows.Count > 0)
            {
                master.Report = new LateralLocationSheetReport();

                // ... for client
                int currentClientId = Int32.Parse(hdfCurrentClientId.Value);
                CompaniesGateway companiesGateway = new CompaniesGateway();
                companiesGateway.LoadByCompaniesId(currentClientId, companyId);
                master.SetParameter("Client", companiesGateway.GetName(currentClientId));

                // ... for project
                int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value);
                ProjectGateway projectGateway = new ProjectGateway();
                projectGateway.LoadByProjectId(currentProjectId);
                string name = projectGateway.GetName(currentProjectId);
                master.SetParameter("Project", projectGateway.GetProjectNumber(currentProjectId));

                int loginId = Convert.ToInt32(Session["loginID"]);

                LoginGateway loginGateway = new LoginGateway();
                loginGateway.LoadByLoginId(loginId, companyId);
                string user = loginGateway.GetLastName(loginId, companyId) + " " + loginGateway.GetFirstName(loginId, companyId);
                master.SetParameter("User", user.Trim());
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            bool isFromTabClick = false;

            if (!IsPostBack)
            {
                if (!isFromTabClick)
                {
                    // Security check
                    if (!(Convert.ToBoolean(Session["sgLFS_CWP_FULLLENGTHLINING_VIEW"]) && Convert.ToBoolean(Session["sgLFS_CWP_FULLLENGTHLINING_EDIT"])))
                    {
                        Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                    }

                    // Validate query string
                    if (((string)Request.QueryString["source_page"] == null) || ((string)Request.QueryString["client_id"] == null) || ((string)Request.QueryString["project_id"] == null) || ((string)Request.QueryString["asset_id"] == null) || ((string)Request.QueryString["active_tab"] == null))
                    {
                        Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in fl_edit.aspx");
                    }

                    // Tag Page
                    TagPage();

                    // Prepare initial data
                    Session.Remove("flAddLateralsNewDummy");
                    Session.Remove("wetOutCatalystsDetailsDummy");
                    Session.Remove("materialInformationTDS");

                    materialInformationTDS = new MaterialInformationTDS();

                    // ... for wet out section list
                    AssetSewerSectionList assetSewerSectionList = new AssetSewerSectionList();
                    assetSewerSectionList.LoadAndAddItem(Int32.Parse(hdfCurrentProjectId.Value), hdfWorkType.Value, "-1", "(All)", Int32.Parse(hdfCompanyId.Value));
                    cbxlSectionId.DataSource = assetSewerSectionList.Table;
                    cbxlSectionId.DataValueField = "SectionID";
                    cbxlSectionId.DataTextField = "FlowOrderID";
                    cbxlSectionId.DataBind();

                    cbxlInversionDataSectionId.DataSource = assetSewerSectionList.Table;
                    cbxlInversionDataSectionId.DataValueField = "SectionID";
                    cbxlInversionDataSectionId.DataTextField = "FlowOrderID";
                    cbxlInversionDataSectionId.DataBind();

                    // If coming from
                    int companyId = Int32.Parse(hdfCompanyId.Value.Trim());
                    int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());
                    int assetId = Int32.Parse(hdfAssetId.Value.Trim());
                    int workId = Int32.Parse(hdfWorkId.Value.Trim());
                    string workType = hdfWorkType.Value;

                    // ... fl_navigator2.aspx
                    if (Request.QueryString["source_page"] == "fl_navigator2.aspx")
                    {
                        StoreNavigatorState();
                        ViewState["update"] = "no";

                        // ... Set initial tab
                        if ((string)Session["dialogOpenedFll"] != "1")
                        {
                            hdfActiveTab.Value = Request.QueryString["active_tab"];

                            fullLengthLiningTDS = new FullLengthLiningTDS();

                            FullLengthLiningSectionDetails fullLengthLiningSectionDetails = new FullLengthLiningSectionDetails(fullLengthLiningTDS);
                            fullLengthLiningSectionDetails.LoadByWorkId(workId, companyId);

                            FullLengthLiningWorkDetails fullLengthLiningWorkDetails = new FullLengthLiningWorkDetails(fullLengthLiningTDS);
                            fullLengthLiningWorkDetails.LoadByWorkIdAssetId(workId, assetId, companyId);

                            FullLengthLiningLateralDetails fullLengthLiningLateralDetails = new FullLengthLiningLateralDetails(fullLengthLiningTDS);
                            fullLengthLiningLateralDetails.LoadForEdit(workId, assetId, companyId, currentProjectId);

                            FullLengthLiningWetOutCatalystsDetails fullLengthLiningWetOutCatalystsDetails = new FullLengthLiningWetOutCatalystsDetails(fullLengthLiningTDS);
                            fullLengthLiningWetOutCatalystsDetails.LoadAll(workId, companyId);
                        }
                        else
                        {
                            hdfActiveTab.Value = (string)Session["activeTabFll"];

                            // Restore datasets
                            fullLengthLiningTDS = (FullLengthLiningTDS)Session["fullLengthLiningTDS"];
                        }

                        // ... Store dataset
                        Session["fullLengthLiningTDS"] = fullLengthLiningTDS;
                    }

                    // ... fl_summary.aspx or fl_edit.aspx
                    if ((Request.QueryString["source_page"] == "fl_summary.aspx") || (Request.QueryString["source_page"] == "fl_edit.aspx"))
                    {
                        StoreNavigatorState();
                        ViewState["update"] = Request.QueryString["update"];

                        // ... Restore dataset
                        fullLengthLiningTDS = (FullLengthLiningTDS)Session["fullLengthLiningTDS"];

                        // ... Set initial tab
                        if ((string)Session["dialogOpenedFll"] != "1")
                        {
                            hdfActiveTab.Value = Request.QueryString["active_tab"];
                        }
                        else
                        {
                            hdfActiveTab.Value = (string)Session["activeTabFll"];
                        }

                        if (ViewState["update"].ToString().Trim() == "yes")
                        {
                            FullLengthLiningSectionDetails fullLengthLiningSectionDetails = new FullLengthLiningSectionDetails(fullLengthLiningTDS);
                            fullLengthLiningSectionDetails.LoadByWorkId(workId, companyId);

                            FullLengthLiningWorkDetails fullLengthLiningWorkDetails = new FullLengthLiningWorkDetails(fullLengthLiningTDS);
                            fullLengthLiningWorkDetails.LoadByWorkIdAssetId(workId, assetId, companyId);

                            FullLengthLiningLateralDetails fullLengthLiningLateralDetails = new FullLengthLiningLateralDetails(fullLengthLiningTDS);
                            fullLengthLiningLateralDetails.LoadForEdit(workId, assetId, companyId, currentProjectId);

                            FullLengthLiningWetOutCatalystsDetails fullLengthLiningWetOutCatalystsDetails = new FullLengthLiningWetOutCatalystsDetails(fullLengthLiningTDS);
                            fullLengthLiningWetOutCatalystsDetails.LoadAll(workId, companyId);

                            // ... Store dataset
                            Session["fullLengthLiningTDS"] = fullLengthLiningTDS;
                        }
                    }

                    // Prepare initial data
                    lblMissingData.Visible = false;

                    // Set initial tab
                    int activeTab = Int32.Parse(hdfActiveTab.Value);
                    tcFlDetails.ActiveTabIndex = activeTab;

                    // ... for client
                    int currentClientId = Int32.Parse(hdfCurrentClientId.Value.ToString());
                    CompaniesGateway companiesGateway = new CompaniesGateway();
                    companiesGateway.LoadByCompaniesId(currentClientId, companyId);
                    lblTitleClientName.Text = "Client: " + companiesGateway.GetName(currentClientId);

                    // ... for project
                    ProjectGateway projectGateway = new ProjectGateway();
                    projectGateway.LoadByProjectId(currentProjectId);
                    string name = projectGateway.GetName(currentProjectId);
                    if (name.Length > 23) name = name.Substring(0, 20) + "...";
                    lblTitleProjectName.Text = " > Project: " + name + " (" + projectGateway.GetProjectNumber(currentProjectId) + ") > Selected Section";

                    // ... Data for current full length lining work
                    LoadFullLengthLiningData(currentProjectId, assetId, companyId);

                    // Databind
                    Page.DataBind();

                    // Especial load for Run details
                    string runDetails = hdfRunDetails.Value;
                    WorkFullLengthLiningWetOutGateway workFullLengthLiningWetOutGateway = new WorkFullLengthLiningWetOutGateway();
                    workFullLengthLiningWetOutGateway.LoadByWorkId(workId, companyId);

                    // ... Verify if work has cipp information to load run details
                    if (workFullLengthLiningWetOutGateway.Table.Rows.Count > 0)
                    {
                        string[] runDetailsList = runDetails.Split('>');
                        for (int i = 0; i < runDetailsList.Length; i++)
                        {
                            cbxlSectionId.Items.FindByValue(runDetailsList[i]).Selected = true;
                            cbxlInversionDataSectionId.Items.FindByValue(runDetailsList[i]).Selected = true;
                        }
                    }
                    else
                    {
                        if (cbxlSectionId.Items.Count > 1)
                        {
                            cbxlSectionId.Items.FindByValue(runDetails).Selected = true;
                        }
                    }

                    // SelectIndex for grids
                    ((DropDownList)grdLaterals.FooterRow.FindControl("ddlNewMaterial")).SelectedIndex = 0;
                    ((DropDownList)grdCatalysts.FooterRow.FindControl("ddlNameFooter")).SelectedIndex = 0;

                    // For usmh, dsmh autocomplete
                    string provinceId_ = "0"; if (hdfProvinceId.Value != "") provinceId_ = hdfProvinceId.Value;
                    string countyId_ = "0"; if (hdfCountyId.Value != "") countyId_ = hdfCountyId.Value;
                    string cityId_ = "0"; if (hdfCityId.Value != "") cityId_ = hdfCityId.Value;

                    aceUsmh.ContextKey = hdfCountryId.Value + "," + provinceId_ + "," + countyId_ + "," + cityId_ + "," + hdfCompanyId.Value;
                    aceDsmh.ContextKey = hdfCountryId.Value + "," + provinceId_ + "," + countyId_ + "," + cityId_ + "," + hdfCompanyId.Value;

                    // Make Wetout tab visible
                    if (ckbxWetOutDataIncludeWetOutInformation.Checked)
                    {
                        pnlVisibleInformation.Visible = true;
                        upnlVisibleInformation.Update();
                    }
                    else
                    {
                        pnlVisibleInformation.Visible = false;
                        upnlVisibleInformation.Update();
                    }

                    // Make inversion tab visible
                    lblInversionDataInversionMissingData.Visible = false;
                    uplInversionDataInversionMissingData.Update();
                    if (ckbxInversionDataIncludeInversionInformation.Checked)
                    {
                        // ... ... visible only if wet out information is provided.
                        if (!ckbxWetOutDataIncludeWetOutInformation.Checked)
                        {
                            pnlInversionVisibleInformation.Visible = false;
                            upnlInversionVisibleInformation.Update();
                        }
                        else
                        {

                            pnlInversionVisibleInformation.Visible = true;
                            upnlInversionVisibleInformation.Update();
                        }
                    }
                    else
                    {
                        pnlInversionVisibleInformation.Visible = false;
                        upnlInversionVisibleInformation.Update();
                    }

                    // Load Materials
                    MaterialInformationGateway materialInformationGateway = new MaterialInformationGateway(materialInformationTDS);
                    materialInformationGateway.LoadAllByAssetId(assetId, companyId);

                    materialInformation = materialInformationTDS.MaterialInformation;
                    Session["materialInformationTDS"] = materialInformationTDS;
                }
            }
            else
            {
                // Restore datasets
                fullLengthLiningTDS = (FullLengthLiningTDS)Session["fullLengthLiningTDS"];
                flatSectionJlTDSForFLL = (FlatSectionJlTDS)Session["flatSectionJlTDSForFLL"];
                materialInformationTDS = (MaterialInformationTDS)Session["materialInformationTDS"];
                materialInformation = materialInformationTDS.MaterialInformation;

                // Set initial tab
                int activeTab = Int32.Parse(hdfActiveTab.Value);
                tcFlDetails.ActiveTabIndex = activeTab;
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            if (!IsPostBack)
            {
                // Security check
                if (!(Convert.ToBoolean(Session["sgLFS_CWP_JUNCTIONLINING_VIEW"]) && Convert.ToBoolean(Session["sgLFS_CWP_JUNCTIONLINING_DELETE"])))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                }

                // Validate query string
                if (((string)Request.QueryString["source_page"] == null) || ((string)Request.QueryString["client_id"] == null) || ((string)Request.QueryString["project_id"] == null))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in jls_delete.aspx");
                }

                // Tag Page
                hdfCompanyId.Value = Session["companyID"].ToString();
                hdfCurrentProjectId.Value = Request.QueryString["project_id"].ToString();
                hdfCurrentClientId.Value = Request.QueryString["client_id"].ToString();

                // Prepare initial data
                // ... for client
                int currentClientId = Int32.Parse(hdfCurrentClientId.Value.ToString());
                int companyId = Int32.Parse(hdfCompanyId.Value);

                CompaniesGateway companiesGateway = new CompaniesGateway();
                companiesGateway.LoadByCompaniesId(currentClientId, companyId);
                lblTitleClientName.Text = "Client: " + companiesGateway.GetName(currentClientId);

                // ... for project
                int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());
                ProjectGateway projectGateway = new ProjectGateway();
                projectGateway.LoadByProjectId(currentProjectId);
                string name = projectGateway.GetName(currentProjectId);
                if (name.Length > 23) name = name.Substring(0, 20) + "...";
                lblTitleProjectName.Text = " > Project: " + name + " (" + projectGateway.GetProjectNumber(currentProjectId) + ") > Selected Sections";

                // If coming from
                // ... jls_navigator2.aspx
                if (Request.QueryString["source_page"] == "jls_navigator2.aspx")
                {
                    StoreNavigatorState();
                    ViewState["update"] = "no";
                }

                // ... flat_section_jls_summary.aspx
                if (Request.QueryString["source_page"] == "flat_section_jls_summary.aspx")
                {
                    StoreNavigatorState();
                    ViewState["update"] = Request.QueryString["update"];
                }

                // Restore datasets
                flatSectionJlsTDS = (FlatSectionJlsTDS)Session["flatSectionJlsTDS"];
            }
            else
            {
                // Restore datasets
                flatSectionJlsTDS = (FlatSectionJlsTDS)Session["flatSectionJlsTDS"];
            }
        }
        private void PostPageChanges()
        {
            ProjectGateway projectGateway = new ProjectGateway(projectTDS);
            int projectId = int.Parse(hdfProjectId.Value);

            // General Data
            Int64 countryId = projectGateway.GetCountryID(projectId);
            int officeId = projectGateway.GetOfficeID(projectId);
            Int64? provinceId = projectGateway.GetProvinceID(projectId);
            Int64? cityId = projectGateway.GetCityID(projectId);
            Int64? countyId = projectGateway.GetCountyID(projectId);
            int? projectLeadId = null; if ((ddlProjectLeadId.SelectedValue != "-1") && (ddlProjectLeadId.SelectedIndex > -1)) projectLeadId = int.Parse(ddlProjectLeadId.SelectedValue);
            int salesmanId = int.Parse(ddlSalesmanId.SelectedValue);
            string projectType = projectGateway.GetProjectType(projectId);
            string projectState = projectGateway.GetProjectState(projectId);
            string name = tbxName.Text.Trim();
            string description = tbxDescription.Text.Trim();
            DateTime? proposalDate = null; if (tkrdpProposalDate.SelectedDate.HasValue) proposalDate = tkrdpProposalDate.SelectedDate.Value;
            DateTime? startDate = null; if (tkrdpStartDate.SelectedDate.HasValue) startDate = tkrdpStartDate.SelectedDate.Value;
            DateTime? endDate = null; if (tkrdpEndDate.SelectedDate.HasValue) endDate = tkrdpEndDate.SelectedDate.Value;
            int clientId = projectGateway.GetClientID(projectId);
            string clientProjectNumber = tbxClientProjectNumber.Text.Trim();
            int? clientPrimaryContactId = null; if ((ddlClientPrimaryContactId.SelectedValue != "-1") && (ddlClientPrimaryContactId.SelectedIndex > -1)) clientPrimaryContactId = int.Parse(ddlClientPrimaryContactId.SelectedValue);
            int? clientSecondaryContactId = null; if ((ddlClientSecondaryContactId.SelectedValue != "-1") && (ddlClientSecondaryContactId.SelectedIndex > -1)) clientSecondaryContactId = int.Parse(ddlClientSecondaryContactId.SelectedValue);
            bool deleted = projectGateway.GetDeleted(projectId);
            int? libraryCategoriesId = null; if (projectGateway.GetLibraryCategoriesId(projectId).HasValue) libraryCategoriesId = (int)projectGateway.GetLibraryCategoriesId(projectId);
            bool fairWageApplies = cbxFairWageApplies.Checked;

            // ... Update Project Number
            Project project = new Project(projectTDS);
            string projectNumber;

            if (projectGateway.GetOriginalProjectID(projectId) == null)
            {
                projectNumber = project.UpdateProjectNumber(projectId, salesmanId);
            }
            else
            {
                projectNumber = projectGateway.GetProjectNumber(projectId);
            }

            // ... Update Project
            project.Update(projectId, countryId, officeId, projectLeadId, salesmanId, projectNumber, projectType, projectState, name, description, proposalDate, startDate, endDate, clientId, clientProjectNumber, clientPrimaryContactId, clientSecondaryContactId, deleted, libraryCategoriesId, provinceId, cityId, Int32.Parse(hdfCompanyId.Value.Trim()), countyId, fairWageApplies);

            // ... If project type is Ballpark update Bill Price and Bill Money
            if (projectType == "Ballpark")
            {
                ProjectSaleBillingPricing projectSaleBillingPricingForGeneralData = new ProjectSaleBillingPricing(projectTDS);

                decimal? billPrice = null; if (tbxBillPrice.Text != "") billPrice = Convert.ToDecimal(tbxBillPrice.Text);
                string billMoney = ddlBillMoney.SelectedValue;

                projectSaleBillingPricingForGeneralData.UpdateBillPrice(projectId, billPrice, billMoney);
            }

            if ((projectType != "Ballpark") && (projectType != "Internal"))
            {
                // Sale/Billing/Pricing
                //bool saleBidProject = cbxSaleBidProject.Checked;
                //bool saleRFP = cbxSaleRFP.Checked;
                //bool saleSoleSource = cbxSaleSoleSource.Checked;
                //bool saleTermContract = cbxSaleTermContract.Checked;
                //string saleTermContractDetail = tbxSaleTermContractDetail.Text.Trim();
                //bool saleOther = cbxSaleOther.Checked;
                //string saleOtherDetail = tbxSaleOtherDetail.Text.Trim();
                //int? saleGettingJob = null; if (tbxSaleGettingJob.Text.Trim() != "") saleGettingJob = int.Parse(tbxSaleGettingJob.Text.Trim());
                decimal? billPriceSaleBillingPricing = null; if (tbxBillPriceSaleBillingPricing.Text.Trim() != "") billPriceSaleBillingPricing = decimal.Parse(tbxBillPriceSaleBillingPricing.Text.Trim());
                string billMoneySaleBillingPricing = ddlBillMoneySaleBillingPricing.SelectedValue;
                decimal? billSubcontractorAmount = null; if (tbxBillSubcontractorAmount.Text.Trim() != "") billSubcontractorAmount = decimal.Parse(tbxBillSubcontractorAmount.Text.Trim());
                //string billBidHardDollar = tbxBillBidHardDollar.Text.Trim();
                //bool billPerUnit = cbxBillPerUnit.Checked;
                //bool billHourly = cbxBillHourly.Checked;
                //string billExpectExtras = tbxBillExpectExtras.Text.Trim();
                //bool chargesWater = cbxChargesWater.Checked;
                //decimal? chargesWaterAmount = null; if (tbxChargesWaterAmount.Text.Trim() != "") chargesWaterAmount = decimal.Parse(tbxChargesWaterAmount.Text.Trim());
                //bool chargesDisposal = cbxChargesDisposal.Checked;
                //decimal? chargesDisposalAmount = null; if (tbxChargesDisposalAmount.Text.Trim() != "") chargesDisposalAmount = decimal.Parse(tbxChargesDisposalAmount.Text.Trim());

                // ... Update Sale/Billing/Pricing
                ProjectSaleBillingPricing projectSaleBillingPricing = new ProjectSaleBillingPricing(projectTDS);
                //projectSaleBillingPricing.Update(projectId, saleBidProject, saleRFP, saleSoleSource, saleTermContract, saleTermContractDetail, saleOther, saleOtherDetail, saleGettingJob, billPriceSaleBillingPricing, billMoneySaleBillingPricing, billBidHardDollar, billPerUnit, billHourly, billExpectExtras, billSubcontractorAmount, chargesWater, chargesWaterAmount, chargesDisposal, chargesDisposalAmount, Int32.Parse(hdfCompanyId.Value.Trim()));
                projectSaleBillingPricing.Update(projectId, billPriceSaleBillingPricing, billMoneySaleBillingPricing, billSubcontractorAmount, Int32.Parse(hdfCompanyId.Value.Trim()));

                // ... Update job info
                bool typeOfWorkMhRehab = ckbxMhRehab.Checked;
                bool typeOfWorkJunctionLining = ckbxJunctionLining.Checked;
                bool typeOfWorkProjectManagement = ckbxProjectManagement.Checked;
                bool typeOfWorkFullLenghtLining = ckbxFullLengthLining.Checked;
                bool typeOfWorkPointRepairs = ckbxPointRepairs.Checked;
                bool typeOfWorkRehabAssessment = ckbxRehabAssessment.Checked;
                bool typeOfWorkGrout = ckbxGrout.Checked;
                bool typeOfWorkOther = ckbxOther.Checked;
                bool agreement = cbxSubcontractorAgreement.Checked;
                bool writtenQuote = cbxSubcontractorWrittenQuote.Checked;
                string role = tbxSubcontractorRole.Text;

                ProjectNavigatorProjectJobInfo projectNavigatorProjectJobInfo = new ProjectNavigatorProjectJobInfo(projectNavigatorTDS);
                projectNavigatorProjectJobInfo.Update(projectId, typeOfWorkMhRehab, typeOfWorkJunctionLining, typeOfWorkProjectManagement, typeOfWorkFullLenghtLining, typeOfWorkPointRepairs, typeOfWorkRehabAssessment, typeOfWorkGrout, typeOfWorkOther, agreement, writtenQuote, role);

                // Costing Updates
                //decimal? extrasToDate = null; if (tbxExtrasToDate.Text.Trim() != "") extrasToDate = decimal.Parse(tbxExtrasToDate.Text.Trim());
                //decimal? costsIncurred = null; if (tbxCostsIncurred.Text.Trim() != "") costsIncurred = decimal.Parse(tbxCostsIncurred.Text.Trim());
                //decimal? costToComplete = null; if (tbxCostToComplete.Text.Trim() != "") costToComplete = decimal.Parse(tbxCostToComplete.Text.Trim());
                //decimal? originalProfitEstimated = null; if (tbxOriginalProfitEstimated.Text.Trim() != "") originalProfitEstimated = decimal.Parse(tbxOriginalProfitEstimated.Text.Trim());
                //decimal? invoicedToDate = null; if (tbxInvoicedToDate.Text.Trim() != "") invoicedToDate = decimal.Parse(tbxInvoicedToDate.Text.Trim());

                // ... Update Costing Updates
                //ProjectCostingUpdates projectCostingUpdates = new ProjectCostingUpdates(projectTDS);
                //projectCostingUpdates.Update(projectId, extrasToDate, costsIncurred, costToComplete, originalProfitEstimated, invoicedToDate, Int32.Parse(hdfCompanyId.Value.Trim()));

                // Terms/PO
                // ... Liquidated Damage
                //bool liquidateDamage = cbxLiquidatedDamages.Checked;
                //decimal? liquidatedRate = null;
                //if (tbxLiquidatedDamagesRate.Text.Trim() != "") { decimal damages = Decimal.Parse(tbxLiquidatedDamagesRate.Text.Trim()); liquidatedRate = Decimal.Round(damages, 2); }
                //string liquidatedUnit = null; if (tbxLiquidatedDamagesUnit.Text != "") liquidatedUnit = tbxLiquidatedDamagesUnit.Text.Trim();

                //// ... Client LFS Relationship
                //bool clientWorkedBefore = cbxWorkedBefore.Checked;
                //string clientQuirks = null; if (tbxClientQuirks.Text.Trim() != "") clientQuirks = tbxClientQuirks.Text.Trim();
                //bool clientPromises = cbxClientPromises.Checked;
                //string clientPromisesNotes = null; if (tbxClientPromises.Text.Trim() != "") clientPromisesNotes = tbxClientPromises.Text.Trim();
                //string waterObtain = null; if (tbxWaterObtain.Text.Trim() != "") waterObtain = tbxWaterObtain.Text.Trim();
                //string materialDispose = null; if (tbxMaterialDispose.Text.Trim() != "") materialDispose = tbxMaterialDispose.Text.Trim();
                //bool requireRPZ = cbxRequireRPZ.Checked;
                //string standardHydrantFitting = null; if (tbxStandardHydrantFitting.Text.Trim() != "") standardHydrantFitting = tbxStandardHydrantFitting.Text.Trim();
                //bool preconstructionMeeting = cbxPreConstructionMeetingNeed.Checked;
                //bool specificMeetingLocation = cbxSpecificMeetingLocation.Checked;
                //string specificMeetingLocationNotes = null; if (tbxSpecificMeetingLocation.Text.Trim() != "") specificMeetingLocationNotes = tbxSpecificMeetingLocation.Text.Trim();
                //string vehicleAccess = null; if (ddlVehicleAccess.Text.Trim() != "") vehicleAccess = ddlVehicleAccess.Text.Trim();
                //string vehicleAccessNotes = null; if (tbxVehicleAccess.Text.Trim() != "") vehicleAccessNotes = tbxVehicleAccess.Text.Trim();
                string projectOutcome = null; if (tbxDesireOutcomeOfProject.Text.Trim() != "") projectOutcome = tbxDesireOutcomeOfProject.Text.Trim();
                string specificReportingNeeds = null; if (tbxSpecificReportingNeeds.Text.Trim() != "") specificReportingNeeds = tbxSpecificReportingNeeds.Text.Trim();
                bool vehicleAccessRoad = ckbxVehicleAccessRoad.Checked;
                bool vehicleAccessEasement = ckbxVehicleAccessEasement.Checked;
                bool vehicleAccessOther = ckbxVehicleAccessOther.Checked;

                //... Purchase Order
                //bool orderAttached = cbxPurchaseOrderAttach.Checked;
                string orderNumber = null; if (tbxPurchaseOrderNumber.Text.Trim() != "") orderNumber = tbxPurchaseOrderNumber.Text.Trim();
                //string orderNotes = null; if (tbxPurchaseOrderWillNotProvided.Text.Trim() != "") orderNotes = tbxPurchaseOrderWillNotProvided.Text.Trim();

                // ... Update Term/PO
                ProjectTermsPO projectTermsPO = new ProjectTermsPO(projectTDS);
                //projectTermsPO.Update(projectId, liquidateDamage, liquidatedRate, liquidatedUnit, clientWorkedBefore, clientQuirks, clientPromises, clientPromisesNotes, waterObtain, materialDispose, requireRPZ, standardHydrantFitting, preconstructionMeeting, specificMeetingLocation, specificMeetingLocationNotes, vehicleAccess, vehicleAccessNotes, projectOutcome, specificReportingNeeds, orderNumber, orderAttached, orderNotes, Int32.Parse(hdfCompanyId.Value.Trim()));
                projectTermsPO.Update(projectId, projectOutcome, specificReportingNeeds, orderNumber,  Int32.Parse(hdfCompanyId.Value.Trim()), vehicleAccessRoad, vehicleAccessEasement, vehicleAccessOther);

                // Technical
                bool availableDrawings = cbxAvailableDrawings.Checked;
                bool availableVideo = cbxAvailableVideo.Checked;
                //bool groundConditions = cbxGroundConditions.Checked;
                //string groundConditionNotes = null; if (tbxGroundCondition.Text != "") groundConditionNotes = tbxGroundCondition.Text.Trim();
                //bool reviewVideoInspections = cbxReviewVideoInspections.Checked;
                //bool strangeConfigurations = cbxStrangeConfigurations.Checked;
                //string strangeConfigurationsNotes = null; if (tbxStrangeConfigurations.Text != "") strangeConfigurationsNotes = tbxStrangeConfigurations.Text.Trim();
                //string furtherObservations = null; if (tbxFurtherObservations.Text != "") furtherObservations = tbxFurtherObservations.Text.Trim();
                //string restrictiveFactors = null; if (tbxRestrictiveFactors.Text != "") restrictiveFactors = tbxRestrictiveFactors.Text.Trim();

                // ... Update Technical
                ProjectTechnical projectTechnical = new ProjectTechnical(projectTDS);
                //projectTechnical.Update(projectId, availableDrawings, availableVideo, groundConditions, groundConditionNotes, reviewVideoInspections, strangeConfigurations, strangeConfigurationsNotes, furtherObservations, restrictiveFactors, Int32.Parse(hdfCompanyId.Value.Trim()));
                projectTechnical.Update(projectId, availableDrawings, availableVideo,  Int32.Parse(hdfCompanyId.Value.Trim()));

                // Engineer/Subcontractors
                bool generalContractor = cbxGeneralContractor.Checked;
                bool generalWSIB = cbxGeneralWSIB.Checked;
                bool generalInsuranceCertificate = cbxGeneralInsuranceCertificate.Checked;
                string generalBondingSupplied = ddlGeneralBondingSupplied.SelectedValue;
                //string generalMOLForm = ddlGeneralMOLForm.SelectedValue;
                //bool generalNoticeProject = rbtnGeneralNoticeProject.Checked;
                //bool generalForm1000 = rbtnGeneralForm1000.Checked;
                //int? engineeringFirmId = null; if (ddlEngineeringFirmId.SelectedValue != "") engineeringFirmId = int.Parse(ddlEngineeringFirmId.SelectedValue);
                //int? engineerId = null; if (ddlEngineerId.SelectedValue != "") engineerId = int.Parse(ddlEngineerId.SelectedValue);
                //string engineerNumber = tbxEngineerNumber.Text.Trim();
                bool subcontractorUsed = cbxSubcontractorUsed.Checked;
                string bondNumber = tbxBondNumber.Text.Trim();

                // ... Update Engineer/Subcontractors
                ProjectEngineerSubcontractors projectEngineerSubcontractors = new ProjectEngineerSubcontractors(projectTDS);
                //projectEngineerSubcontractors.Update(projectId, generalContractor, generalWSIB, generalInsuranceCertificate, generalBondingSupplied, generalMOLForm, generalNoticeProject, generalForm1000, engineeringFirmId, engineerId, engineerNumber, subcontractorUsed, Int32.Parse(hdfCompanyId.Value.Trim()), bondNumber);
                projectEngineerSubcontractors.Update(projectId, generalContractor, generalWSIB, generalInsuranceCertificate, generalBondingSupplied, subcontractorUsed, Int32.Parse(hdfCompanyId.Value.Trim()), bondNumber);

                // ... Update subcontractors
                //ProjectSubcontractor projectSubcontractor = new ProjectSubcontractor(projectTDS);

                //bool subcontractorWrittenQuote = ((CheckBox)row.FindControl("cbxSubcontractorWrittenQuote")).Checked;
                //bool subcontractorAgreement = ((CheckBox)row.FindControl("cbxSubcontractorAgreement")).Checked;

                ////foreach (GridViewRow row in grdvSubcontractors.Rows)
                //{
                //    int subcontractorRefId = int.Parse(((HiddenField)row.FindControl("hdfRefId")).Value);
                //    int subcontractorId = int.Parse(((DropDownList)row.FindControl("ddlSubcontractorId")).SelectedValue);

                //    bool subcontractorSurveyedSite = ((CheckBox)row.FindControl("cbxSubcontractorSurveyedSite")).Checked;
                //    bool subcontractorWorkedBefore = ((CheckBox)row.FindControl("cbxSubcontractorWorkedBefore")).Checked;
                //    string subcontractorRole = ((TextBox)row.FindControl("tbxSubcontractorRole")).Text.Trim();

                //    string subcontractorIssues = ((TextBox)row.FindControl("tbxSubcontractorIssues")).Text.Trim();
                //    bool subcontractorPurchaseOrder = ((CheckBox)row.FindControl("cbxSubcontractorPurchaseOrder")).Checked;
                //    bool subcontractorInsuranceCertificate = ((CheckBox)row.FindControl("cbxSubcontractorInsuranceCertificate")).Checked;
                //    bool subcontractorWSIB = ((CheckBox)row.FindControl("cbxSubcontractorWSIB")).Checked;
                //    string subcontractorMOLForm1000 = ((DropDownList)row.FindControl("ddlSubcontractorMolForm1000")).SelectedValue;
                //    int? royalties = null;
                //    if (((TextBox)row.FindControl("tbxRoyalties")).Text != "")
                //    {
                //        royalties = Int32.Parse(((TextBox)row.FindControl("tbxRoyalties")).Text);
                //    }

                    //projectSubcontractor.Update(projectId, subcontractorRefId, subcontractorId, subcontractorWrittenQuote, subcontractorSurveyedSite, subcontractorWorkedBefore, subcontractorRole, subcontractorAgreement, subcontractorIssues, subcontractorPurchaseOrder, subcontractorInsuranceCertificate, subcontractorWSIB, subcontractorMOLForm1000, false, Int32.Parse(hdfCompanyId.Value.Trim()), royalties);
                    //projectSubcontractor.Update(projectId, 1,  subcontractorWrittenQuote, subcontractorAgreement, Int32.Parse(hdfCompanyId.Value.Trim()));
                //}

                decimal unitsBudget = 0M; if (tbxUnitsBudget.Text.Trim() != "") unitsBudget = decimal.Parse(tbxUnitsBudget.Text);
                decimal materialsBudget = 0M; if (tbxMaterialsBudget.Text.Trim() != "") materialsBudget = decimal.Parse(tbxMaterialsBudget.Text);
                decimal subcontractorsBudget = 0M; if (tbxSubcontractorsBudget.Text.Trim() != "") subcontractorsBudget = decimal.Parse(tbxSubcontractorsBudget.Text);
                decimal hotelsBudget = 0M; if (tbxHotelsBudget.Text.Trim() != "") hotelsBudget = decimal.Parse(tbxHotelsBudget.Text);
                decimal bondingsBudget = 0M; if (tbxBondingsBudget.Text.Trim() != "") bondingsBudget = decimal.Parse(tbxBondingsBudget.Text);
                decimal insurancesBudget = 0M; if (tbxInsurancesBudget.Text.Trim() != "") insurancesBudget = decimal.Parse(tbxInsurancesBudget.Text);

                ProjectNavigatorProjectUnitsBudget projectNavigatorProjectUnitsBudget = new ProjectNavigatorProjectUnitsBudget(projectNavigatorTDS);
                if (projectNavigatorProjectUnitsBudget.Table.Rows.Count > 0)
                {
                    projectNavigatorProjectUnitsBudget.Update(projectId, unitsBudget);
                }
                else
                {
                    projectNavigatorProjectUnitsBudget.Insert(projectId, unitsBudget, false, Int32.Parse(hdfCompanyId.Value), false);
                }

                ProjectNavigatorProjectMaterialsBudget projectNavigatorProjectMaterialsBudget = new ProjectNavigatorProjectMaterialsBudget(projectNavigatorTDS);
                if (projectNavigatorProjectMaterialsBudget.Table.Rows.Count > 0)
                {
                    projectNavigatorProjectMaterialsBudget.Update(projectId, materialsBudget);
                }
                else
                {
                    projectNavigatorProjectMaterialsBudget.Insert(projectId, materialsBudget, false, Int32.Parse(hdfCompanyId.Value), false);
                }

                ProjectNavigatorProjectSubcontractorsBudget projectNavigatorProjectSubcontractorsBudget = new ProjectNavigatorProjectSubcontractorsBudget(projectNavigatorTDS);
                if (projectNavigatorProjectSubcontractorsBudget.Table.Rows.Count > 0)
                {
                    projectNavigatorProjectSubcontractorsBudget.Update(projectId, 1, 1, subcontractorsBudget, false, Int32.Parse(hdfCompanyId.Value));
                }
                else
                {
                    projectNavigatorProjectSubcontractorsBudget.Insert(projectId, 1, subcontractorsBudget, false, Int32.Parse(hdfCompanyId.Value), false, "");
                }

                ProjectNavigatorProjectHotelsBudget projectNavigatorProjectHotelsBudget = new ProjectNavigatorProjectHotelsBudget(projectNavigatorTDS);
                if (projectNavigatorProjectHotelsBudget.Table.Rows.Count > 0)
                {
                    projectNavigatorProjectHotelsBudget.Update(projectId, 1, 1, hotelsBudget, false, Int32.Parse(hdfCompanyId.Value));
                }
                else
                {
                    projectNavigatorProjectHotelsBudget.Insert(projectId, 1, hotelsBudget, false, Int32.Parse(hdfCompanyId.Value), false, "");
                }

                ProjectNavigatorProjectBondingsBudget projectNavigatorProjectBondingsBudget = new ProjectNavigatorProjectBondingsBudget(projectNavigatorTDS);
                if (projectNavigatorProjectBondingsBudget.Table.Rows.Count > 0)
                {
                    projectNavigatorProjectBondingsBudget.Update(projectId, 1, 1, bondingsBudget, false, Int32.Parse(hdfCompanyId.Value));
                }
                else
                {
                    projectNavigatorProjectBondingsBudget.Insert(projectId, 1, bondingsBudget, false, Int32.Parse(hdfCompanyId.Value), false, "");
                }

                ProjectNavigatorProjectInsurancesBudget projectNavigatorProjectInsurancesBudget = new ProjectNavigatorProjectInsurancesBudget(projectNavigatorTDS);
                if (projectNavigatorProjectInsurancesBudget.Table.Rows.Count > 0)
                {
                    projectNavigatorProjectInsurancesBudget.Update(projectId, 1, 1, insurancesBudget, false, Int32.Parse(hdfCompanyId.Value));
                }
                else
                {
                    projectNavigatorProjectInsurancesBudget.Insert(projectId, 1, insurancesBudget, false, Int32.Parse(hdfCompanyId.Value), false, "");
                }
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            bool isFromTabClick = false;

            if (!IsPostBack)
            {
                if (!isFromTabClick)
                {
                    // Security check
                    if (!(Convert.ToBoolean(Session["sgLFS_CWP_MANHOLEREHABILITATION_VIEW"]) && Convert.ToBoolean(Session["sgLFS_CWP_MANHOLEREHABILITATION_EDIT"])))
                    {
                        Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                    }

                    // Validate query string
                    if (((string)Request.QueryString["source_page"] == null) || ((string)Request.QueryString["client_id"] == null) || ((string)Request.QueryString["project_id"] == null) || ((string)Request.QueryString["asset_id"] == null) || ((string)Request.QueryString["active_tab"] == null) || ((string)Request.QueryString["in_project"] == null))
                    {
                        Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in mr_edit.aspx");
                    }

                    // Tag Page
                    TagPage();

                    // If coming from
                    int companyId = Int32.Parse(hdfCompanyId.Value.Trim());
                    int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());
                    int assetId = Int32.Parse(hdfAssetId.Value.Trim());
                    int workId = Int32.Parse(hdfWorkId.Value.Trim());
                    string workType = hdfWorkType.Value;
                    lblNotLastBatch.Visible = false;

                    // ... mr_navigator2.aspx
                    if (Request.QueryString["source_page"] == "mr_navigator2.aspx")
                    {
                        StoreNavigatorState();
                        ViewState["update"] = "no";

                        // ... Set initial tab
                        if ((string)Session["dialogOpenedMr"] != "1")
                        {
                            hdfActiveTab.Value = Request.QueryString["active_tab"];

                            manholeRehabilitationTDS = new ManholeRehabilitationTDS();

                            ManholeRehabilitationManholeDetails manholeRehabilitationManholeDetails = new ManholeRehabilitationManholeDetails(manholeRehabilitationTDS);
                            manholeRehabilitationManholeDetails.LoadByAssetId(assetId, companyId);

                            ManholeRehabilitationWorkDetails fullLengthLiningWorkDetails = new ManholeRehabilitationWorkDetails(manholeRehabilitationTDS);
                            fullLengthLiningWorkDetails.LoadByWorkIdAssetId(workId, assetId, companyId);
                        }
                        else
                        {
                            hdfActiveTab.Value = (string)Session["activeTabMr"];

                            // Restore datasets
                            manholeRehabilitationTDS = (ManholeRehabilitationTDS)Session["manholeRehabilitationTDS"];
                        }

                        // ... Store dataset
                        Session["manholeRehabilitationTDS"] = manholeRehabilitationTDS;
                    }

                    // ... mr_summary.aspx or mr_edit.aspx
                    if ((Request.QueryString["source_page"] == "mr_summary.aspx") || (Request.QueryString["source_page"] == "mr_edit.aspx"))
                    {
                        StoreNavigatorState();
                        ViewState["update"] = Request.QueryString["update"];

                        // ... Restore dataset
                        manholeRehabilitationTDS = (ManholeRehabilitationTDS)Session["manholeRehabilitationTDS"];

                        // ... Set initial tab
                        if ((string)Session["dialogOpenedMr"] != "1")
                        {
                            hdfActiveTab.Value = Request.QueryString["active_tab"];
                        }
                        else
                        {
                            hdfActiveTab.Value = (string)Session["activeTabMr"];
                        }

                        if (ViewState["update"].ToString().Trim() == "yes")
                        {
                            ManholeRehabilitationManholeDetails manholeRehabilitationManholeDetails = new ManholeRehabilitationManholeDetails(manholeRehabilitationTDS);
                            manholeRehabilitationManholeDetails.LoadByAssetId(assetId, companyId);

                            ManholeRehabilitationWorkDetails fullLengthLiningWorkDetails = new ManholeRehabilitationWorkDetails(manholeRehabilitationTDS);
                            fullLengthLiningWorkDetails.LoadByWorkIdAssetId(workId, assetId, companyId);

                            // ... Store dataset
                            Session["manholeRehabilitationTDS"] = manholeRehabilitationTDS;
                        }
                    }

                    // Set initial data
                    int activeTab = Int32.Parse(hdfActiveTab.Value);
                    tcMrDetails.ActiveTabIndex = activeTab;
                    lblBatchDateRequired.Visible = false;

                    if ((hdfCurrentClientId.Value != "0") && (hdfCurrentProjectId.Value != "0"))
                    {
                        // ... for client
                        int currentClientId = Int32.Parse(hdfCurrentClientId.Value.ToString());
                        CompaniesGateway companiesGateway = new CompaniesGateway();
                        companiesGateway.LoadByCompaniesId(currentClientId, companyId);
                        lblTitleClientName.Text = "Client: " + companiesGateway.GetName(currentClientId);

                        // ... for project
                        ProjectGateway projectGateway = new ProjectGateway();
                        projectGateway.LoadByProjectId(currentProjectId);
                        string name = projectGateway.GetName(currentProjectId);
                        if (name.Length > 23) name = name.Substring(0, 20) + "...";
                        lblTitleProjectName.Text = " > Project: " + name + " (" + projectGateway.GetProjectNumber(currentProjectId) + ") > Selected Manhole";
                    }
                    else
                    {
                        lblTitleClientName.Text = "";
                        lblTitleProjectName.Text = "";
                    }

                    // ... For batch dates
                    WorkManholeRehabilitationBatchList workManholeRehabilitationBatchList = new WorkManholeRehabilitationBatchList();
                    workManholeRehabilitationBatchList.LoadAndAddItem(-1, "(Select a batch)", companyId);
                    ddlRehabilitationBatchDate.DataSource = workManholeRehabilitationBatchList.Table;
                    ddlRehabilitationBatchDate.DataValueField = "BatchID";
                    ddlRehabilitationBatchDate.DataTextField = "Description";
                    ddlRehabilitationBatchDate.DataBind();

                    // ... ... Data for current manhole rehabilitation work
                    LoadManholeRehabilitationData(currentProjectId, assetId, companyId);

                    // ... ... Make panels visible
                    ShapeStructure();

                    // Databind
                    Page.DataBind();

                    // For usmh, dsmh autocomplete
                    string provinceId_ = "0"; if (hdfProvinceId.Value != "") provinceId_ = hdfProvinceId.Value;
                    string countyId_ = "0"; if (hdfCountyId.Value != "") countyId_ = hdfCountyId.Value;
                    string cityId_ = "0"; if (hdfCityId.Value != "") cityId_ = hdfCityId.Value;
                }
            }
            else
            {
                // Restore datasets
                manholeRehabilitationTDS = (ManholeRehabilitationTDS)Session["manholeRehabilitationTDS"];

                // Set initial tab
                int activeTab = Int32.Parse(hdfActiveTab.Value);
                tcMrDetails.ActiveTabIndex = activeTab;
            }
        }
        protected void tkrmTop_ItemClick(object sender, RadMenuEventArgs e)
        {
            if (e.Item.Value == "mPreview")
            {
                if (prLiningPlanTDS.PlLiningPlan.Rows.Count > 0)
                {
                    Page.Validate();
                    if (Page.IsValid)
                    {
                        PostPageChanges();

                        string name = "";
                        string client = "";
                        string project = "";

                        // ... for client
                        int companyId = Int32.Parse(hdfCompanyId.Value);
                        int currentClientId = Int32.Parse(hdfCurrentClientId.Value.ToString());
                        CompaniesGateway companiesGateway = new CompaniesGateway();
                        companiesGateway.LoadByCompaniesId(currentClientId, companyId);
                        client += "Client: " + companiesGateway.GetName(currentClientId);

                        // ... for project
                        int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());
                        ProjectGateway projectGateway = new ProjectGateway();
                        projectGateway.LoadByProjectId(currentProjectId);
                        project = projectGateway.GetName(currentProjectId);
                        name = client + " > Project: " + project + " (" + projectGateway.GetProjectNumber(currentProjectId) + ")";

                        Response.Write("<script language='javascript'> {window.open('./pr_lining_plan_report.aspx?name=" + name + "', '_blank', 'toolbar=no, location=no, directories=no, status=yes, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=800, height=680');}</script>");
                    }
                }
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            if (!IsPostBack)
            {
                // Security check
                if (!(Convert.ToBoolean(Session["sgLFS_CWP_JUNCTIONLINING_VIEW"])))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                }

                // Validate query string
                if (((string)Request.QueryString["source_page"] == null) || ((string)Request.QueryString["client_id"] == null) || ((string)Request.QueryString["project_id"] == null) || ((string)Request.QueryString["work_type"] == null))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in jl_navigator.aspx");
                }

                // Tag Page
                hdfCompanyId.Value = Session["companyID"].ToString();
                hdfCurrentProjectId.Value = Request.QueryString["project_id"].ToString();
                hdfCurrentClientId.Value = Request.QueryString["client_id"].ToString();
                hdfWorkType.Value = Request.QueryString["work_type"].ToString();

                // Prepare initial data
                // ... For sortByList
                odsSortByList.DataBind();
                ddlSortBy.DataSourceID = "odsSortByList";
                ddlSortBy.DataValueField = "SortID";
                ddlSortBy.DataTextField = "Name";
                ddlSortBy.DataBind();

                // ... For
                odsViewForDisplayList.DataBind();
                odsViewForDisplayList2.DataBind();

                // ... For view ddl
                int companyId = Int32.Parse(hdfCompanyId.Value.Trim());
                string workType = hdfWorkType.Value;
                int loginId = Convert.ToInt32(Session["loginID"]);
                string viewTypeGlobal = "";
                string viewTypePersonal = "Personal";

                // Global Views check
                if (Convert.ToBoolean(Session["sgLFS_GLOBALVIEWS_VIEW"]))
                {
                    viewTypeGlobal = "Global";
                }

                WorkViewList workViewList = new WorkViewList();
                workViewList.LoadAndAddItem(workType, viewTypeGlobal, viewTypePersonal, loginId, companyId);
                ddlView.DataSource = workViewList.Table;
                ddlView.DataValueField = "ViewID";
                ddlView.DataTextField = "Name";
                ddlView.DataBind();
                ddlView.SelectedIndex = 1;

                WorkTypeViewSubAreaList workTypeViewSubAreaList = new WorkTypeViewSubAreaList();
                workTypeViewSubAreaList.LoadAndAddItem("Junction Lining", Int32.Parse(hdfCompanyId.Value), int.Parse(hdfCurrentProjectId.Value), "(All)");
                ddlSubArea.DataSource = workTypeViewSubAreaList.Table;
                ddlSubArea.DataValueField = "SubArea";
                ddlSubArea.DataTextField = "SubArea";
                ddlSubArea.DataBind();

                // ... for client
                int currentClientId = Int32.Parse(hdfCurrentClientId.Value.ToString());

                CompaniesGateway companiesGateway = new CompaniesGateway();
                companiesGateway.LoadByCompaniesId(currentClientId, companyId);
                lblTitleClientName.Text = "Client: " + companiesGateway.GetName(currentClientId);

                // ... for project
                int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());
                ProjectGateway projectGateway = new ProjectGateway();
                projectGateway.LoadByProjectId(currentProjectId);
                string name = projectGateway.GetName(currentProjectId);
                if (name.Length > 23) name = name.Substring(0, 20) + "...";
                lblTitleProjectName.Text = " > Project: " + name + " (" + projectGateway.GetProjectNumber(currentProjectId) + ")";

                // If coming from

                // ... Left Menu, select_project.aspx or Projects2.aspx
                if ((Request.QueryString["source_page"] == "lm") || (Request.QueryString["source_page"] == "select_project.aspx") || (Request.QueryString["source_page"] == "Projects2.aspx"))
                {
                    tdNoResults.Visible = false;
                }

                // ... jl_navigator2.aspx
                if (Request.QueryString["source_page"] == "jl_navigator2.aspx")
                {
                    RestoreNavigatorState();
                    if ((string)Request.QueryString["no_results"] == "yes")
                    {
                        tdNoResults.Visible = true;
                    }
                    else
                    {
                        tdNoResults.Visible = true;
                    }
                }
            }
        }
        private void Generate()
        {
            mReport1 master = (mReport1)this.Master;

            // Get Data
            JlLiningPlanTDS jlLiningPlanTDS = (JlLiningPlanTDS)Session["jlLiningPlanTDS"];
            JlLiningPlan jlLiningPlan = new JlLiningPlan();
            jlLiningPlan.ProcessForReport(jlLiningPlanTDS);

            // ... set properties to master page
            master.Data = jlLiningPlan.Data;
            master.Table = jlLiningPlan.TableName;

            // Get report
            if (jlLiningPlan.Table.Rows.Count > 0)
            {
                master.Report = new JlLiningPlanReport();

                // ... for client
                int companyId = Int32.Parse(Session["companyID"].ToString());
                int currentClientId = Int32.Parse(hdfCurrentClientId.Value);
                CompaniesGateway companiesGateway = new CompaniesGateway();
                companiesGateway.LoadByCompaniesId(currentClientId, companyId);
                master.SetParameter("Client", companiesGateway.GetName(currentClientId));

                // ... for project
                int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value);
                ProjectGateway projectGateway = new ProjectGateway();
                projectGateway.LoadByProjectId(currentProjectId);
                string name = projectGateway.GetName(currentProjectId);
                master.SetParameter("Project", projectGateway.GetProjectNumber(currentProjectId));

                int loginId = Convert.ToInt32(Session["loginID"]);

                LoginGateway loginGateway = new LoginGateway();
                loginGateway.LoadByLoginId(loginId, companyId);
                string user = loginGateway.GetLastName(loginId, companyId) + " " + loginGateway.GetFirstName(loginId, companyId);
                master.SetParameter("User", user.Trim());
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            if (!IsPostBack)
            {
                // Security check
                if (!Convert.ToBoolean(Session["sgLFS_PROJECTS_VIEW"]))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                }

                // Validate query string
                if (Request.QueryString["source_page"] == null)
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in project_sections_navigator2.aspx");
                }

                projectTDS = (ProjectTDS)Session["lfsProjectTDS"];
                assetsTDS = new AssetsTDS();
                lfsAssetsTDS = new LfsAssetsTDS();
                workTDS = new WorkTDS();

                // Tag page
                hdfCompanyId.Value = Session["companyID"].ToString();
                hdfProjectId.Value = Request.QueryString["project_id"];
                hdfDataChanged.Value = Request.QueryString["data_changed"];
                hdfDataChangedMessage.Value = "Changes made to this project will not be saved.";
                ViewState["state"] = Request.QueryString["state"];
                ViewState["active_tab"] = Request.QueryString["active_tab"];
                ViewState["origin"] = Request.QueryString["origin"];
                ViewState["update"] = Request.QueryString["update"];

                Session.Remove("projectSectionsNavigatorNewDummy");
                Session.Remove("projectSectionsNavigator");

                // Prepare initial data
                lblError.Visible = false;

                // ... for project
                int currentProjectId = Int32.Parse(hdfProjectId.Value.ToString());
                ProjectGateway projectGateway = new ProjectGateway();
                projectGateway.LoadByProjectId(currentProjectId);
                string name = projectGateway.GetName(currentProjectId);
                if (name.Length > 23) name = name.Substring(0, 20) + "...";
                lblTitleProjectName.Text = name + " (" + projectGateway.GetProjectNumber(currentProjectId) + ")";

                // ... for client
                int companyId = Int32.Parse(hdfCompanyId.Value.Trim());
                int currentClientId = projectGateway.GetClientID(Int32.Parse(hdfProjectId.Value.ToString()));
                CompaniesGateway companiesGateway = new CompaniesGateway();
                companiesGateway.LoadAllByCompaniesId(currentClientId, companyId);
                lblTitleClientName.Text = "Client: " + companiesGateway.GetName(currentClientId);

                hdfClientId.Value = projectGateway.GetClientID(int.Parse(hdfProjectId.Value)).ToString();

                // Store navigator state at projects navigator
                StoreNavigatorState();

                // ... project_sections_navigator.aspx or project_sections_navigator2.aspx
                if ((Request.QueryString["source_page"] == "project_sections_navigator.aspx") || (Request.QueryString["source_page"] == "project_sections_navigator2.aspx"))
                {
                    // Restore navigator state
                    RestoreNavigatorState();

                    // Restore data
                    projectSectionsNavigatorTDS = (ProjectSectionsNavigatorTDS)Session["lfsProjectSectionsNavigatorTDS"];
                    projectSectionsNavigator = projectSectionsNavigatorTDS.LFS_PROJECT_SECTIONS_NAVIGATOR;

                    // Store data
                    Session["projectSectionsNavigator"] = projectSectionsNavigatorTDS.LFS_PROJECT_SECTIONS_NAVIGATOR;

                    if (Request.QueryString["update_section"] == "no")
                    {
                        // Restore data
                        projectSectionsNavigatorTDS = (ProjectSectionsNavigatorTDS)Session["lfsProjectSectionsNavigatorTDS"];
                        projectSectionsNavigator = projectSectionsNavigatorTDS.LFS_PROJECT_SECTIONS_NAVIGATOR;

                        // Store data
                        Session["projectSectionsNavigator"] = projectSectionsNavigatorTDS.LFS_PROJECT_SECTIONS_NAVIGATOR;
                    }
                    else
                    {
                        // ... Delete store data
                        Session.Contents.Remove("lfsProjectSectionsNavigatorTDS");

                        // ... Search data with updates
                        projectSectionsNavigatorTDS = SubmitSearch();

                        // ... store datasets
                        Session["lfsProjectSectionsNavigatorTDS"] = projectSectionsNavigatorTDS;
                        Session["projectSectionsNavigator"] = projectSectionsNavigatorTDS.LFS_PROJECT_SECTIONS_NAVIGATOR;
                    }

                    //... for the total rows
                    if (projectSectionsNavigatorTDS.LFS_PROJECT_SECTIONS_NAVIGATOR.Rows.Count > 0)
                    {
                        lblTotalRows.Text = "Total Rows: " + projectSectionsNavigatorTDS.LFS_PROJECT_SECTIONS_NAVIGATOR.Rows.Count;
                        lblTotalRows.Visible = true;
                    }
                    else
                    {
                        lblTotalRows.Visible = false;
                    }
                }
            }
            else
            {
                // Restore dataset
                projectTDS = (ProjectTDS)Session["lfsProjectTDS"];
                projectSectionsNavigatorTDS = (ProjectSectionsNavigatorTDS)Session["lfsProjectSectionsNavigatorTDS"];
                assetsTDS = (AssetsTDS)Session["assetsTDS"];
                lfsAssetsTDS = (LfsAssetsTDS)Session["lfsAssetsTDS"];
                workTDS = (WorkTDS)Session["workTDS"];

                // ... for project
                int currentProjectId = Int32.Parse(hdfProjectId.Value.ToString());
                ProjectGateway projectGateway = new ProjectGateway();
                projectGateway.LoadByProjectId(currentProjectId);
                string name = projectGateway.GetName(currentProjectId);
                if (name.Length > 23) name = name.Substring(0, 20) + "...";
                lblTitleProjectName.Text = name + " (" + projectGateway.GetProjectNumber(currentProjectId) + ")";

                // ... for client
                int companyId = Int32.Parse(hdfCompanyId.Value);
                int currentClientId = projectGateway.GetClientID(Int32.Parse(hdfProjectId.Value.ToString()));
                CompaniesGateway companiesGateway = new CompaniesGateway();
                companiesGateway.LoadAllByCompaniesId(currentClientId, companyId);
                lblTitleClientName.Text = "Client: " + companiesGateway.GetName(currentClientId);

                // Restore searched data (if any)
                projectSectionsNavigatorTDS = (ProjectSectionsNavigatorTDS)Session["lfsProjectSectionsNavigatorTDS"];
                projectSectionsNavigator = projectSectionsNavigatorTDS.LFS_PROJECT_SECTIONS_NAVIGATOR;

                //... for the total rows
                if (projectSectionsNavigatorTDS.LFS_PROJECT_SECTIONS_NAVIGATOR.Rows.Count > 0)
                {
                    lblTotalRows.Text = "Total Rows: " + projectSectionsNavigatorTDS.LFS_PROJECT_SECTIONS_NAVIGATOR.Rows.Count;
                }
                else
                {
                    lblTotalRows.Visible = false;
                }
            }
        }
        protected void btnExportList_Click(object sender, EventArgs e)
        {
            mForm7 master = (mForm7)this.Master;
            ScriptManager scriptManager = (ScriptManager)master.FindControl("ScriptManagerMaster7");

            if (!scriptManager.IsInAsyncPostBack)
            {
                string url = "";
                string headerValues = "";
                int totalColumnsExport = 11;
                int totalColumnsPreview = 11;
                string client = "";
                string name = "";
                string project = "";
                string title = "Manhole Rehabilitation Search Results";
                string columnsForReport = "";
                int j;

                // ... for client
                int companyId = Int32.Parse(hdfCompanyId.Value);
                int currentClientId = Int32.Parse(hdfCurrentClientId.Value.ToString());
                CompaniesGateway companiesGateway = new CompaniesGateway();
                companiesGateway.LoadByCompaniesId(currentClientId, companyId);
                client += "Client: " + companiesGateway.GetName(currentClientId);

                // ... for project
                int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());
                ProjectGateway projectGateway = new ProjectGateway();
                projectGateway.LoadByProjectId(currentProjectId);
                project = projectGateway.GetName(currentProjectId);
                name = client + " > Project: " + project + " (" + projectGateway.GetProjectNumber(currentProjectId) + ")";

                // ... for title view
                if (hdfBtnOrigin.Value == "Go")
                {
                    int viewId = Int32.Parse(ddlView.SelectedValue.Trim());

                    // ... Load name view
                    WorkViewGateway workViewGateway = new WorkViewGateway();
                    workViewGateway.LoadByViewId(viewId, companyId);

                    title = workViewGateway.GetName(viewId);
                }

                // ... For comments option
                string comments = "None";

                headerValues = "";
                columnsForReport = "";

                // Establishing header values
                if (grdMRNavigator.Columns[1].Visible) headerValues += "Manhole No";
                if (grdMRNavigator.Columns[2].Visible) headerValues += " * Street";
                if (grdMRNavigator.Columns[3].Visible) headerValues += " * Latitude";
                if (grdMRNavigator.Columns[4].Visible) headerValues += " * Longitude";
                if (grdMRNavigator.Columns[5].Visible) headerValues += " * Shape";
                if (grdMRNavigator.Columns[6].Visible) headerValues += " * Location";
                if (grdMRNavigator.Columns[7].Visible) headerValues += " * Condition Rating";
                if (grdMRNavigator.Columns[8].Visible) headerValues += " * Prepped Date";
                if (grdMRNavigator.Columns[9].Visible) headerValues += " * Sprayed Date";
                if (grdMRNavigator.Columns[10].Visible) headerValues += " * Batch Date";
                if (grdMRNavigator.Columns[11].Visible) headerValues += " * Comments";

                // Establishing columns to display
                string[] columnsExcel = headerValues.Split('*');

                // ... for visible columns
                for (int i = 0; i < columnsExcel.Length; i++)
                {
                    j = i + 1;
                    columnsForReport += "&header" + j + "=" + columnsExcel[i].Trim();
                }

                // ... For not visible columns
                for (int i = columnsExcel.Length; i < totalColumnsExport; i++)
                {
                    j = i + 1;
                    columnsForReport += "&header" + j + "=None";
                }

                // Report call
                Page.Validate();
                if (Page.IsValid)
                {
                    PostPageChanges();
                    title = title.Replace("'", "%27");
                    Response.Write("<script language='javascript'> {window.open('./mr_print_search_results_report.aspx?" + columnsForReport + "&comments=" + comments + "&totalColumnsPreview=" + totalColumnsPreview + "&totalColumnsExport=" + totalColumnsExport + "&totalSelectedColumns=" + columnsExcel.Length + "&name=" + Server.UrlEncode(name) + "&title=" + Server.UrlEncode(title) + "&format=excel', '_blank', 'toolbar=no, location=no, directories=no, status=yes, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=800, height=680');}</script>");
                }

                if (url != "") Response.Redirect(url);
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            if (!IsPostBack)
            {
                // Security check
                if (!(Convert.ToBoolean(Session["sgLFS_CWP_REHABASSESSMENT_VIEW"]) && Convert.ToBoolean(Session["sgLFS_CWP_REHABASSESSMENT_DELETE"])))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                }

                // Validate query string
                if (((string)Request.QueryString["source_page"] == null) || ((string)Request.QueryString["client_id"] == null) || ((string)Request.QueryString["project_id"] == null))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in ra_delete.aspx");
                }

                // Tag Page
                TagPage();

                // Prepare initial data
                // ... for client
                int currentClientId = Int32.Parse(hdfCurrentClientId.Value.ToString());
                int companyId = Int32.Parse(hdfCompanyId.Value);
                CompaniesGateway companiesGateway = new CompaniesGateway();
                companiesGateway.LoadByCompaniesId(currentClientId, companyId);
                lblTitleClientName.Text = "Client: " + companiesGateway.GetName(currentClientId);

                // ... for project
                int currentProjectId = Int32.Parse(hdfCurrentProjectId.Value.ToString());
                ProjectGateway projectGateway = new ProjectGateway();
                projectGateway.LoadByProjectId(currentProjectId);
                string name = projectGateway.GetName(currentProjectId);
                if (name.Length > 23) name = name.Substring(0, 20) + "...";
                lblTitleProjectName.Text = " > Project: " + name + " (" + projectGateway.GetProjectNumber(currentProjectId) + ") > Selected Sections";

                // If coming from
                // ... ra_navigator2.aspx
                if (Request.QueryString["source_page"] == "ra_navigator2.aspx")
                {
                    StoreNavigatorState();
                    ViewState["update"] = "no";

                    rehabAssessmentTDS = new RehabAssessmentTDS();

                    int workId = Int32.Parse(hdfWorkId.Value);

                    RehabAssessmentSectionDetails rehabAssessmentSectionDetails = new RehabAssessmentSectionDetails(rehabAssessmentTDS);
                    rehabAssessmentSectionDetails.LoadByWorkId(workId, companyId);

                    RehabAssessmentWorkDetails rehabAssessmentWorkDetails = new RehabAssessmentWorkDetails(rehabAssessmentTDS);
                    rehabAssessmentWorkDetails.LoadByWorkId(workId, companyId);

                    RehabAssessmentLateralDetails rehabAssessmentLateralDetails = new RehabAssessmentLateralDetails(rehabAssessmentTDS);
                    rehabAssessmentLateralDetails.LoadAllByWorkId(workId, companyId);

                    // Store dataset
                    Session["rehabAssessmentTDS"] = rehabAssessmentTDS;
                }

                // ... ra_summary.aspx
                if (Request.QueryString["source_page"] == "ra_summary.aspx")
                {
                    StoreNavigatorState();
                    ViewState["update"] = Request.QueryString["update"];

                    // Restore dataset
                    rehabAssessmentTDS = (RehabAssessmentTDS)Session["rehabAssessmentTDS"];
                }
            }
            else
            {
                // Restore datasets
                rehabAssessmentTDS = (RehabAssessmentTDS)Session["rehabAssessmentTDS"];
            }
        }