<%@ 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" %>
<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 int isfree = 0;
    public string teacherid = string.Empty;
    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/CourseList");//判断权限

        infoInitial();
        A =KSCMS.S("do");
        __info.CourseName = DataFactory.GetOnlyValue("select top 1 name from KS_Course  where CourseID=" + Utils.StrToInt(KSCMS.S("CourseID")));

        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;
        }
        if (KSCMS.S("action").Equals("save"))
        {
            Utils.TipsDisabled();  //检查是否演示状态
            SavePeriod();
        }

    }
    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");
        switch (Utils.StrToInt(KSCMS.S("radiotype")))
        {
            case 1:
                __info.Textppt = KSCMS.S("Textppts");
                break;
            default:
                __info.Textppt = KSCMS.S("Textppt");
                break;
        }
        __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.RadioButtonList1 = KSCMS.S("RadioButtonList1");
        __info.MyItem = KSCMS.S("myitem");
        __info.Txtintro = Utils.ChkSQL(KSCMS.S("Txtintro"));
        __info.RadioButtonList3 = KSCMS.S("RadioButtonList3");
        __info.TextMoney = KSCMS.S("TextMoney");
        __info.jifen =Utils.StrToInt(KSCMS.S("jifen"));
        if (Utils.StrToInt(__info.courseid) == 0)
        {
            __info.courseid = Utils.StrToInt(KSCMS.S("courseid"));
        }

    }

    private string getselect(int courseid,int periodid)
    {
        #region 获取下拉框内容

        StringBuilder sb = new StringBuilder();

        if (courseid != 0)
        {
            DataTable dt = DataFactory.GetDataTable("select PeriodName, periodid,addtype from KS_CosPeriod where (addtype=0 or addtype=2) and courseid=" + courseid + " order by orderid");
            if (dt.Rows.Count > 0)
            {
                int i = 1;
                foreach (DataRow dr in dt.Rows)
                {
                    string selected = "";
                    if (dr["periodID"].ToString() == periodid.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(0, __info.courseid, __info.teacherid,"teacher/cszj");
        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(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_CosPeriod Where CourseID=" + __info.courseid + sql)) + 1;
        __info.TxtOrderID = OrderId.ToString();
        #endregion


        //绑定分类列表控件
        //  GetTree(ChannelID, ref ParentID);

        string sqlStr = "";

        if (KSCMS.S("child") == "1")
        {
            if (KSCMS.S("addtype") == "1")
            {
                sqlStr = "select top 100 PeriodID,PeriodName,Depth from KS_CosPeriod 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_Cosperiod where periodid=" + Utils.StrToInt(KSCMS.S("parentid"), 0) + "");

                sqlStr = "select top 100 PeriodID,PeriodName,Depth from KS_CosPeriod 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_Cosperiod where periodid=" + Utils.StrToInt(KSCMS.S("parentid"), 0) + "");
                //   KSCMS.Die(ids);
                sqlStr = "select top 100 PeriodID,PeriodName,Depth from KS_CosPeriod where CourseID=" + __info.courseid + " and parentid=" + ids + " and depth=3 order by root,orderid";

            }
            else
            {
                sqlStr = "select top 600 PeriodID,PeriodName,Depth from KS_CosPeriod where parentid=0 and addtype=0 and CourseID=" + __info.courseid + " and periodid not in(select parentid from KS_CosPeriod 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 (Utils.StrToInt(dr["isfree"].ToString()) <= 0)
                {
                    __info.RadioButtonList1 = "0";
                }
                else
                {
                    isfree = 1;
                }
            }
        }


        string _Cosname = Utils.StrFormat(DataFactory.GetOnlyValue("select top 1 Name from KS_Course  where CourseId =" + Utils.StrToInt(KSCMS.S("CourseID"))));
        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);

            Dictionary<string, string> PeriodInfo = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            Kesion.Course.Course.InitalCoursePeriod(PeriodInfo, 1,"user");
            Context.Items["courseperiod"] = PeriodInfo;
            this.PeriodPlace.Controls.Add(base.LoadControl("~/Config/Control/SystemCourse/CoursePeriod.ascx"));


        }
        else
        {
            using (DataTable dt = DataFactory.GetDataTable("select top 1 * from KS_CosPeriod where PeriodID=" + __info.periodid))
            {
                if (dt.Rows.Count > 0)
                {
                    DataRow dr = dt.Rows[0];

                    __info.ClassName = dr["PeriodName"].ToString().Trim();

                    __info.AddType = Utils.StrToInt(dr["addtype"].ToString());

                    Dictionary<string, string> PeriodInfo = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                    Kesion.Course.Course.InitalCoursePeriod(PeriodInfo, 1, "user", dr, 1);
                    Context.Items["courseperiod"] = PeriodInfo;
                    this.PeriodPlace.Controls.Add(base.LoadControl("~/Config/Control/SystemCourse/CoursePeriod.ascx"));

                    __info.RadioButtonList1 = Utils.StrToInt(dr["IsFree"].ToString()).ToString(); //是否免费
                    __info.TxtOrderID = dr["orderid"].ToString();

                    __info.RadioButtonList2 = dr["IsExam"].ToString();//是否有试卷


                    if (isfree == 1)//课程收费
                    {
                        __info.RadioButtonList1 = Utils.StrToInt(dr["IsFree"].ToString()).ToString(); //外层是否免费
                        if (dr["IsFree"].ToString() == "0")//课时免费
                        {
                            __info.jifen = dr["jifen"].ToString();
                            __info.RadioButtonList3 = Utils.StrToInt(dr["IsRepeat"].ToString(), 0).ToString();
                        }
                        else//课时收费
                        {
                            __info.TextMoney = Utils.StrToFloat(dr["money"].ToString()).ToString("0.00");
                        }
                    }
                    else
                    {
                        __info.RadioButtonList3 = Utils.StrToInt(dr["IsRepeat"].ToString(), 0).ToString();
                        __info.jifen = dr["jifen"].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_CosPeriod 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_CosPeriod Where  parentid=" + __info.Parentid + " and CourseID=" + dr["courseid"].ToString()));
                int proid = Utils.StrToInt(DataFactory.GetOnlyValue("select top 1 PeriodID from KS_CosPeriod Where CourseID=" + dr["courseid"].ToString() + "and  parentid=" + __info.Parentid + " and  orderid<" + dr["orderid"].ToString() + " order by orderid desc"));
                DataFactory.ExecuteNonQuery("update KS_CosPeriod set orderid=orderid+1 where parentid=" + __info.Parentid + " and  PeriodID=" + proid);

                DataFactory.ExecuteNonQuery("update KS_CosPeriod set orderid=orderid-1 where  parentid=" + __info.Parentid + " and PeriodID=" + __info.S_ClassID + " and orderid>" + minorderid + "");
                Kesion.Course.CoursePeriodCache.CreateCosJsonToCache(__info.courseid);  //生成课时JSON缓存
            }
        }
        Msg.Alert("恭喜，上移成功", KSCMS.GetComeUrl());
        return;
        #endregion
    }
    public void next()
    {
        #region 下移
        using (DataTable dt = DataFactory.GetDataTable("select top 1 CourseID,PeriodID,orderid from KS_CosPeriod 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_CosPeriod Where  parentid=" + __info.Parentid + " and CourseID=" + dr["courseid"].ToString()));
                int proid = Utils.StrToInt(DataFactory.GetOnlyValue("select top 1 PeriodID from KS_CosPeriod Where  parentid=" + __info.Parentid + " and CourseID=" + dr["courseid"].ToString() + "and  orderid>" + dr["orderid"].ToString() + " order by orderid asc"));
                DataFactory.ExecuteNonQuery("update KS_CosPeriod set orderid=orderid+1 where  parentid=" + __info.Parentid + " and orderid<" + maxorderid + " and  PeriodID=" + __info.S_ClassID);

                DataFactory.ExecuteNonQuery("update KS_CosPeriod set orderid=orderid-1 where  parentid=" + __info.Parentid + " and PeriodID=" + proid + " and orderid<>1");
                Kesion.Course.CoursePeriodCache.CreateCosJsonToCache(__info.courseid);  //生成课时JSON缓存
            }
        }
        Msg.Alert("恭喜，下移成功",KSCMS.GetComeUrl());
        return;
        #endregion
    }
    protected void SavePeriod()
    {
        infoInitial();
        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_CosPeriod] 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_CosPeriod");
                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("ban_seek", Utils.StrToInt(KSCMS.S("ban_seek")));
            ht.Add("ParentID", ParentID);

            if (A == "edit")
            {

            }
            else
            {
                int orderid = 0;
                if (ParentID == 0)
                {
                    orderid = Utils.StrToInt(DataFactory.GetOnlyValue("select max(orderid) from KS_CosPeriod where courseid=" + __info.courseid));//章级的orderid，直接排序
                }
                else
                {
                    orderid = Utils.StrToInt(DataFactory.GetOnlyValue("select max(orderid) from KS_CosPeriod where parentidpath like '%" + ParentID + ",%' and courseid=" + __info.courseid));//节级，存在没有orderid的情况
                    if (orderid == 0)
                    {
                        orderid = Utils.StrToInt(DataFactory.GetOnlyValue("select top 1 orderid from KS_CosPeriod 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_Cosperiod set orderid=orderid+1 where orderid>" + orderid + " and courseid=" + __info.courseid + "");
            }
            Kesion.Course.Course.DoCoursePeiodSave(ht);

            ht.Add("IsFree", Utils.StrToInt(__info.RadioButtonList1));
            if (Utils.StrToInt(__info.RadioButtonList1) == 0)
            {
                ht.Add("Isrepeat", __info.RadioButtonList3);
                ht.Add("jifen", Utils.StrToInt(__info.jifen));
            }
            else
            {
                ht.Add("jifen", 0);
                //课时收费
                float money = Utils.StrToFloat(__info.TextMoney, 0);
                if (money > 0)
                    ht.Add("money", money);
                else
                    ht.Add("money", 0);
            }

            ht.Add("UserName", UserManage.GetUserInfo().UserName);
            int classid = Utils.StrToInt(__info.S_ClassID, 0);
            int id = Utils.StrToInt(DataFactory.GetOnlyValue("select max(PeriodID) from KS_CosPeriod"));

            #region 指定试卷

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

                    SJIDs = KSCMS.S("LstB1");

                    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 (__user.GroupID == 4 && __user.SchoolID == 0)
                {
                    if (EnterPrise.GetTotal("yunvideo", 2))
                    {

                    }
                    else
                    {
                        Msg.Alert("对不起,你上传视频个数已经超过!", BasicField.GetUserUrl("teacher/courselist"));
                        isLoadPage = false;
                        return;
                    }

                }

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

                    if (ParentID != 0)
                    {

                        string bigparent = DataFactory.GetOnlyValue("select top 1 parentidpath from KS_Cosperiod where courseid=" + __info.courseid + " and periodid=" + ParentID + "");//获取父级的上级 合集路径
                        parentidpath = bigparent + "," + parentidpath;
                    }
                    DataFactory.ExecuteNonQuery("update KS_CosPeriod set parentidpath='" + parentidpath + "' where periodid=" + newPid);//更新路径合集
                    CheckAndFixClass(ParentID);
                    arstr = "success";
                }
                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_CosPeriod", ht, "where PeriodID=" + classid))
                {
                    erstr = "success";
                }
                else
                {
                    erstr = "failnmae";
                }
                if (erstr.Equals("success"))
                {
                    Kesion.Course.CoursePeriodCache.CreateCosJsonToCache(__info.courseid);  //生成课时JSON缓存
                    Msg.Alert("课时修改成功", BasicField.GetUserUrl("Teacher/Cszj", "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/Cszj", "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_Cosperiod where parentidpath like '%" + parentID + ",%' and courseid=" + __info.courseid + ""));

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

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

        #endregion
    }
    private void CountKS()
    {
        #region 统计课时数
        int CountPid = Utils.StrToInt(DataFactory.GetOnlyValue("select count(1) From KS_CosPeriod Where (addtype=1 or addtype is null) and  CourseID=" + __info.courseid));
        DataFactory.ExecuteNonQuery("UPDATE KS_Course Set CountPid=" + CountPid + " WHERE CourseId=" + __info.courseid);
        #endregion
    }
</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/cszj","do-add,addtype-1,courseid-"+__info.courseid+",parentid-0") %>" class="addbtn"><b></b>添加课时</a>
	<a href="<%=BasicField.GetUserUrl("teacher/courselist") %>" 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>
		 <%}
	 else{ %>
	
	 	<form name="aspnetForm" method="post" action="<%=BasicField.GetUserUrl("teacher/cszj","do-"+KSCMS.S("do"))%>" id="aspnetForm">
		<input type="hidden" name="action" value="save" />
	<div class="t_tybox">
	 <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="ctl00_KSContent_TxtName" 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" class="radiobtn" name="RadioButtonList2" value="0" <%=__info.RadioButtonList2=="0"?"checked":"" %> />
			无</td>

			<td><input id="RadioButtonList2_1" type="radio" name="RadioButtonList2" class="radiobtn" value="2"  <%=__info.RadioButtonList2=="2"?"checked":"" %> />
			指定试卷ID</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>
				<tr style="display: none">
					<td align="right" class="lefttd" height="30"><strong>考试状态规定：</strong></td>
					<td class="righttd">
						<input name="regulations" type="text" id="regulations" class="textbox" style="height:23px;width:40px;" />%
						<font color="red">学习达到总课时的多少比例时才能考试，留空或0为不限制</font>
					</td>
				</tr>
			 </tbody>
		   </tbody>
		   <script>
		   	$(document).ready(function () {
		   		if (parseInt(1) == 1) {
		   			jQuery("#Tbody5").css("display", "");
		   			jQuery("#zjclass").show();
		   		}
		   		jQuery("#tbody10").show();
		   		isType();
		   		SetListening1();
		   		judgejifen();
		   	});
		   	function judgejifen() {
		   	    var a = jQuery("#RadioButtonList1 :radio[checked]").val();
		   	    if (a == "0") {
		   	        jQuery("#tbody110").show();
		   	    }
		   	    else {
		   	        jQuery("#tbody110").hide();
		   	    }
 if ("<%=(courseIsFree==0||courseIsChargePeriod==1).ToString().ToLower()%>"=="true" || a== 0) {   //主程课免费或是不允许按课时购买时，不能显示价格录入框
                jQuery("#tbody3").hide();
            } else {
                jQuery("#tbody3").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="PeriodPlace"  runat="server"></asp:PlaceHolder> 
		   <tr>
			  <td align="right" class="lefttd" height="30" ><strong>收费状态：</strong></td>
			  <td class="tag_left">
				<table id="RadioButtonList1" border="0" onclick="judgejifen()">
		<tr>
			<td><input id="RadioButtonList1_0" type="radio" class="radiobtn" name="RadioButtonList1" <%=__info.RadioButtonList1=="1"?"checked":"" %> value="1" <%=courseIsFree==0?"disabled='disabled'":"" %>/>付费</td>
			<td><input id="RadioButtonList1_1" type="radio" class="radiobtn" name="RadioButtonList1"  <%=Utils.StrToInt(__info.RadioButtonList1)==0?"checked":"" %> value="0" />免费</td>
		</tr>
	</table>


			  </td>
		   </tr>  
           <tbody id="tbody110">
				   <tr>
            <td align="right" class="lefttd" height="30" >是否重复扣<%=MyCache.GetCacheConfig(90)  %>：</td>
            <td class="tag_left">
            	<table id="RadioButtonList3"  border="0">
		<tr>
			<td><input id="RadioButtonList3_0" type="radio" name="RadioButtonList3" value="0" <%=Utils.StrToInt(__info.RadioButtonList3)==0?"checked":""%> /><label for="RadioButtonList3_0">否</label></td>
			<td><input id="RadioButtonList3_1" type="radio" name="RadioButtonList3" value="1" <%=Utils.StrToInt(__info.RadioButtonList3)==1?"checked":""%> /><label for="RadioButtonList3_1">是</label></td>
		</tr>
	</table>
                </td>
        </tr>
		          <tr>
	   <td align="right" class="lefttd" height="30">
	   <strong><font color="red">*</font><%=MyCache.GetCacheConfig(90)  %>价格：</strong></td>
	   <td class="tag_left"> &nbsp;<input name="jifen" type="text" value="<%=__info.jifen %>" id="jifen" class="textbox" style="width:50px;" /><%=MyCache.GetCacheConfig(90)  %></td>
				 </tr>
				   </tbody>
				   <tbody id="tbody3" <%=((courseIsFree == 0||courseIsChargePeriod==1)?" style='display:none'":"") %>>
				    <tr>
	   <td align="right" class="lefttd" height="30">
                <strong><font color="red">*</font>单个课时价格：</strong>
	   </td>
            <td class="tag_left">
                &nbsp;<input name="TextMoney" type="text" value="<%=__info.TextMoney %>" id="TextMoney" class="textbox" style="width:50px;" />元<span style="margin-left:10px" class="tips">设置为“0”表示不按课时收费</span></td>
				
				 </tr>
				 </tbody>
	   </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('#ctl00_KSContent_TxtName').val() == '') {
		 	        KesionJS.Alert('请输入标题名称！', "jQuery('#ctl00_KSContent_TxtName').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/CsAddZj","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/CsAddZj","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/CsZj","do-pro")%>";
	    	    url += ",parentid-" + parentid + ",courseid-" + <%=__info.courseid%> + ",Periodid-" + id + ",costype-" + <%=KSCMS.S("costype")%> + "";
                location.href = url;

	    	
	    	}
	    	function next(id, parentid) {
	    		var url = "<%=BasicField.GetUserUrl("teacher/CsZj","do-next")%>";
	    	    url += ",parentid-" + parentid + ",courseid-" + <%=__info.courseid%> + ",Periodid-" + id + ",costype-" + <%=KSCMS.S("costype")%> + "";
	    		location.href = url;
	    	}
   </script>
      <script>
        		function SetDownUrlByUpLoad(v, s) {
        			jQuery("#TxtUrl").val(v);
        		}      
                function isType(){
            //var $this = $(t);
            var a = $('input[name="radiotype"]:checked').val();
            jQuery("#x_time").hide();

            if (a=='2'){	
                //图文  
                jQuery("#Tbody13").show();
                jQuery("#Tbody14").hide();
                jQuery("#Tbody12").hide();
                jQuery("#Tbody11").hide();
                jQuery("#threencscreen").hide();
                jQuery("#UploadThreen").hide();
                jQuery("#UploadThreen1").hide();
                jQuery("#SetListening").hide();
            }else if (a=='0') {
                //视频
            
                jQuery("#Tbody11").show();
                jQuery("#Tbody14").hide();
                jQuery("#Tbody12").hide();	
                jQuery("#Tbody13").hide();
                jQuery("#x_time").show();
                jQuery("#threencscreen").show();
                jQuery("#UploadThreen").show();
                jQuery("#UploadThreen1").show();
                jQuery("#SetListening").show();
                checked();
            }else if(a=='3'){       	
                jQuery("#Tbody13").hide();
                jQuery("#Tbody14").hide();
                jQuery("#Tbody12").show();	
                jQuery("#Tbody11").hide();
                jQuery("#othervideo").hide();
                jQuery("#threencscreen").hide();
                jQuery("#UploadThreen").hide();
                jQuery("#UploadThreen1").hide();
                jQuery("#SetListening").hide();
                
                 jQuery("#Textppt1").val('');
            
            } else if (a == '1') {
                    jQuery("#Tbody13").hide();
                    jQuery("#Tbody14").show();
                    jQuery("#Tbody12").hide();
                    jQuery("#Tbody11").hide();
                    jQuery("#othervideo").hide();
                    jQuery("#threencscreen").hide();
                    jQuery("#UploadThreen").hide();
                    jQuery("#UploadThreen1").hide();
                    jQuery("#SetListening").hide();

                }}

                             
 		
      </script>	