<%@ Control Language="C#" %>
<%@ Import Namespace="Kesion.Publics" %>
<%@ Import Namespace="Kesion.BLL" %>
<%@ Import Namespace="Kesion.Cache" %>
<%@ Import Namespace="Kesion.HtmlTags" %>
<%@ Import Namespace="Kesion.APPCode" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="Kesion.Course" %>
<%@ Import Namespace="System.Xml" %>
<script runat="server" type="text/C#">
    dynamic __user = HttpContext.Current.Items["user"];                //初始化用户信息，
    private static dynamic __info = new System.Dynamic.ExpandoObject();   //初始化当前页信息
    bool isLoadPage = true;  //定义页面是否加载
    public string A;
    public string isBuyYunserver = string.Empty;
    public string teacherid = string.Empty;
    public int AddType = 0;
    public string KejianID = string.Empty;
    public string KeJianUrl = string.Empty;
    public int isemxpla = 0;
    public int isfree = 0;
    public int isplayback = 0;
    public static int courseIsFree = 0;             //主课程是否免费1收费  0免费
    public static int courseIsChargePeriod = 0;     //主课程是否允许按课时购买 1不允许 0允许
    protected void Page_Load(object sender, EventArgs e)
    {
         Course.CheckMVCVerify("Teacher/LiveList");//判断权限

        isBuyYunserver = Utils.IsBuyYunServer("yunvideo");
        infoInitial();
        A =KSCMS.S("do");
        __info.CourseName = DataFactory.GetOnlyValue("select top 1 name from KS_Course  where CourseID=" + Utils.StrToInt(KSCMS.S("CourseID")));
        if (KSCMS.S("action").Equals("save"))
        {
            SavePeriod();
        }
        switch (A)
        {
            case "edit":
            case "add":
                ClassInitial();
                break;
            case "del":
                DoDel(KSCMS.S("Ids"));
                break;
            case "GetSJ":
                GetSJ();
                KSCMS.Die("");
                break;
            case "pro":
                pro();
                break;
            case "next":
                next();
                break;
        }
    }
    private void infoInitial()
    {
        __info.courseid = Utils.StrToInt(KSCMS.S("courseid"), 0);
        __info.Parentid = Utils.StrToInt(KSCMS.S("ParentID"));
        __info.teacherid = KSCMS.S("teacherid");
        __info.S_ClassID = Utils.StrToInt(KSCMS.S("PeriodID"));
        __info.periodid = KSCMS.S("periodid");
        __info.RadioButtonList4 = Utils.StrToInt(KSCMS.S("RadioButtonList4")).ToString();
        __info.shixian = KSCMS.S("shixian");
        __info.TxtNotice = KSCMS.S("TxtNotice");//课程公告                                
        __info.RadioButtonList2 = Utils.StrToInt(KSCMS.S("RadioButtonList2")).ToString();//是否免费
        __info.radiotype = Utils.StrToInt(KSCMS.S("radiotype")).ToString();
        __info.TxttimeCount = KSCMS.S("TxttimeCount");
        __info.TxtUrl = KSCMS.S("TxtUrl");
        __info.WapUrl = KSCMS.S("WapUrl");
        __info.TextAddress = KSCMS.S("TextAddress");
        __info.TxtYunVideoID = KSCMS.S("TxtYunVideoID");
        __info.TxtOrherVideo = KSCMS.S("TxtOrherVideo");
        __info.TxtMobileOrherVideo = KSCMS.S("TxtMobileOrherVideo");
        __info.Textppt = KSCMS.S("Textppt");
        __info.DrpClassID1 = KSCMS.S("DrpClassID1");//课程分类
        __info.MoreClassID = KSCMS.S("MoreClassList");//更多分类
        __info.moveplaytype = KSCMS.S("moveplaytype");
        __info.ClassName = KSCMS.S("ClassName");
        __info.examPleID = Utils.StrToInt(KSCMS.S("examPleID")).ToString();
        __info.LstB1 = "";
        __info.TxtOrderID = KSCMS.S("TxtOrderID");
        __info.MyItem = KSCMS.S("myitem");
        __info.Txtintro = Utils.ChkSQL(KSCMS.S("Txtintro"));
        __info.AddType = "1";
        __info.RadioLiveStatus = Utils.StrToInt(KSCMS.S("RadioLiveStatus")).ToString();
        __info.TxtPlayOther = KSCMS.S("TxtPlayOther");
        __info.moveLivetype = KSCMS.S("moveLivetype");
        __info.LiveTime = KSCMS.S("LiveTime");
        __info.TextBox4 = KSCMS.S("TextBox4");
        __info.TextUid = KSCMS.S("TextUid");
        __info.liveID = KSCMS.S("liveID");
        __info.TxtIsMobileLivePlayerJS = KSCMS.S("TxtIsMobileLivePlayerJS");
        if (Utils.StrToInt(__info.courseid) == 0)
        {
            __info.courseid = Utils.StrToInt(KSCMS.S("courseid"));
        }
    }

    private string getselect(int courseid,int parentid)
    {
        #region 获取下拉框内容
        StringBuilder sb = new StringBuilder();
        if (courseid != 0)
        {
            DataTable dt = DataFactory.GetDataTable("select PeriodName, periodid,addtype from KS_CosLivePeriod where (addtype=0 or addtype=2) and courseid=" + courseid + " order by orderid");
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    string selected = "";
                    if (dr["periodID"].ToString() == parentid.ToString())
                    {
                        selected = "selected";
                    }
                    if (dr["addtype"].ToString() == "0")
                    {
                        sb.AppendFormat("<option value=\"{1}\" {2}>{0}</option>", "—" + dr["PeriodName"].ToString(), dr["periodID"].ToString(), selected);
                    }
                    else
                    {
                        sb.AppendFormat("<option value=\"{1}\" {2}>{0}</option>", dr["PeriodName"].ToString(), dr["periodID"].ToString(), selected);
                    }
                }
            }
        }
        return sb.ToString();
        #endregion
    }
    private string initialSjClassID(int parentId)
    {
        #region 试卷栏目
        StringBuilder sb = new StringBuilder();
        string selected=","+__info.examPleID+",";
        using (DataTable dt = MyCache.GetCacheSJCategoryTable())
        {
            if (dt != null)
            {
                DataRow[] drr = dt.Select("ParentID=" + parentId.ToString());
                foreach (DataRow dr in drr)
                {
                    int depth = Utils.StrToInt(dr["Depth"].ToString());
                    if (depth <= 3)
                    {
                        int id = Utils.StrToInt(dr["ClassID"].ToString());
                        string CatetoryName = dr["classname"].ToString();
                        if (depth == 2)
                        {
                            CatetoryName = "　├ " + CatetoryName;
                        }
                        if (depth == 3)
                        {
                            CatetoryName = "　   　├ " + CatetoryName;
                        }
                        if(selected.IndexOf(","+id+",")!=-1){
                            sb.AppendFormat("<option value=\"{0}\" {2}>{1}</option>",id.ToString(),CatetoryName,"selected");
                        }
                        else
                        {
                            sb.AppendFormat("<option value=\"{0}\" {2}>{1}</option>",id.ToString(),CatetoryName,"");
                        }
                        initialSjClassID(id);
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
        return sb.ToString();
        #endregion
    }
    private void GetSJ()
    {
        string Key = KSCMS.S("Key");
        if (Key == "")
        {
            return;
        }
        else
        {
            string sql2 = "select top 200 ID,Title from KS_SJ where Title like '%" + Key + "%'";
            using (DataTable dt = DataFactory.GetDataTable(sql2))
            {
                StringBuilder sb = new StringBuilder();
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        sb.AppendFormat(@"<option value=""{0}""{2}>{1}</option>", dr[0].ToString(), dr[1].ToString(), Utils.StrToInt(KSCMS.S("examPleID")) == Utils.StrToInt(dr[0].ToString()) ? " selected" : string.Empty);
                    }
                }
                KSCMS.Die(sb.ToString());
            }
        }
    }
    public string getperiod()
    {
        __info.courseid = Utils.StrToInt(KSCMS.S("courseid"));
        string result=new Kesion.Course.Course().GetManagePeriod(1, __info.courseid, __info.teacherid,"teacher/CsLiveZj");
        result += "#&#";
        return Utils.SplitString(result,"#&#")[0].ToString();
    }
    public void DoDel(string periodid, bool fromuser = false)
    {
        if (Kesion.Course.Course.DeleteCoursePeriod(periodid,__info.courseid,false,true))
        {
            Msg.Alert("删除成功！", KSCMS.GetComeUrl());
            isLoadPage = false;
            return;
        }
    }
    void ClassInitial()
    {
        infoInitial();
        int CourseId = Utils.StrToInt(KSCMS.S("CourseId"));
        getselect(__info.courseid, __info.Parentid);
        __info.MyItem = KSCMS.S("parentid").ToString();
        string sql = string.Empty;

        if (!string.IsNullOrEmpty(KSCMS.S("parentid")))
        {
            if (Convert.ToInt32(KSCMS.S("parentid")) > 0)
            {
                sql = " and  parentid=" + Convert.ToInt32(KSCMS.S("parentid"));
                //  KSCMS.Die(KSCMS.S("parentid"));
            }
        }
        #region 课时自动加1
        int OrderId = Utils.StrToInt(DataFactory.GetOnlyValue("select max(orderid) From KS_CosLivePeriod Where CourseID=" + __info.courseid + sql)) + 1;
        __info.TxtOrderID = OrderId.ToString();
        #endregion
        string sqlStr = "";
        if (KSCMS.S("child") == "1")
        {
            if (KSCMS.S("addtype") == "1")
            {
                sqlStr = "select top 100 PeriodID,PeriodName,Depth from KS_CosLivePeriod where CourseID=" + __info.courseid + " and parentid=" + KSCMS.S("parentid") + " and depth=3 order by root,orderid";
            }
            else
            {
                string ids = DataFactory.GetOnlyValue("select top 1 parentid from KS_CosLivePeriod where periodid=" + Utils.StrToInt(KSCMS.S("parentid"), 0) + "");

                sqlStr = "select top 100 PeriodID,PeriodName,Depth from KS_CosLivePeriod where CourseID=" + __info.courseid + " and parentid=" + ids + " and depth=3 order by root,orderid";
            }
        }
        else
        {
            if (Kesion.Cache.MyCache.GetCourseCommonConfig(69) == "1")
            {
                string ids = DataFactory.GetOnlyValue("select top 1 parentid from KS_CosLivePeriod where periodid=" + Utils.StrToInt(KSCMS.S("parentid"), 0) + "");
                sqlStr = "select top 100 PeriodID,PeriodName,Depth from KS_CosLivePeriod where CourseID=" + __info.courseid + " and parentid=" + ids + " and depth=3 order by root,orderid";
            }
            else
            {
                sqlStr = "select top 600 PeriodID,PeriodName,Depth from KS_CosLivePeriod where parentid=0 and addtype=0 and CourseID=" + __info.courseid + " and periodid not in(select parentid from KS_CosLivePeriod where depth=3 and CourseID=" + __info.courseid + ")  order by root,orderid";
            }
        }
        using (DataTable dt = DataFactory.GetDataTable("select top 1 Name,isfree,chargeperiod from KS_Course  where CourseId =" + Utils.StrToInt(KSCMS.S("CourseID"))))
        {
            if (dt.Rows.Count > 0)
            {
                DataRow dr = dt.Rows[0];
                courseIsFree = Utils.StrToInt(dr["isfree"].ToString());
                courseIsChargePeriod = Utils.StrToInt(dr["ChargePeriod"].ToString());

            }
        }
        if (KSCMS.S("do") == "add")
        {
            string S_ParentID = KSCMS.S("Parentid");
            if (string.IsNullOrEmpty(S_ParentID)) S_ParentID = "0";
            __info.AddType = Utils.StrToInt(KSCMS.S("AddType"), 0).ToString();
            Dictionary<string, string> PeriodInfo = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            string liveType = DataFactory.GetOnlyValue("select top 1 liveType from ks_course where CourseID=" + Utils.StrToInt(KSCMS.S("CourseID")));
            Kesion.Course.Live.InitalCourseLive(PeriodInfo, Utils.StrToInt(liveType),"user");
            PeriodInfo.Add("courseIsFree", courseIsFree.ToString());                    //主课程是否免费0免费  1收费
            PeriodInfo.Add("courseIsChargePeriod", courseIsChargePeriod.ToString());    //主课程是否允许按课时购买 1不允许 0允许
            if (courseIsFree==1 && courseIsChargePeriod == 1) PeriodInfo["IsFree"] = "1";
            Context.Items["courseLive"] = PeriodInfo;
            this.LivePlace.Controls.Add(base.LoadControl("~/Config/Control/SystemCourse/CourseLive.ascx"));

        }
        else
        {
            using (DataTable dt = DataFactory.GetDataTable("select top 1 a.*,b.livetype from KS_CoslivePeriod a inner join ks_course b on a.courseid=b.courseid where a.PeriodID=" + Utils.StrToInt(KSCMS.S("PeriodID"))))
            {
                if (dt.Rows.Count > 0)
                {
                    DataRow dr = dt.Rows[0];
                    __info.radiotype = Utils.StrToInt(dr["type"].ToString()).ToString();
                    __info.ClassName = dr["PeriodName"].ToString().Trim();
                    __info.AddType = dr["addtype"].ToString();
                    isemxpla = Utils.StrToInt(dr["IsExample"].ToString());
                    string[] tpArr1 = string.Concat(dr["url"].ToString(), "|").Split('|');
                    __info.RadioLiveStatus = dr["status"].ToString();
                    if (dr["status"].ToString() == "2")
                    {
                        __info.moveplaytype = Utils.StrToInt(dr["IsPlayBack"].ToString()).ToString();
                        if (dr["IsPlayBack"].ToString() == "0")   //视频类型
                        {
                            __info.TxtUrl = dr["Url"].ToString();  //地址
                        }
                        else
                        {
                            __info.TextAddress = dr["url"].ToString();
                        }
                    }
                    Dictionary<string, string> PeriodInfo = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                    Kesion.Course.Live.InitalCourseLive(PeriodInfo, 0, "user", dr, 1);
                    PeriodInfo.Add("courseIsFree", courseIsFree.ToString());                    //主课程是否免费0免费  1收费
                    PeriodInfo.Add("courseIsChargePeriod", courseIsChargePeriod.ToString());    //主课程是否允许按课时购买 1不允许 0允许
                    Context.Items["courseLive"] = PeriodInfo;
                    this.LivePlace.Controls.Add(base.LoadControl("~/Config/Control/SystemCourse/CourseLive.ascx"));
                    __info.RadioButtonList2 = dr["IsExam"].ToString();//是否有试卷

                    #region 选择试卷ID
                    //************选择试卷ID*********
                    string examPleID = dr["examPleID"].ToString();

                    switch (Utils.StrToInt(dr["IsExam"].ToString()))
                    {
                        case 2:
                            if (string.IsNullOrEmpty(examPleID) || examPleID == "0")
                            {
                                //  __info.Label2 = "暂无指定试卷！";
                            }
                            else
                            {
                                StringBuilder sbb = new StringBuilder();
                                string sql2 = "select ID,Title from KS_SJ where id in(" + examPleID + ")";
                                using (DataTable dt2 = DataFactory.GetDataTable(sql2))
                                {
                                    if (dt2.Rows.Count > 0)
                                    {
                                        foreach (DataRow dr2 in dt2.Rows)
                                        {

                                            sbb.AppendFormat("<option value=\"{1}\" {2}>{0}</option>", dr2["title"].ToString(), dr2["id"].ToString(), "selected");
                                            __info.LstB1 = sbb.ToString();
                                        }
                                    }
                                }
                            }
                            break;
                        case 1:
                            #region 试卷栏目
                            string sj = dr["examPleID"].ToString(); //名师ID；

                            foreach (ListItem li1 in __info.ListSjClass.Items)
                            {
                                if (Utils.InArray(li1.Value, sj, ","))
                                {
                                    li1.Selected = true;
                                }
                            }
                            #endregion
                            break;
                    }
                    //************选择试卷ID*********
                    #endregion

                }

            }
        }
    }
    public void pro()
    {
        #region 上移
        using (DataTable dt = DataFactory.GetDataTable("select top 1 CourseID,PeriodID,orderid from KS_CosLivePeriod Where  parentid=" + __info.Parentid + " and PeriodID =" + __info.S_ClassID))
        {
            if (dt.Rows.Count > 0)
            {
                DataRow dr = dt.Rows[0];
                int minorderid = Utils.StrToInt(DataFactory.GetOnlyValue("select top 1 min(orderid) from KS_CosLivePeriod Where  parentid=" + __info.Parentid + " and CourseID=" + dr["courseid"].ToString()));
                int proid = Utils.StrToInt(DataFactory.GetOnlyValue("select top 1 PeriodID from KS_CosLivePeriod Where CourseID=" + dr["courseid"].ToString() + "and  parentid=" + __info.Parentid + " and  orderid<" + dr["orderid"].ToString() + " order by orderid desc"));
                DataFactory.ExecuteNonQuery("update KS_CosLivePeriod set orderid=orderid+1 where parentid=" + __info.Parentid + " and  PeriodID=" + proid);

                DataFactory.ExecuteNonQuery("update KS_CosLivePeriod set orderid=orderid-1 where  parentid=" + __info.Parentid + " and PeriodID=" + __info.S_ClassID + " and orderid>" + minorderid + "");
                Kesion.Course.CoursePeriodCache.CreateCosJsonToCache(Utils.StrToInt(dr["CourseId"].ToString()));  //生成课时JSON缓存
            }
        }
        JS.Alert("恭喜，上移成功", KSCMS.GetComeUrl());

        #endregion
    }
    public void next()
    {
        #region 下移
        using (DataTable dt = DataFactory.GetDataTable("select top 1 CourseID,PeriodID,orderid from KS_CosLivePeriod Where  parentid=" + __info.Parentid + " and PeriodID =" + __info.S_ClassID))
        {
            if (dt.Rows.Count > 0)
            {
                DataRow dr = dt.Rows[0];
                int maxorderid = Utils.StrToInt(DataFactory.GetOnlyValue("select top 1 max(orderid) from KS_CosLivePeriod Where  parentid=" + __info.Parentid + " and CourseID=" + dr["courseid"].ToString()));
                int proid = Utils.StrToInt(DataFactory.GetOnlyValue("select top 1 PeriodID from KS_CosLivePeriod Where  parentid=" + __info.Parentid + " and CourseID=" + dr["courseid"].ToString() + "and  orderid>" + dr["orderid"].ToString() + " order by orderid asc"));
                DataFactory.ExecuteNonQuery("update KS_CosLivePeriod set orderid=orderid+1 where  parentid=" + __info.Parentid + " and orderid<" + maxorderid + " and  PeriodID=" + __info.S_ClassID);
                DataFactory.ExecuteNonQuery("update KS_CosLivePeriod set orderid=orderid-1 where  parentid=" + __info.Parentid + " and PeriodID=" + proid + " and orderid<>1");
                Kesion.Course.CoursePeriodCache.CreateCosJsonToCache(Utils.StrToInt(dr["CourseId"].ToString()));  //生成课时JSON缓存
            }
        }
        JS.Alert("恭喜，下移成功",KSCMS.GetComeUrl());

        #endregion
    }
    protected void SavePeriod()
    {
        Utils.TipsDisabled();  //检查是否演示状态
        if (string.IsNullOrEmpty(__info.ClassName))
        {
            Msg.Alert("请填写标题",KSCMS.GetComeUrl());
            isLoadPage=false;
            return;
        }



        #region 添加/编辑分类

        int ParentID = 0;
        ParentID = Utils.StrToInt(__info.MyItem, 0);
        if (__info.courseid == 0)
        {
            Msg.Alert("对不起,找不到你要添加的课程，请重新选择!",KSCMS.GetComeUrl());
            isLoadPage=false;
            return;
        }

        if (!string.IsNullOrEmpty( __info.ClassName))
        {
            int Root = 0, Depth = 0;


            DataTable dt = DataFactory.GetDataTable("select top 1 PeriodID,Root,Depth,OrderID,Child,type from [KS_CosLivePeriod] where PeriodID=" + ParentID);
            if (dt.Rows.Count > 0)
            {
                Root = Convert.ToInt32(dt.Rows[0][1].ToString());
                Depth = Convert.ToInt32(dt.Rows[0][2].ToString()) + 1;
            }
            else
            {
                string TRoot = DataFactory.GetOnlyValue("select Max(root) from KS_CosLivePeriod");
                if (TRoot.Equals("0"))
                {
                    Root = 1;
                }
                else
                {
                    Root = Convert.ToInt32(TRoot) + 1;
                }
                Depth = 1;
            }
            Hashtable ht = new Hashtable();
            ht.Add("child", Utils.StrToInt(KSCMS.S("child"), 0));
            ht.Add("CourseID", __info.courseid);
            ht.Add("PeriodName", __info.ClassName);
            ht.Add("Addtype", 1);
            ht.Add("ParentID", ParentID);
            if (A == "edit")
            {

            }
            else
            {
                int orderid = 0;
                if (ParentID == 0)
                {
                    orderid = Utils.StrToInt(DataFactory.GetOnlyValue("select max(orderid) from KS_CosLivePeriod where courseid=" + __info.courseid));//章级的orderid，直接排序
                }
                else
                {
                    orderid = Utils.StrToInt(DataFactory.GetOnlyValue("select max(orderid) from KS_CosLivePeriod where parentidpath like '%" + ParentID + ",%' and courseid=" + __info.courseid));//节级，存在没有orderid的情况
                    if (orderid == 0)
                    {
                        orderid = Utils.StrToInt(DataFactory.GetOnlyValue("select top 1 orderid from KS_CosLivePeriod where periodid=" + ParentID + " and courseid=" + __info.courseid));//没有orderid，查出父orderid
                    }
                }
                ht.Add("Root", Root);
                ht.Add("Depth", Depth);
                ht.Add("orderid", orderid + 1);
                DataFactory.ExecuteNonQuery("update KS_CosLivePeriod set orderid=orderid+1 where orderid>" + orderid + " and courseid=" + __info.courseid + "");
            }

            ht.Add("status", KSCMS.S("RadioLiveStatus"));
            if (KSCMS.S("RadioLiveStatus") == "2")
            {

                ht.Add("Url", KSCMS.S("TextAddress"));

                ht.Add("IsPlayBack", KSCMS.S("moveplaytype"));
            }


            ht.Add("liveid", KSCMS.S("LiveVideoID"));  //直播ID和UID

            ht.Add("LiveTime", KSCMS.S("LiveTime"));
            ht.Add("InvalidDate", KSCMS.S("InvalidDate"));
            if (courseIsFree == 0)
            {
                ht.Add("IsFree", 0);
            }
            else
            {
                ht.Add("IsFree", Utils.StrToInt(KSCMS.S("RadioFree")));
            }

            ht.Add("UserName", UserManage.GetUserInfo().UserName);
            int classid = Utils.StrToInt(__info.S_ClassID, 0);
            ht.Add("isexample",Utils.StrToInt(DataFactory.GetOnlyValue("select top 1 liveType from ks_course where CourseID=" + Utils.StrToInt(KSCMS.S("CourseID")))));
            ht.Add("IsLogin", Utils.StrToInt(KSCMS.S("IsLogin")));


            #region 指定试卷

            ht.Add("IsExam", Utils.StrToInt(__info.RadioButtonList2));//是否有试卷
            string SJIDs = string.Empty;
            switch ((string)__info.RadioButtonList2)
            {
                case "2":
                    SJIDs = KSCMS.S("LstB1");
                    break;
                case "1":

                    #region 指定试卷栏目
                    foreach (ListItem li in __info.ListSjClass.Items)
                    {
                        if (li.Selected == true)
                        {
                            if (string.IsNullOrEmpty(SJIDs))
                            {
                                SJIDs = li.Value;
                            }
                            else
                            {
                                SJIDs += "," + li.Value;
                            }
                        }
                    }
                    #endregion
                    break;
            }

            SJIDs = Utils.FilterIDs(SJIDs);
            SJIDs = Utils.FilterRepeatInArray(SJIDs, ",");
            ht.Add("examPleID", SJIDs);
            #endregion

            if (classid.Equals(0))
            {
                ht.Add("AddDate", DateTime.Now);
                string arstr = string.Empty;

                if (CommonData.Insert("KS_CosLivePeriod", ht))
                {
                    int newPid = CommonData.GetMaxId("KS_CosLivePeriod", "periodid");
                    string parentidpath = newPid.ToString();

                    if (ParentID != 0)
                    {

                        string bigparent = DataFactory.GetOnlyValue("select top 1 parentidpath from KS_CosLivePeriod where courseid=" + __info.courseid + " and periodid=" + ParentID + "");//获取父级的上级 合集路径
                        parentidpath = bigparent + "," + parentidpath;
                    }
                    DataFactory.ExecuteNonQuery("update KS_CosLivePeriod set parentidpath='" + parentidpath + "' where periodid=" + newPid);//更新路径合集
                    CheckAndFixClass(ParentID);
                    arstr = "success";
                   Kesion.Course.Course.SetLiveStatus(__info.courseid, Utils.StrToInt(KSCMS.S("RadioLiveStatus")));//更新课程的直播状态
                }
                else
                {
                    arstr = "failnmae";
                }
                switch (arstr)
                {
                    case "success":
                        CountKS();
                        break;
                    case "failname":
                        Msg.Alert("对不起,分类名称已存在，请重新输入!");

                        break;
                    case "failename":
                        Msg.Alert("对不起,分类英文名称已存在，请重新输入!");
                        break;
                }

            }
            else if (A == "edit")
            {
                string erstr = string.Empty;
                if (CommonData.Update("KS_CosLivePeriod", ht, "where PeriodID=" + classid))
                {
                    erstr = "success";
                    Kesion.Course.Course.SetLiveStatus(__info.courseid, Utils.StrToInt(KSCMS.S("RadioLiveStatus")));//更新课程的直播状态
                }
                else
                {
                    erstr = "failnmae";
                }
                if (erstr.Equals("success"))
                {
                    Kesion.Course.CoursePeriodCache.CreateCosJsonToCache(__info.courseid);  //生成课时JSON缓存
                    Msg.Alert("课时修改成功", BasicField.GetUserUrl("Teacher/CsLiveZj","courseid-"+__info.courseid));
                    isLoadPage=false;
                    return;
                }
                else if (erstr.Equals("failnmae"))
                {
                    Msg.Alert("对不起,请重新输入!");
                    isLoadPage=false;
                    return;
                }
            }
        }
        if (A != "edit")
        {
            Kesion.Course.CoursePeriodCache.CreateCosJsonToCache(__info.courseid);  //生成课时JSON缓存
            Msg.Alert("课时添加成功", BasicField.GetUserUrl("Teacher/CsLiveZj","courseid-"+__info.courseid));
            isLoadPage=false;
            return;
        }


        #endregion
    }
    private void CheckAndFixClass(int parentID)
    {
        #region 更新child
        int Child = Convert.ToInt32(DataFactory.GetOnlyValue("select count(1) from KS_CosLivePeriod where parentidpath like '%" + parentID + ",%' and courseid=" + __info.courseid + ""));

        DataFactory.ExecuteNonQuery("update KS_CosLivePeriod set Child=" + Child + " where periodid=" + parentID);//更新上一级child

        string s = DataFactory.GetOnlyValue("select top 1 parentid from KS_CosLivePeriod where periodid=" + parentID + " and courseid=" + __info.courseid + "");
        if (Utils.StrToInt(s, 0) != 0)//如果存在章级，更新章级
        {
            DataFactory.ExecuteNonQuery("update KS_CosLivePeriod set Child=Child+1  where periodid=" + s);
        }

        #endregion
    }
    private void CountKS()
    {
        #region 统计课时数
        int CountPid = Utils.StrToInt(DataFactory.GetOnlyValue("select count(1) From KS_CosLivePeriod Where (addtype=1 or addtype is null) and  CourseID=" + __info.courseid));
        DataFactory.ExecuteNonQuery("UPDATE KS_Course Set CountPid=" + CountPid + " WHERE CourseId=" + __info.courseid);
        #endregion
    }
    public string InniaLivePlay()
    {
        #region 初始直播视频类型
        StringBuilder sb = new StringBuilder();
        string isBuyYunserver = Utils.IsBuyYunServer("yunvideo");
        if (isBuyYunserver == "1")
        {
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(Utils.GetMapPath(KSCMS.GetInstallDir() + "config/course/PCLivePlay.config"));
            foreach (XmlNode xn in xmldoc.SelectNodes("//liveplay/item"))
            {
                ListItem li = new ListItem();
                if (xn.SelectSingleNode("@isdefault").InnerText == "true")
                {
                    string selected = "";
                    if (__info.moveLivetype == xn.SelectSingleNode("@id").InnerText)
                        selected = "selected";
                    sb.AppendFormat("<option value=\"{0}\" {2}>{1}</option>", xn.SelectSingleNode("@id").InnerText, xn.SelectSingleNode("@name").InnerText, selected);
                    break;
                }
                //this.moveplaytype.Items.Add(li);
            }
            foreach (XmlNode xn in xmldoc.SelectNodes("//liveplay/item"))
            {
                ListItem li = new ListItem();
                if (xn.SelectSingleNode("@enable").InnerText == "true" && xn.SelectSingleNode("@isdefault").InnerText == "false")
                {
                    string selected = "";
                    if (__info.moveLivetype == xn.SelectSingleNode("@id").InnerText)
                        selected = "selected";
                    sb.AppendFormat("<option value=\"{0}\" {2}>{1}</option>", xn.SelectSingleNode("@id").InnerText, xn.SelectSingleNode("@name").InnerText, selected);
                }
                //this.moveplaytype.Items.Add(li);

            }
        }
        else
        {

            string selecteds = "";
            if (__info.moveLivetype == "100")
                selecteds = "selected";
            sb.AppendFormat("<option value=\"{0}\" {2}>{1}</option>", "100", "其他", selecteds);

        }
        #endregion
        return sb.ToString();
    }
</script>
<%
    if (!isLoadPage) return;
%>
<%if (KSCMS.S("do") != "add" && KSCMS.S("do") != "edit")
  { %>
  
<div class="t_tybox">
   	<div class="tytitle"><h4>课时管理</h4>
		<a onclick="add(<%=__info.courseid.ToString()%>,0,0)"  href="javascript:void(0);" class="addbtn" ><b></b>添加章</a>
		<a onclick="add(<%=__info.courseid.ToString()%>,2,0)"  href="javascript:void(0);" class="addbtn"><b></b>添加节</a>
		<a href="<%=BasicField.GetUserUrl("teacher/CsLiveZj","do-add,addtype-1,courseid-"+__info.courseid+",parentid-0") %>" class="addbtn"><b></b>添加课时</a>
	<a href="<%=BasicField.GetUserUrl("teacher/livelist") %>" class="addbtn">返回</a>
   	</div>
    <div class="clear blank20"></div>  
    <div class="part_now">当前课程：<%=__info.CourseName %></div>
    <div class="clear blank10"></div> 
	
		 <div class="courseKeshi">
				<div class="lineY"></div>
				<ul id="myloop">
		<%=getperiod()%>
				</ul>
         </div>
		 </div>
		 <%}
	 else{ %>
	 <script src="/ks_inc/DatePicker/WdatePicker.js"></script>
	<div class="t_tybox">
	 	<form name="aspnetForm" method="post" action="<%=BasicField.GetUserUrl("teacher/CsLiveZj","do-"+KSCMS.S("do"))%>" id="aspnetForm">
		<input type="hidden" name="action" value="save" />
	 <div class="ty_title">添加课时</div>       			   
	 <table width="100%" border="0" cellpadding="0" cellspacing="0" class="border">
		<input name="child" type="text" value="0" id="child" style="width:50px;display:none" />
		<tr>
		  <td class="lefttd" height="30" align="right"><strong>当前课程：</strong></td>
		  <td class="tag_left"><%=__info.CourseName %></td>
		  <input type="hidden" value="<%=__info.courseid %>" name="courseid" />
		  <input type="hidden" value="<%=__info.periodid %>" name="periodid" />
		</tr>
		<tr>
			<td class="lefttd" height="30" align="right"><font color="red">*</font>  <strong>标题：</strong></td>
			<td class="tag_left">
				<span id="Span2">
					<input name="ClassName" type="text" value="<%=__info.ClassName %>" id="ClassName" class="textbox" style="width:350px;" />
				</span>
			</td>
		</tr>
		   <tr>
                       <td align="right" class="lefttd" style="width: 155px; height: 37px;"><strong>
                           所属章节：</strong><br>
                         </td>
                         <td class="tag_left" style="height: 37px;">
						 <input type="hidden" name="MyItem" value="<%=__info.Parentid %>" />
                             <select name="ctl00$KSContent$MyItem" id="MyItem"  style="width:250px;">
		<option value="0">请选择章节</option>
	<%=getselect(__info.courseid,__info.Parentid) %>

	</select>
                       </td>
                    </tr>  
		<tbody id="Tbody5" style="display:none">
			 <tr>
				<td align="right" class="lefttd" height="30" ><strong>是否有模拟试卷：</strong></td>
				<td class="tag_left">
					
					<table id="RadioButtonList2" onclick="showwatermarkarea()" border="0" style="height:24px;">
		<tr>
			<td><input id="RadioButtonList2_0" type="radio" name="RadioButtonList2" value="0" <%=__info.RadioButtonList2=="0"?"checked":"" %> />
			<label for="RadioButtonList2_0">无</label></td>

			<td><input id="RadioButtonList2_1" type="radio" name="RadioButtonList2" value="2"  <%=__info.RadioButtonList2=="2"?"checked":"" %> />
			<label for="RadioButtonList2_1">指定试卷ID</label></td>
		</tr>
	</table>
				</td>
			</tr>
			<tbody id="watermark0" style="display:none;">
				<tr>
					<td align="right" class="lefttd"><strong>试卷栏目：</strong></td>
					<td class="righttd">
						<select size="4" name="ListSjClass" multiple="multiple" id="ListSjClass" style="height:300px;width:150px;float:left;height:200px !important; background:#fff">
	<%=initialSjClassID(0) %>
	
	</select>
						<a class="textarea_min" href="javascript:zoomtextarea(-5,'ListSjClass');"></a>
						<a class="textarea_max" href="javascript:zoomtextarea(5,'ListSjClass');"></a>
					</td>
				</tr>
			</tbody>
			<tbody id="watermark2" style="display:none;">
				<tr>
					<td align="right" class="lefttd" height="30"><strong>试卷ID：</strong></td>
					<td class="righttd" valign="top">&nbsp;
						<table border="0" width='100%' class="exam_seacher">
							<tr>
								<td class="tag_left" width="320" style="line-height: 30px;">搜索试卷<span class="top_c_sc clearfix"><input name="TxtSJKey" type="text" id="TxtSJKey" class="textbox" style="width:160px;" />
									<input type="button" value="搜索" class="button" onclick="searchSJ();" cssclass="button" style="margin-left: 10px; border-radius: 5px; border: 1px solid #dce2e4;" /></span>
									<br />
									<br />
									<select size="4" name="LstB2" multiple="multiple" id="LstB2" style="height:300px;width:200px;float: left; height: 200px !important; background: #fff">

	</select>
								</td>
								<td>
									<p>
										<input type="button" value=" > " onclick="addUser()" class="ty_button" />
									</p>
									<br />
									<p>
										<input type="button" value=" < " onclick="delUser()" class="ty_button" />
									</p>
								</td>
								<td class="tag_left" style="line-height: 30px;">指定试卷如下：
									<br />
									<br />
									<select size="4" name="LstB1" multiple="multiple" id="LstB1" style="height:300px;width:200px;float: left; height: 200px !important; background: #fff">
									<%=__info.LstB1 %>
	</select>
								</td>
							</tr>
						</table>
					</td>
				</tr>				
			 </tbody>
		   </tbody>
		   <script>
		   	$(document).ready(function () {
		   		if (parseInt(1) == 1) {
		   			jQuery("#Tbody5").css("display", "");
		   			jQuery("#zjclass").show();
		   		}
		   		jQuery("#tbody10").show();
		  
		   	});

		   </script>
          <tr style="display:none">
					<td align="right" class="lefttd" height="30"><strong>课时编号：</strong></td>
					<td class="lefttd">&nbsp;<input name="TxtOrderID" id="TxtOrderID" style="display:inline-block;width:20px;" value="<%=__info.TxtOrderID %>">课时</td>
		  </tr>	                  
		  <asp:PlaceHolder ID="LivePlace"  runat="server"></asp:PlaceHolder> 
	   </table>
        <div class="clear blank10"></div>
        <div class="cz_btn nofloat" style="padding-left:195px">
     		<span><input type="submit" name="Button2" value="确定保存" onclick="return(CheckForm());" id="Button2" class="button" /></span>
            <span><input type="button" class="button" onclick="window.history.go(-1);"value=" 返 回 "></span>
        </div>
  		<div class="clear blank20"></div>
        </form>
    </div>
		<%} %>
		 <script>	
		 

		 	function CheckForm() {
		 		if (jQuery('#ClassName').val() == '') {
		 			KesionJS.Alert('请输入标题名称！', "jQuery('#ClassName').focus()");
		 			return false;
		 		}

		 		var idArr = new Array();
		 		var dest = document.getElementById('LstB1');
		 		for (var i = 0; i < dest.options.length; i++) {
		 			dest.options[i].selected = "true";
		 			idArr.push(dest.options[i].value);
		 		}
		 		return true;
		 	}
      </script>	
	    <script>
	    	jQuery(document).ready(function () {
	    		showwatermarkarea();
	    		getmyPeriod();
	    	
	    
	    	});
	    	
	    	function getmyPeriod() {
	    	
	    		var msg = $("#myloop").html();
	    	
	    				msg = msg + "#&##&##&#";
	    				$("#myloop").html(msg.split("#&#")[0]);
	    				$("#zhangnum").html(msg.split("#&#")[1]);
	    				$("#jienum").html(msg.split("#&#")[2]);
	    				$("#shinum").html(msg.split("#&#")[3]);

	    				var num = $("#myloop li").length;
	    				if (num == 0) {
	    					$("#myloop").prev(".lineY").hide();
	    					$("#myloop").html('<div class="empty">您还未添加任何课时</div>')
	    				};

	    				$("#myloop li").hover(function () {
	    					$(this).find(".rButton").show();
	    				}, function () {
	    					$(this).find(".rButton").hide();
	    				});

	    				$(".addButton").click(function () {
	    					$(this).toggleClass("addOn");
	    				});

	    				$(".rButton .icon").hover(function () {
	    					$(this).find("span").show();
	    				}, function () {
	    					$(this).find("span").hide();
	    				});
	    				$(".rButton").click(function () {
	    					doNone(click());
	    				});

	    				//展开收缩
	    				click();
	    				function click() {
	    					$(".chapter,.section").click(function () {
	    						$(this).find(".menubtn").toggleClass("menubtn2");
	    						$(this).next(".box").stop().slideToggle(300);
	    					});
	    				};
	    				//是否添加按钮
	    				$(".menubtn").each(function () {
	    					var num = $(this).parent().next(".box").length;
	    					if (num == 0) {
	    						$(this).hide();
	    					};
	    				});
	    				$(".chapterBox").each(function () {
	    					var i = $(this).index() + 1;
	    					if (i > 10) {
	    						$(this).find(".chapter .menubtn").addClass("menubtn2");
	    						$(this).find(".chapter").siblings(".box").hide();
	    					};
	    				});
	    	}
	    	function doNone(evt) {
	    		var e = (evt) ? evt : window.event; //判断浏览器的类型，在基于ie内核的浏览器中的使用cancelBubble
	    		if (window.event) {
	    			e.cancelBubble = true;
	    		} else {
	    			e.stopPropagation();
	    		}
	    	}
	    	function showwatermarkarea() {
	    		// alert("dd");
	    		var checkrad = jQuery("#RadioButtonList2 :radio[checked]").val();
	    		if (checkrad == "2") {
	    			jQuery("#watermark0").css("display", "none");
	    			jQuery("#watermark2").css("display", "");
	    		} else if (checkrad == "1") {
	    			jQuery("#watermark0").css("display", "");
	    			jQuery("#watermark2").css("display", "none");
	    		}
	    		else {
	    			jQuery("#watermark0").css("display", "none");
	    			jQuery("#watermark2").css("display", "none");
	    		}
	    	}
	    	var puburl="<%= BasicField.GetUserUrl("teacher/courselist")%>";
	    	function searchSJ() {
		
	    		var key = jQuery("#TxtSJKey").val();
	    		if (key == '') {
	    			KesionJS.Alert("请输入试卷关键字！", "jQuery('#TxtSJKey').focus()");
	    			return false;
	    		} else {
				
	    			puburl="/plus/course/CourseAjax.ashx?action=getsearchsj&courseid=<%=__info.courseid%>&key=" + escape(key)

				jQuery.ajax({ url: puburl, success: function (d) {
					jQuery("#LstB2").empty();
					jQuery("#LstB2").html(d);
				}
				});
			
			}
		}
	    	function addUser() {
	    		var src = document.getElementById('LstB2');
	    		var dest = document.getElementById('LstB1');

	    		for (var i = 0; i < src.options.length; i++) {
	    			if (src.options[i].selected) {
	    				var exist = false;
	    				for (var j = 0; j < dest.options.length; j++) {
	    					if (dest.options[j].value == src.options[i].value) {
	    						exist = true;
	    						break;
	    					}
	    				}
	    				if (!exist) {
	    					var opt = document.createElement('OPTION');
	    					opt.value = src.options[i].value;
	    					opt.text = src.options[i].text;
	    					opt.selected=true;
	    					dest.options.add(opt);
	    				}
	    			}
	    		}
	    	}
	    	function delUser() {
	    		var dest = document.getElementById('LstB1');

	    		for (var i = dest.options.length - 1; i >= 0; i--) {
	    			if (dest.options[i].selected) {
	    				dest.options[i] = null;
	    			}
	    		}
	    	}
	    	var box = '';
	    	function openWin(title, url, isreload, width, height) {
	    		if (width == null) width = 760;
	    		if (height == null) height = 450;
	    		box = $.dialog.open(url, {
	    			id: 'topbox', lock: true, title: title, width: width, height: height, close: function () {
	    				if (isreload) {
	    					frames['main'].location.reload();
	    				}
	    			}
	    		});
	    	}
	   
	    	function add(id, type, parentid) {
	    		var iWidth = 400;
	    		var iHeight = 200;
	    		var iTop = (window.screen.availHeight - 30 - iHeight) / 2;
	    		var iLeft = (window.screen.availWidth - 10 - iWidth) / 2;
	    	
	    		var url = "<%=BasicField.GetUserUrl("teacher/CsAddLiveZj","do-add")%>";

	    		url += ",type-" + type + ",parentid-" + parentid + ",courseid-" + id + ",frame-no";
	    	
	    		//parent.open('TcAddZj.aspx?action=add&Courseid='+id,'添加章节','width=500,height=300,top='+iTop+',left='+iLeft+'');
	    		openWin('添加章节',url, false, 500, 250);
	    	}
	    	function edit(id, Periodid, type, parentid) {
	    		var iWidth = 400;
	    		var iHeight = 200;
	    		var iTop = (window.screen.availHeight - 30 - iHeight) / 2;
	    		var iLeft = (window.screen.availWidth - 10 - iWidth) / 2;
	    		var url = "<%=BasicField.GetUserUrl("teacher/CsAddLiveZj","do-edit")%>";

	    		url += ",type-" + type + ",parentid-" + parentid + ",courseid-" + id + ",frame-no,Periodid-"+Periodid;
	    		openWin('修改章节', url, false, 500, 250);
	    		//	parent.open( 'TcAddZj.aspx?action=edit&Courseid='+id+'&Periodid='+Periodid,'修改章节','width=500,height=300,top='+iTop+',left='+iLeft+'');
	    	}
	    	function pro(id, parentid) {
	    		var url = "<%=BasicField.GetUserUrl("teacher/CsAddLiveZj","do-pro")%>";
	    		url += ",parentid-" + parentid + ",courseid-" + <%=__info.courseid%> + ",Periodid-" + id;
	    		location.href = url;
	    	}
	    	function next(id, parentid) {
	    		var url = "<%=BasicField.GetUserUrl("teacher/CsAddLiveZj","do-next")%>";
	    		url += ",parentid-" + parentid + ",courseid-" + <%=__info.courseid%> + ",Periodid-" + id;
	    		location.href = url;
	    	}
	    	function SetDownUrlByUpLoad(v, s) {
	    		jQuery("#TxtUrl").val(v);
	    	}
   </script>