//生成URL查询参数
function BuildUrlQuery(url, key, value) {
    var _key = key.toLowerCase();
    var params = url.split("&");
    if (params.length == 0)
        return _key + "=" + value;

    var found = false;
    for (i = 0; i < params.length; i++) {
        if (params[i].split("=")[0].toLowerCase() == _key) {
            params[i] = _key + "=" + value;
            found = true;
            break;
        }
    }
    if (found)
        return params.join("&");
    else
        return url + "&" + _key + "=" + value;
}

//生成查询URL，并加载
function BuildQuery(Submit) {
    var form = document.forms[0];
    var query = location.search;
    if (query != "")
        query = query.substring(1);
    for (var i = 0; i < form.length; i++) {
        var element = form[i];
        var element_value = "";
        if (element.name == null || element.name == undefined) continue;
        if (element.getAttribute("type") == "button" || element.getAttribute("type") == "submit")
            continue;
        if (element.name.indexOf("chkHead") >= 0 || element.name.indexOf("chkItem") >= 0
            || element.name.indexOf("__") == 0 || element.name.indexOf("pager_input") == 0)
            continue;

        element_value = element.value;
        if (element.getAttribute("type") == "checkbox" || element.getAttribute("type") == "radio") {
            if (element.checked == false) element_value = "";
        }
        query = BuildUrlQuery(query, element.name, element_value);
    }
    query = BuildUrlQuery(query, "page", "1");
    query = BuildUrlQuery(query, "submit", Submit);

    var url = encodeURI(location.pathname + "?" + query);

    location.href = url;
    return false;
}

/*
列表中的单击操作处理，处理删除、审批等操作     
元素:<元素标签 url="执行AJAX操作的页面地址,不存在或为空则是当前页面" json="id:'1',op:'cs执行方法名'">
CallbackFun==null&data=error:'操作结果(ok/-1)[ok刷新当前页面]',msg:'错误提示'
*/
function opAjax(obj, CallbackFun) {
    if ($(obj).attr("json").length == 0) {
        return false;
    }
    var url = $(obj).attr("url");
    if (url == null || url == "") url = window.location.pathname;
    var get_data = eval("({" + $(obj).attr("json") + ",radom:" + Math.random() + "})");
    $.get(
        url,
        get_data,
        function (data) {
            if (CallbackFun != null) {
                CallbackFun(data, CallbackFun);
            }
            else {
                data = eval("(" + data + ")");
                if (data.error == "ok") {
                    if (data.msg != null && data.msg != "")
                        alert(data.msg);
                    window.location.href = window.location.href;
                } else {
                    alert(data.msg);
                }
            }
        }
    );
    return false;
}

/*
列表页的批量操作处理     
元素:<元素标签 url="执行AJAX操作的页面地址,不存在或为空则是当前页面" json="op:'cs执行方法名'">
CallbackFun==null&data=error:'操作结果(ok/-1)[ok刷新当前页面]',msg:'错误提示'
*/
function BatchOpAjax(obj, CallbackFun) {
    if ($(obj).attr("json").length == 0) {
        return false;
    }
    var ids = GetCheckedValues();
    if (ids == null || ids.length == 0) {
        alert("请选择要操作的数据");
        return false;
    }
    var url = $(obj).attr("url");
    if (url == null || url == "") url = window.location.pathname;
    var get_data = eval("({" + $(obj).attr("json") + ",ids:'" + GetCheckedValues() + "',radom:" + Math.random() + "})");
    if (get_data.op.indexOf("Delete") != -1 && !confirm("确定要删除选中数据?")) {
        return false;
    }
    $.get(
        url,
        get_data,
        function (data, textStatus) {
            if (CallbackFun != null) {
                CallbackFun(data, CallbackFun);
            }
            else {

                data = eval("(" + data + ")");
                if (data.error == "ok") {
                    alert(data.msg);
                    window.location.href = window.location.href;
                } else {
                    alert(data.msg);
                }
            }
        }
    );
    return false;
}
/*
获取列表中选中的数据ID集合
控件格式：<input id="chkItem" type="checkbox" value="<%#Eval("Id") %>" />
返回结果:id1,id2,id3
*/
function GetCheckedValues() {
    var chk = $(document.body).find('input[id="chkItem"]:checked');
    var chk_value = [];
    $.each(chk, function (i, o) {
        chk_value.push($(o).val());
    });
    return chk_value.join(",");
}
/*扩展提交,外部调用 按钮必须是Id=btnSave,form表单ID=aspnetForm*/
function FormPostAjax(url, successKey, CallbackFun) {
    return FormPostAjax(url, successKey, CallbackFun, null);
}
/*扩展提交,外部调用 按钮必须是Id=btnSave,form表单ID=aspnetForm*/
function FormPostAjax(url, successKey, CallbackFun, CallbackFailFun) {
    $("#btnSave").attr("disabled", "true");
    $("#aspnetForm").ajaxSubmit({
        url: url,
        success: function (result) {
            if (result == "ok") {
                alert("保存成功");
                if (CallbackFun != null)
                    CallbackFun();
            } else if(result.indexOf("ok:") > -1) {
                alert(result.replace("ok:",""));
                if (CallbackFun != null)
                    CallbackFun();
            } else {
                if (CallbackFailFun != null)
                    CallbackFailFun();
                alert(result);
            }
            $("#btnSave").removeAttr("disabled");
        }
    });
    return false;
}

jQuery.extend({
    handleError: function (s, xhr, status, e) {
        // If a local callback was specified, fire it
        if (s.error) s.error(xhr, status, e);

        // Fire the global callback
        if (s.global)
            jQuery.event.trigger("ajaxError", [xhr, s, e]);
    },
    httpData: function (xhr, type, s) {
        var ct = xhr.getResponseHeader("content-type"),
			xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
			data = xml ? xhr.responseXML : xhr.responseText;

        if (xml && data.documentElement.tagName == "parsererror")
            throw "parsererror";

        // Allow a pre-filtering function to sanitize the response
        // s != null is checked to keep backwards compatibility
        if (s && s.dataFilter)
            data = s.dataFilter(data, type);

        // The filter can actually parse the response
        if (typeof data === "string") {

            // If the type is "script", eval it in global context
            if (type == "script")
                jQuery.globalEval(data);

            // Get the JavaScript object, if JSON is used.
            if (type == "json")
                data = window["eval"]("(" + data + ")");
        }

        return data;
    }
})