var _Type = "";

$(document).ready(function () {
    _Type = CmsData.Common.QueryString("type");
    
    if (document.getElementById("DataList")) 
        CmsData.DataList();
    else
        CmsData.DataEdit("", 3);
});

var CmsData = {
    DataList: function () {
        $.ajax({
            type: "get",
            dataType: "html",
            url: "dataajax.aspx?stype=sum&type=" + _Type + CmsData.SqlSearch() + "&r=" + Math.random(),
            async: false,
            beforeSend: function (XMLHttpRequest) { },
            success: function (data) {
                CmsData.Pager.recordCount = Number(data);
            },
            error: function () { alert("sum ajax error..."); }
        });
                
        var ajaxurl = "datahtml.aspx?path=list&type=" + _Type;
        ajaxurl += CmsData.SqlSearch();
        ajaxurl += "&sortfield=";
        ajaxurl += "&sortorderby=";
        ajaxurl += "&page=" + CmsData.Pager.pageIndex;
        ajaxurl += "&pagesize=" + CmsData.Pager.pageSize;
        ajaxurl += "&pagesum=" + CmsData.Pager.recordCount;
        ajaxurl += "&r=" + Math.random();
        
        $.ajax({
            type: "get",
            dataType: "html",
            url: ajaxurl,
            async: false,
            beforeSend: function (XMLHttpRequest) {
                CmsData.Common.MsgState();
            },
            success: function (data) {
                $("#DataList").html(data);

                if (CmsData.Pager.recordCount == 0)
                    CmsData.Pager.recordCount = $("#DataList tbody tr").length;

                $("#DataPager").html(CmsData.Pager.Render());

                $("#DataList table tbody tr:even").addClass("treven"); //隔行换色
                $("#DataList table tbody tr:odd").addClass("trodd");   //隔行换色

                $("#DataList table tbody tr").mouseover(function () {  //鼠标移动加样式
                    $(this).addClass("trmouse");
                }).mouseout(function () {
                    $(this).removeClass("trmouse");
                });

                if (CmsData.Selects != undefined)
                    CmsData.Selects.Init(); //多文件选择框初始化赋值

                CmsData.Common.MsgState();
            },
            error: function () {
                alert("list ajax error...");
                CmsData.Common.MsgState();
            }
        });
    },
    DataEdit: function (type, id) {
        if (type == "") type = _Type;
        $.ajax({
            type: "get",
            dataType: "html",
            url: "datahtml.aspx?path=edit&type=" + type + "&id=" + id + CmsData.SqlSearch() + "&r=" + Math.random(),
            beforeSend: function (XMLHttpRequest) { CmsData.Common.MsgState(); },
            success: function (data) {
                var dataaduhtml = "<div id=\"DataAdu\" ></div>";

                if (document.getElementById("DataList")) {
                    CmsData.Common.TransCreate("编辑窗口", "DataAdu", "", 1, dataaduhtml);
                    CmsData.Common.TransToggle("DataAdu");
                } else
                    $(dataaduhtml).appendTo($("#myformadu"));
                $("#DataAdu").html(data);

                //标签控制 无列的隐藏
                $("#DataAdu>table>tbody").each(function (i) {
                    var isNone = true;
                    $(this).find("tr").each(function () {
                        if ($(this).find("th").length == 0) {
                            if ($(this).css("display") != "none")
                                isNone = false;
                        }
                    });
                    
                    if (isNone == true) {
                        $("#DataAdu>table>thead a:eq(" + i + ")").hide();
                        $(this).prev().hide();
                    }
                });

                //标签切换
                $("#DataAdu thead td a:eq(0)").addClass("on");
                $("#DataAdu>table>tbody:eq(0)").show();
                $("#DataAdu thead td a").each(function (i) {
                    $(this).click(function () {
                        $("#DataAdu thead td a").removeClass("on");
                        $(this).addClass("on");
                        $("#DataAdu>table>tbody").hide();
                        $("#DataAdu>table>tbody:eq(" + i + ")").show();
                    });
                });

                //图片初始加载
                if (CmsData.UpFiles != undefined)
                    CmsData.UpFiles.Init();

                //自定义插件初始事件
                if (typeof (PlugInit) == "function")
                    PlugInit(type);
                CmsData.Common.MsgState();
            },
            error: function () { alert("edit ajax error..."); CmsData.Common.MsgState(); }
        });
    },
    DataSubmit: function (type) {   //编辑界面数据提交
        if (type == "") type = _Type;

        $(".myEditor").each(function () {
            $(this).val(UE.getEditor("myEditor" + $(this).attr("id")).getContent());
        });
        $.ajax({
            type: "post",
            dataType: "html",
            data: $('#myformadu').serialize(),
            url: "datasubmit.aspx?type=" + type + "&r=" + Math.random(),
            beforeSend: function (XMLHttpRequest) {
                CmsData.Common.MsgState();
                CmsData.Common.BtnDisabled(true);
            },
            success: function (data) {
                if (CmsData.Common.MsgResult(data)) {
                    CmsData.Common.TransToggle("DataAdu");
                    if (document.getElementById("DataList"))
                        CmsData.DataList();
                }
                CmsData.Common.BtnDisabled(false);
            },
            error: function () {
                alert("submit ajax error...");
                CmsData.Common.MsgState();
                CmsData.Common.BtnDisabled(false);
            }
        });

        return false;
    },
    DataTools: function () { //选中数据操作提交
        var stype = $("#SelectTools").val();
        if (stype != "") {
            var ids = CmsData.CheckboxIds();
            if (ids == "") {
                alert("请选择需要操作的数据");
            } else {
                switch (stype) {
                    case "delete":
                        if (confirm("确定对选中数据执行删除操作？此操作不可恢复"))
                            CmsData.DataAjax(ids, stype, "");
                        break;
                    case "sort":
                        CmsData.DataAjax(ids, stype, "&sorts=" + CmsData.CheckboxSorts(stype));
                        break;
                    case "show":
                        CmsData.DataAjax(ids, stype, "");
                        break;
                    case "hide":
                        CmsData.DataAjax(ids, stype, "");
                        break;
                    default:
                        break;
                }

            }
        }
    },
    DataDelete: function (ids) {   //单行数据删除
        if (confirm("确定删除当前行数据吗，此操作不可恢复？"))
            CmsData.DataAjax(ids, "delete", "");
    },
    DataCopy: function (id) {
        if (confirm("确定复制当前行数据吗？"))
            CmsData.DataAjax(id, "copy", "");
    },
    DataAjax: function (ids, stype, parm) {  //数据执行操作
        $.ajax({
            type: "get",
            dataType: "html",
            url: "dataajax.aspx?type=" + _Type + "&stype=" + stype + "&ids=" + ids
                + parm + CmsData.SqlSearch() + "&r=" + Math.random(),
            beforeSend: function (XMLHttpRequest) { CmsData.Common.MsgState(); },
            success: function (data) {
                if (CmsData.Common.MsgResult(data)) {
                    CmsData.DataList();
                }
                CmsData.CheckboxAll(false);
            },
            error: function () { alert("ajax error..."); CmsData.Common.MsgState(); }
        });
    },
    SqlSearch: function () {
        var str = "";

        if (Number(CmsData.Common.QueryString("menuid")) > 0)
            str += "&menuid=" + CmsData.Common.QueryString("menuid");
        else if (Number($("#SearchMenuID").val()) > 0)
            str += "&menuid=" + $("#SearchMenuID").val();

        if (document.getElementById("SearchHot"))
            str += "&hot=" + $("#SearchHot").val();

        if (document.getElementById("SearchCategoryID"))
            str += "&categoryid=" + $("#SearchCategoryID").val();

        if (CmsData.Common.QueryString("key") != "")
            str += "&key=" + escape(CmsData.Common.QueryString("key"));
        else if (document.getElementById("SearchKey"))
            str += "&key=" + escape($("#SearchKey").val());

        /*
        if (document.getElementById("cname"))
            str += "&cname=" + escape($("#cname").val());
    
        if (document.getElementById("SearchAttribute"))
            str += "&attribute=" + escape($("#SearchAttribute").val());
        */
        return str;
    },
    CheckboxAll: function (val) {     //全选框事件
        $("#checkboxall").attr("checked", val);
        $("#DataList table tbody tr").each(function (i) {
            $(this).find("input[name=CKRow]").attr("checked", val);

            if (val == true)
                $(this).addClass("trselect");
            else
                $(this).removeClass("trselect");

            if (CmsData.Selects != undefined)
                CmsData.Selects.Checked($(this).find("input[name=CKRow]").get(0));
        });
    },
    CheckboxRow: function (obj) {  //当前行选中
        $(obj).parent().parent().parent().toggleClass("trselect");

        if (CmsData.Selects != undefined)
            CmsData.Selects.Checked(obj);
    },
    CheckboxIds: function () {    //获取选中ID        
        var ids = "";
        $("input[name=CKRow]:checked").each(function () {
            ids += this.value + ",";
        });
        return CmsData.Common.ClearLastChar(ids);
    },
    CheckboxSorts: function () {  //获取选中项的排序值
        var sorts = "";
        $("input[name=CKRow]:checked").each(function () {
            sorts += $(this).parent().parent().parent().find("input[name=CKSort]").val() + ",";
        });
        return CmsData.Common.ClearLastChar(sorts);
    }
};

