using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using SES.DB;

public partial class MasterPage : System.Web.UI.MasterPage {

    private ProfileCommon pc;

    void Page_PreInit(object sender, EventArgs e) {
        //string sEng = "";
        //try {
        //    if (Session.Contents != null && Session.Contents["Localization"] != null)
        //        sEng = Session.Contents["Localization"].ToString();
        //    if (Request.Form.Get("ctl00$selLanguage") != null)
        //        sEng = Request.Form.Get("ctl00$selLanguage").ToString();
        //}
        //catch (Exception ex) {
        //    Console.Write(ex.Message);
        //}


        //if (sEng != null && sEng != "") {
        //    }
        //switch (sEng) {
        //    case "zh-TW":
        //        selLanguage.SelectedIndex = 0;
        //        //Page.UICulture = "zh-TW";
        //        break;
        //    case "ja":
        //        selLanguage.SelectedIndex = 1;
        //        //Page.UICulture = "ja-JP";
        //        break;
        //    case "en":
        //        selLanguage.SelectedIndex = 2;
        //        //Page.UICulture = "en-US";
        //        break;
        //}

        //System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(sEng);
        //System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(sEng);

        //Session["Localization"] = sEng;
        //Page.UICulture = "ja-JP";
        //Page.Culture = "auto:" + sEng
        //}
        Page.Theme = Profile.UI.Theme;

    }
    protected void Page_Load(object sender, EventArgs e) {
        Response.Cookies["Authority"].Value = "Yes";
        Response.Cookies["Authority"].Expires = DateTime.Now.AddDays(1);
        Response.Cookies["User"].Value = Profile.UserName;

        // KM 的超連結
        //hlKMLink.NavigateUrl = System.IO.Path.Combine(Request.Url.Scheme + "://" + Request.Url.Authority, "KM" ) + "/login.aspx";
        //hlKMLink.Attributes.Add("onclick", "window.open('" + System.IO.Path.Combine(Request.Url.Scheme + "://" + Request.Url.Authority, "/KM") + "/login.aspx" + "')");
        hlKMLink.Attributes.Add("onclick", "window.open('" + System.IO.Path.Combine(Request.Url.Scheme + "://" + Request.Url.Authority, "/KM") + "/login.aspx?User=" + Profile.UserName + "')");
        hlKMLink.Attributes.Add("style", "cursor: hand; color: #F6F6F6");

        try { pc = (ProfileCommon)this.Context.Profile; }
        catch { }
        if (!IsPostBack) {
            foreach (ListItem li in ddlLanguage.Items) {
                if (li.Value == pc.lang)
                    li.Selected = true;
                else
                    li.Selected = false;
            }

            ddlTheme.Items.FindByValue(Profile.UI.Theme).Selected = true;

            //string s=pc.UserName;
            //s = Profile.Providers["SES_ProfileProvider"].ApplicationName  ;
            //s = Profile.Providers["SES_ConnectionHelper"].ApplicationName;
            //s= Profile.Providers["ProfileProvider"].ApplicationName;


            //SiteMap.SiteMapResolve += new SiteMapResolveEventHandler(this.ModifyPath);


            if (Profile.UserName.Length < 15) {
                lblWelcome.Text = Resources.Universal.Msg_LoginUser + " : " + Profile.UserName;
                lblWelcome.Visible = true;
                hlLogin.Visible = false;
                lbnLogout.Visible = true;
            }
            else {
                hlLogin.Text = Resources.Universal.Msg_PleaseLogin;
                lblWelcome.Visible = false;
                hlLogin.Visible = true;
                lbnLogout.Visible = false;
            }
        }


        SiteMap.SiteMapResolve += new SiteMapResolveEventHandler(this.ModifyPath);
    }
    public void Logout(Object s, EventArgs e) {
        FormsAuthentication.SignOut();
        Response.Redirect("~/Login.aspx");
    }


    // =========== TopOf SiteMapPath 如果沒有連結的網頁 (某一個根目錄) 則 URL 設為空 ===============
    private SiteMapNode ModifyPath(object sender, SiteMapResolveEventArgs e) {
        if (SiteMap.CurrentNode != null) {
            SiteMapNode currentNode = SiteMap.CurrentNode.Clone(true);

            return checkURL(currentNode);
        }
        else
            return null;
    }
    private SiteMapNode checkURL(SiteMapNode smn) {
        if (smn != null) {
            if (smn.Url.EndsWith("#")) {
                smn.Url = "";
            }
            if ((smn.ParentNode) != null) {
                checkURL(smn.ParentNode);
            }
        }

        return smn;
    }
    // =========== BottomOf SiteMapPath 如果沒有連結的網頁 (某一個根目錄) 則 URL 設為空 ===============



    protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e) {
        //HttpCookie cookie = new HttpCookie("selLanguage");
        //cookie.Value = selLanguage.UniqueID;
        //Response.SetCookie(cookie);
        pc.lang = ddlLanguage.SelectedValue;
        Response.Redirect(Request.RawUrl);
    }
    protected void ddlTheme_SelectedIndexChanged(object sender, EventArgs e) {
        pc.UI.Theme = ddlTheme.SelectedValue;
        Response.Redirect(Request.RawUrl);
    }




    protected void TreeView1_DataBinding(object sender, EventArgs e) {
        
    }
    string[] arAbailable = null;
    //////////////////////////////////////////////////////////////////////////////////
    //當 Treeview databounding 時秀出真正要顯示的內容
    protected void TreeView1_DataBound(object sender, EventArgs e) {
        //if (!IsPostBack)
        //    ValidateAndShoeTreeView(Profile.UserName, txtPassword.Text);

        if (!IsPostBack) {
            // 取得有權限的節點
            string sCondition = ""; // 未登入
            if (Profile.UserName.Length > 15)
                arAbailable = new string[] { "unauthorized" };
            else { // 已登入
                sCondition = " (Account='Anonymous' and RoleOrUser='Role') " + " or Account='" + Profile.UserName + "' ";
                arAbailable = new WebAuthorityData().Select("Page", sCondition);
                // 移除沒有權限的節點
                if (arAbailable == null)
                    arAbailable = new string[] { "unauthorized" };
            }
            RemoveNode(TreeView1.Nodes[0]);
        }


        // -------------- Top Of 控制按下的節點有網址時的 TreeView1 的收合 --------------
        // 如果導致 ErrorPage.aspx 時則 tn 為 null (to catch),此時會收合全部節點
        TreeNode tn = TreeView1.SelectedNode;
        if (tn == null) {
            //    tn = TreeView1.Nodes[Convert.ToInt32(ViewState["tvSelectedIndex"])];
            try {
                tn = getCurrentNode(TreeView1.Nodes[0], Request.UrlReferrer.LocalPath);
            }
            catch { }
        }
        try {
            TreeView1.CollapseAll();    
            if (!tn.NavigateUrl.EndsWith("#")) {
                //收合全部的節點再展開目前路徑的節點
                if (tn != null) {
                    while (true) {
                        tn.Expand();

                        if (tn.Parent != null)
                            tn = tn.Parent;
                        else {
                            break;
                        }
                    }
                    tn.Select();
                }
            }
        //ViewState["selectedNode"] = tn;
        }
        catch { }
        // -------------- Bottom Of 控制按下的節點有網址時的 TreeView1 的收合 --------------
    }
    TreeNode getCurrentNode(TreeNode tn, string URL) { 
        TreeNodeCollection tnAll = tn.ChildNodes ;
        string sTmpURL = "";
        foreach (TreeNode tnTemp in tnAll) { 
            // 只留網址不包含參數
            if (tnTemp.NavigateUrl.IndexOf("?") > -1 )
                sTmpURL = tnTemp.NavigateUrl.Substring(0, tnTemp.NavigateUrl.IndexOf("?"));
            else
                sTmpURL = tnTemp.NavigateUrl;

            // 判斷到的節點如果和 Request.UrlReferrer.LocalPath 一樣則選取該節點
            if (sTmpURL == URL)
                return tnTemp;
            else{
                TreeNode rtnNode = getCurrentNode(tnTemp, URL);
                if (rtnNode != null) return rtnNode;
            }      
        }
        return null;
    }
    protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e) {
        // -------------- Top Of 控制按下的節點沒有網址時的 TreeView1 的收合 --------------
        TreeView1.CollapseAll();
        TreeNode tn = TreeView1.SelectedNode;

        //收合全部的節點再展開目前路徑的節點
        if (tn != null) {
            while (true) {
                tn.Expand();

                if (tn.Parent != null)
                    tn = tn.Parent;
                else {
                    break;
                }
            }
            tn.Select();
            //ViewState["tvSelectedIndex"] = TreeView1.Nodes.IndexOf(tn);
        }
        // -------------- Bottom Of 控制按下的節點沒有網址時的 TreeView1 的收合 --------------
    }

    //從資料庫中判斷該使用者可視的選單
    private bool RemoveNode(TreeNode tn) {
        //bool bRemove = false;
        int i=0, j=0;

        for (j = 0; j < arAbailable.Length; j++) {
            if (arAbailable[j] != "" && tn.NavigateUrl.IndexOf(arAbailable[j]) > -1) {
                return false;       // 如果節點已出現, 則子節點將不再判斷
            }
        }

        // 將要移除的TreeNode 先放在 arRemoveTN 中
        TreeNode[] arRemoveTN = new TreeNode[tn.ChildNodes.Count];
        foreach (TreeNode tn1 in tn.ChildNodes) {
            if (RemoveNode(tn1) && tn1.ChildNodes.Count <= 0) { // 如果沒有出現該節點的權限同時該節點是終端節點則移除該節點
                arRemoveTN[i] = tn1;
                i++;
            }
        }
        // remove non authorization item
        for (i = 0; i < arRemoveTN.Length; i++) {
            if (arRemoveTN[i] != null)
                tn.ChildNodes.Remove(arRemoveTN[i]);
            else
                break;
        }

        return true;
    }


    // 判斷所連結的網頁是不是以開新的方式顯示 (配合 web.SiteMap 檔案中的 Description 屬性)
    protected void TreeView1_TreeNodeDataBound(object sender, TreeNodeEventArgs e) {
        if (((SiteMapNode)e.Node.DataItem).Description == "_blank") {
            e.Node.Target = "_blank";
        }

        if (e.Node.NavigateUrl.EndsWith("#"))
            e.Node.NavigateUrl = "";

    }


    protected void btnLogin_Click(object sender, EventArgs e) {
        //TreeView1.DataSourceID = "SiteMapDataSource1";
        //TreeView1.DataBind();

        //ValidateAndShoeTreeView(txtAccount.Text, txtPassword.Text);

        //if (IsAuthorized) {
        //    lblWelcome.Text = "Welcome !! " + txtAccount.Text; lblWelcome.Visible = true;
        //}
        
        Response.Redirect("~/SEST/login.aspx");
    }

}