/*
    公用方法
*/
CmsData.Common = {
    MsgState: function () { //提示状态：正在提交  
        $("#MsgState").html("正在提交请求...").toggle();
    },
    MsgResult: function (data) { //提示状态：提交结果判断
        CmsData.Common.MsgState();
        if (data != "") {
            var result = eval("(" + data + ")");
            if (data != "" && result != null) {
                if (result.result == "success") {
                    $("#MsgSuccess").html(result.msg == "" ? "提交成功..." : result.msg).show().fadeOut(3000);
                    return true;
                } else {
                    $("#MsgError").html(result.msg == "" ? "提交失败..." : result.msg).show().fadeOut(3000);
                }
            } else { $("#MsgError").html("未返回处理结果").fadeOut(3000); }
        } else { $("#MsgError").html("未返回处理结果").fadeOut(3000); }

        return false;
    },
    BtnDisabled: function (bit) { //禁用或启用页面按钮
        if (bit)
            $(".btn").attr("disabled", "disabled");
        else
            $(".btn").removeAttr("disabled");
    },
    StrToJson: function (str) { //转json对象
        return eval("(" + str + ")");
    },
    QueryString: function (name) { //获取url请求地址
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return "";
    },
    ClearLastChar: function (str) {    //清除最后一个字符
        if (str != "")
            str = str.substring(0, str.length - 1);
        return str;
    },
    IndexOf: function (str, val) {  //查找字符串
        return (("," + str + ",").indexOf("," + val + ",") > -1)
    },
    RemoveAt: function (str, val) { //移除指定值元素
        if (str != "") {
            var strList = str.split(",");
            str = "";
            $.each(strList, function (n, value) {
                if (value != "" && value != val)
                    str += value + ",";
            });
        }
        return str;
    },
    InsertAt: function (id, textFeildValue) {  //在光标位置插入文本 IE不兼容 有空要改
        var textObj = document.getElementById(id);
        if (document.all) {
            if (textObj.createTextRange && textObj.caretPos) {
                var caretPos = textObj.caretPos;
                caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == '     ' ? textFeildValue + '     ' : textFeildValue;
            } else {
                textObj.value = textFeildValue;
            }
        } else {
            if (textObj.setSelectionRange) {
                var rangeStart = textObj.selectionStart;
                var rangeEnd = textObj.selectionEnd;
                var tempStr1 = textObj.value.substring(0, rangeStart);
                var tempStr2 = textObj.value.substring(rangeEnd);
                textObj.value = tempStr1 + textFeildValue + tempStr2;
            } else {

            }
        }
    },
    TransIsExists: function (id) {  //透明遮挡层是否创建
        return document.getElementById("Trans" + id) == null ? false : true;
    },
    TransCreate: function (title, id, style, zindex, html) {   //创建半透明遮挡层与DIV对象
        if (CmsData.Common.TransIsExists(id) == false) {
            $("<div id='TransBg" + id + "' class='transBg zindex" + zindex + "' ></div>").appendTo($("#myformadu"));
            $("<div id='TransDiv" + id + "' class='transDiv zindex" + zindex + "1' style='" + style + "' ></div>").appendTo($("#myformadu"));
            $("<div class='transHead' ><h4>" + title + "</h4><a href=\"javascript:CmsData.Common.TransToggle('" + id + "');\" class=\"transClose zindex" + zindex + "1\" ></a></div>").appendTo("#TransDiv" + id);
            $("<div id='Trans" + id + "'></div>").appendTo("#TransDiv" + id);
            $("#Trans" + id).html(html);
        }
    },
    TransToggle: function (id) {     //显示或隐藏编辑框
        $("#TransBg" + id).toggle();
        $("#TransDiv" + id).toggle();
        return false;
    }
};