﻿/******************************************************************************
* filename: Common.js
* Ajax Modul Scripting
* (C) MasterLi(masterljf#hotmail.com),Oran Day(likecode#qq.com)
* (C) NSW(http://www.nsw.com)
*******************************************************************************/
/********************
* 初始化头部信息，如购物车产品总数，登录状态等
* 回应 : XML对象
********************/
function initCommonHeader() {
    $.get("/ajax.ashx?action=initcommonheader&t=" + Math.random(), function(rsp) {
        $j("headerCartCount").html(gav(rsp, "prod_count"));
        var username = gav(rsp, "username");
        if (username.length > 0) {
            $j("commonHeaderGuest").hide();
            $j("commonHeaderUsername").html("[<a href='/user/index.aspx'>" + username + "</a>][<a href='/user/login.aspx?action=logout'>退出</a>]");
            $j("divSignIn").hide();
            $j("divLogin").show();
            $j("commonHeaderUser").fadeIn(80);
        }
        else {
            $j("commonHeaderUsername").html("<span class='b corange'>游客</span>");
        }
    });
}
/********************
* 添加产品到购物车
* src : 触发事件的源对象
* _pid : 产品ID
* qutiElmId : 数量（重载：number购买数量、string数量的文本框元素ID）
* reloadCartPage : (可选)是否询问重新刷新购物车首页
* redirectUrl : (可选)当产品添加成功后，跳转到的页面（优先权高）
* 回应 : XML对象
********************/
function addToCart(src, _pid, qutiElmId, reloadCartPage, redirectUrl) {
    showProc(src);
    if (reloadCartPage == null) {
        reloadCartPage = false;
    }
    var _quti;
    if (qutiElmId == null) {
        _quti = 1;
    } else if (typeof (qutiElmId) == "number") {
        _quti = qutiElmId;
    } else {
        _quti = $tv(qutiElmId);
    }
    $.post("/ajax.ashx?action=addtocart&t=" + Math.random(), {
        pid: _pid,
        quti: _quti
    }, function(msg) {
        var sMsg = gav(msg, "msg");
        var sCount = gav(msg, "count");
        if (redirectUrl != null) {
            location.href = redirectUrl;
            return;
        }
        $confirm(sMsg, { title: "去结算", toDo: "/paycenter/cart.aspx" }, { title: "再选购", toDo: function() {
            hideConfirm();
        }
        });
        $j("headerCartCount").html(sCount);
        if (reloadCartPage && (gav(msg, "state") == 1) && confirm("添加到购物车成功，是否马上刷新页面购物车页面？\r\n\r\n是 - 刷新本页面查看最新结果\r\n否 - 保留当前页面状态")) {
            location.href = "cart.aspx?t=" + Math.random();
            return;
        }
        showProc(src, false);
    });
}
/********************
* 清空购物车
* src : 触发事件的源对象
* 回应 : string
*       1 - 成功
*       0 - 失败
********************/
function emptyCart(src) {
    showBgProc();
    $.get("/ajax.ashx?action=emptycart&t=" + Math.random(), function(msg) {
        if (msg == "1") {
            $a("清空购物车成功，单击确认返回产品中心。", 1, false, null, "消息", function() {
                location.href = "/product";
            });
        } else {
            $a("清空购物车失败，请稍候重试。");
        }
        showBgProc(false);
    });
}
/********************
* 清空购物车
* src : 触发事件的源对象
* _pid : 产品ID
* 回应 : xml
********************/
function changeQuantity(src, _pid) {
    var newVal = $(src).parent().find("input").attr("value");
    if (!/^\d+$/.test(newVal)) {
        $a("数量必须是一个整数。");
        return;
    }
    if (parseInt(newVal) == 0) {
        $a("数量必须大于0，若要删商品，请点操作中的‘删除’。");
        return;
    }
    showBgProc();
    $.post("/ajax.ashx?action=addtocart&t=" + Math.random(), {
        pid: _pid,
        quti: newVal
    }, function(msg) {
        if (gav(msg, "state") == "1") {
            if (confirm("数量修改成功，是否马上刷新页面查看购物车结果？\n\n是 - 刷新页面查看结果\n否 - 保留当前页面状态")) {
                location.href = "cart.aspx?t=" + Math.random();
            } else {
                showBgProc(false);
                $(src).hide();
            }
        } else {
            $a(msg);
            showBgProc(false);
        }
    });
}
function delCartProduct(src, _pid) {
    showBgProc();
    var _quti = 0;
    $.post("/ajax.ashx?action=addtocart&t=" + Math.random(), {
        pid: _pid,
        quti: _quti
    }, function(msg) {
        if (gav(msg, "state") == "1") {
            if (confirm("商品已删除，是否马上刷新页面查看结果？\n\n\r\n是 - 刷新页面查看结果\n否 - 保留当前页面状态")) {
                location.href = "cart.aspx?t=" + Math.random();
            }
        } else {
            $a(gav(msg, "msg"));
        }
        showBgProc(false);
    });
}
function cancelOrder(src, _orderNo) {
    showBgProc();
    $.post("/ajax.ashx?action=cancelorder&t=" + Math.random(), {
        no: _orderNo
    }, function(msg) {
        if (gav(msg, "state") == "1") {
            $(src).parent().parent().parent().find("td[name=orderstate]").html("已取消");
            $(src).hide();
        } else {
            $a("<p>取消订单操作失败。</p><p>非‘待审核’状态、已锁定等订单不可取消。</p>");
        }
        showBgProc(false);
    });
}
function delFavColumn(src, _oid) {
    showBgProc();
    $.post("/ajax.ashx?action=delfavfolumn&t=" + Math.random(), {
        oid: _oid
    }, function(msg) {
        if (gav(msg, "state") == "1") {
            $(src).parent().parent().fadeOut(80).remove();
        } else {
            $a("操作失败，请稍候重试。");
        }
        showBgProc(false);
    });
}
function addFav(src, _title, _url) {
    if (_url == null) {
        _url = location.pathname;
    }
    if (_title == null) {
        _title = document.title;
    }
    showBgProc();
    $.post("/ajax.ashx?action=fav&t=" + Math.random(), {
        url: _url,
        ptitle: _title
    }, function(msg) {
        $a(gav(msg, "msg"), 1)
        showBgProc(false);
    });
}
function delFav(src, itemTabId) {
    var _ids = getCheckedVal(itemTabId);
    if (_ids.length == 0) {
        $a("无选中项。");
        return;
    }
    showBgProc();
    $.post("/ajax.ashx?action=delfav&t=" + Math.random(), {
        ids: _ids
    }, function(msg) {
        if (gav(msg, "state") == "1") {
            var chks = $j(itemTabId).find("input[name=item]:checked");
            chks.each(function(i) {
                $(this).parent().parent().remove();
            });
        } else {
            $a(gav(msg, "msg"));
        }
        showBgProc(false);
    });
}
function hits(_oid, _mark) {
    $.post("/ajax.ashx?action=hits&t=" + Math.random(), {
        oid: _oid,
        mark: _mark
    })
}
function postComment(src, _oid, _mark) {
    showProc(src);
    var _content = $tv("txtCmtContent");
    var _verCode = $tv("txtCmtVerCode");
    if (_content == "") {
        $a("内容必填。");
        showProc(src, false);
        return;
    }
    if ($g("txtVerCode") != null && s_verCode == "") {
        $a("验证码不可空。");
        showProc(src, false);
        return;
    }
    $.post("/ajax.ashx?action=postcomment&t=" + Math.random(), {
        content: _content,
        oid: _oid,
        verCode: _verCode,
        mark: _mark
    }, function(msg) {
        var sta = gav(msg, "state");
        var sMsg = gav(msg, "msg");
        if (sta == "") {
            $a(msg,-1);
        } else if (sta == "2") {
            $a(sMsg,1);
            emptyText('tbCmt');
        } else if (sta == "1") {
            var sTime = gav(msg, "time");
            var sUsername = gav(msg, "username");
            var sIp = gav(msg, "ip");
            var sComment = gav(msg, "comment");

            var htmlFmt = "<dl>"
						+ "<dd>{$username$}<span class='ip'>IP：{$ip$}</span>时间：{$time$}</dd>"
						+ "<dd class='c666 con mt8'>{$content$}</dd>"
					+ "</dl>";
            var sHtml = htmlFmt
                .replace("{$username$}", sUsername)
                .replace("{$ip$}", sIp)
                .replace("{$time$}", sTime)
                .replace("{$content$}", sComment);
            $j("divComments").html(sHtml + $j("divComments").html());
            $a(sMsg,1);
            emptyText('tbCmt')

        } else {
            $a(sMsg);
        }
        showProc(src, false);
    });
}
function writeComment(_oid, _mark) {
    $.post("/ajax.ashx?action=getcomment&t=" + Math.random(), {
        oid: _oid,
        mark: _mark
    }, function(msg) {
        var iCount = $(msg).find("count").text();
        $j("spCommentCount").html(iCount);
        var commtns = $(msg).find("comment");
        var sHtml = "";
        var htmlFmt = "<dl>"
						+ "<dd>{$username$}<span class='ip'>IP：{$ip$}</span>时间：{$time$}</dd>"
						+ "<dd class='c666 con mt8'>{$content$}</dd>"
					+ "</dl>";
        for (var i = 0; i < commtns.length; ++i) {
            var jCmt = $(commtns[i]);
            var sUsername = jCmt.find("username").text();
            var sContent = jCmt.find("content").text();
            var sIp = jCmt.find("ip").text();
            var sTime = jCmt.find("inputTime").text();
            sHtml += htmlFmt
                .replace("{$username$}", sUsername)
                .replace("{$ip$}", sIp)
                .replace("{$time$}", sTime)
                .replace("{$content$}", sContent);
        }
        if (sHtml.length > 0) {
            $j("divComments").html(sHtml);
        } else {
            $j("divComments").html("暂无评论");
        }
    });
}
function addHistory(_oid, _mark) {
    $.get("/ajax.ashx?action=addhistory&t=" + Math.random(), {
        oid: _oid,
        mark: _mark
    })
}
function getAd(_keyname, cntrElmId) {
    $.post("/ajax.ashx?action=getadd", {
        keyname: _keyname
    }, function(msg) {
        $j(cntrElmId).html(msg);
    })
}
function getVideo(_videoKey) {
    $.post("/ajax.ashx?action=getvideo", {
        videoKey: _videoKey
    }, function(msg) {
        var jDiv = $j("divVideo");
        if (msg.length == 0) {
            jDiv.slideUp(80);
        } else {
            jDiv.html(msg);
            $(".prod_attrs").toggleClass("prod_attrs").toggleClass("prod_attrs_b");
        }
    })
}
function getOrderAnns() {
    $.get("/ajax.ashx?action=getorderanns", function(msg) {
        $j("divOrderAnns").html(msg);
    });
}
function getEndingRemark() {
    $.get("/ajax.ashx?action=getendingremark", function(msg) {
        $j("divEndingRemark").html(msg);
    });
}
function getHistory(_mark) {
    $.post("/ajax.ashx?action=gethistory&t=" + Math.random(), {
        mark: _mark
    }, function(msg) {
        if (msg.length == 0) {
            msg = "<li>无浏览历史</li>";
        }
        $j("divHistoryCntr").html(msg);
    });
}
function getHits(_oid, _mark) {
    $.post("/ajax.ashx?action=gethits", {
        mark: _mark,
        oid: _oid
    }, function(msg) {
        $j("cntrHits").html(msg);
    });
}
function getHelpStatic(_oid) {
    $.post("/ajax.ashx?action=helpsatisfaction&t=" + Math.random(), {
        oid: _oid
    }, function(msg) {
        var arrI = [parseInt(gav(msg, "1")), parseInt(gav(msg, "2")), parseInt(gav(msg, "3"))];
        var total = arrI[0] + arrI[1] + arrI[2];
        if (total == 0) {
            total = 1;
        }
        var maxHeight = 100;
        for (var i = 0; i < arrI.length; ++i) {
            var percent = (arrI[i] / total).toFixed(2);
            var h = maxHeight * percent;
            if (h == 0) {
                h = 1;
            }
            var sHtml = "<td><div class='static_graph' style='height:" + h + "px;'></div><div class='static_w'>"
                    + (percent * 100).toFixed(2) + "%</div></td>";
            $j("cntrStatic_" + i).html(sHtml);
        }
    });
}
function submitHelpUse(src, _oid) {
    showProc(src);
    var _notice = $("input[name=use]:checked").val();
    $.post("/ajax.ashx?action=helpuseful&t=" + Math.random(), {
        oid: _oid,
        notion: _notice
    }, function(msg) {
        if (gav(msg, "state") == "0") {
            $a(gav(msg, "msg"));
        } else {
            $a(gav(msg, "msg"), 1);
            getHelpStatic(_oid);
        }
        showProc(src, false);
    });
}
function getSimilarArticle(_sid) {
    $.post("/ajax.ashx?action=getsmilararticle&t=" + Math.random(), {
        sid: _sid
    }, function(msg) {
        $j("cntrSimilarArticle").html(msg);
    });
}
function getLastArticle() {
    $.post("/ajax.ashx?action=getlastarticle", function(msg) {
        $j("cntrLastArticle").html(msg);
    });
}
function cleanHistory(_mark, key) {
    $.post("/ajax.ashx?action=cleanhistory", {
        mark: _mark
    }, function(msg) {
        $j("divHistoryCntr").html("<li>无浏览历史</li>");
    });
}
function subscription(src, elmId) {
    if (elmId == null) {
        elmId = "txtSubscriptionEmail";
    }
    var _email = $.trim($j(elmId).val());
    var ptn = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
    if (_email.length == 0) {
        $a("E-Mail 不可为空");
        $j(elmId).focus();
        return false;
    }
    if (!ptn.test(_email)) {
        $a("E-Mail 格式错误。");
        $j(elmId).focus();
        return false;
    }
    showProc(src);
    $.post("/ajax.ashx?action=subscription&t=" + Math.random(), {
        email: _email
    }, function(msg) {
        var sta = gav(msg, "state");
        var sMsg = gav(msg, "msg");
        if (sta == "1") {
            $a(sMsg, 1);
        } else {
            $a(sMsg);
        }
        showProc(src, false);
    });
}
function userFeedback(src) {
    var _title = $tv("txtFdTitle");
    var _shortDesc = $tv("txtFdShortDesc");
    if (_title.length == 0 || _shortDesc.length == 0) {
        $a("内容或标题不可为空。")
        return false;
    }

    showBgProc(true, "正在提交...");
    $.post("/ajax.ashx?action=userfeedback&t=" + Math.random(), {
        title: _title,
        shortDesc: _shortDesc
    }, function(msg) {
        var sta = gav(msg, "state");
        var sMsg = gav(msg, "msg");
        if (sta == "1") {
            showMsgPage("<li>您的意见提交成功，感谢您的意见，有您的支持，我们会做得更好。</li>", 1, "/user/faq.aspx", "意见/反馈", "/user/faq.aspx");
            return;
        } else if (sMsg.length > 0) {
            $a(sMsg);
        } else {
            $a(msg);
        }
        showBgProc(false);
    });
}
function checkAuthority(_authIDs, _title) {
    $.post("/ajax.ashx?action=checkauthority&t=" + Math.random(), {
        authIDs: _authIDs
    }, function(msg) {
        if (msg == "1") {
            $j("div___________Perm").hide();
            document.oncontextmenu = function() { return true; }
            document.onselectstart = function() { return true; }
        } else {
            showMsgPage("您不具有查看 " + _title + " 的权限。");
            return;
        }
    });
}
function changeFavColumn(src, itemTabId) {
    var _ids = getCheckedVal(itemTabId);
    if (_ids.length == 0) {
        $a("无选中项。");
        return;
    }
    showProc(src);
    $.post("/ajax.ashx?action=changefavcolumn&t=" + Math.random(), {
        ids: _ids,
        targetId: src.value
    }, function(msg) {
        var sta = gav(msg, "state");
        var sMsg = gav(msg, "msg");
        if (sta == "1") {
            location.reload();
        } else {
            //alert(sMsg);
        }
    });
    showProc(src, false);
}
function getRecommentProductByHistory(_oid) {
    $.post("/ajax.ashx?action=GetRecommentProductByHistory&t=" + Math.random(), {
        oid: _oid
    }, function(msg) {
        var jO = $j("divHistoryRecommentCntr");
        if (msg.length == 0) {
            jO.remove();
        } else {
            jO.html(msg);
        }
    });
}
function getRelevantSales(_oid) {
    $.post("/ajax.ashx?action=GetRelevantSales&t=" + Math.random(), {
        oid: _oid
    }, function(msg) {
        var jO = $j("divRelevantSalesCntr");
        if (msg.length == 0) {
            jO.remove();
        } else {
            jO.html(msg);
        }
    });
}
function getRelevantViewed(_oid) {
    $.post("/ajax.ashx?action=GetRelevantViewed&t=" + Math.random(), {
        oid: _oid
    }, function(msg) {
        var jO = $j("divRelevantViewedCntr");
        if (msg.length == 0) {
            jO.remove();
        } else {
            jO.html(msg);
        }
    });
}
function delInitationlog(src, itemTabId) {
    var _ids = getCheckedVal(itemTabId);
    if (_ids.length == 0) {
        $a("无选中项。");
        return;
    }
    showBgProc();
    $.post("/ajax.ashx?action=DelInitationlog&t=" + Math.random(), {
        ids: _ids
    }, function(msg) {
        if (gav(msg, "state") == "1") {
            var chks = $j(itemTabId).find("input[name=item]:checked");
            chks.each(function(i) {
                $(this).parent().parent().remove();
            });
        } else {
            $a(gav(msg, "msg"));
        }
        showBgProc(false);
    });
}
function sendInvitation(src) {
    var jSrc = $j(src);
    var sEmail = $j("txtEmail").val();
    if (sEmail==null|| sEmail.length == 0) {
        $a("电子邮箱地址不可为空。");
        return;
    }
    if (!PTN_EMAIL.test(sEmail)) {
        $a("电子邮箱地址格式不正确。");
        return;
    }
    showProc(src);
    $.post("/ajax.ashx?action=SendInvitation&t=" + Math.random(), {
        _email: sEmail
    }, function(msg) {
        var sta = gav(msg, "state");
        var sMsg = gav(msg, "msg");
        if (sta == "1") {
            showMsgPage(sMsg, 1, "/user/InviteUserList.aspx", "邀请函列表", "/user/InviteUserList.aspx");
        } else {
            $a(sMsg);
            showProc(src, false);
        }
    });
}


//用户登发

function LoginCheck(username, password) {

    if (username == undefined || username.length == 0) {
        $a("请输入用户名", "表单填写不完整", "txtUsername");
        return;
    }
    if (password == undefined || password.length == 0) {
        $a("请输入用户密码", "表单填写不完整", "password");
        return;
    }
    $.post("/ajax.ashx?action=logincheck&t=" + Math.random(), { username: username, password: password }, function(msg) {
        if (gav(msg, "state") == "1") {
            $a(gav(msg, "msg"));
            location.href = "/";
        }
        else {
            $a(gav(msg, "msg"));
            location.href = "/";
        };

    });
}

/********************
* 产品的搜索
********************/
function searchProd(kwd, type) {
    if (type == null)
        type = "producttype"; //所有商品
    if (kwd == undefined || kwd.length == 0) {
        $a("请输入关键字", "表单填写不完整", "txtKwd");
        return;
    }
    if (type == "producttype") {
        var url = "/Search/?sid=" + encodeURI(kwd);
        url += "&objtype=" + type;

    }
    else {
        var url = "/Search/?kwd=" + encodeURI(kwd);
        url += "&objtype=" + type;

    }

    location.href = url;
}

//意向表单
function submitOrder(src, _oid) {
    showProc(src);
    var _contact = $j("txtContact").val();
    var _compName = $j("txtCompName").val();
    var _tel = $j("txtTel").val();
    var _mobile = $j("txtMobile").val();
    var _email = $j("txtEmail").val();
    var _addr = $j("txtAddr").val();
    var _content = $j("txtContent").val();
    var errorMsg = "";
    if (_contact.length == 0) {
        errorMsg += "<p>联系人不可为空</p>";
    }
    if (_mobile.length == 0) {
        errorMsg += "<p>手机不可为空</p>";
    }
    if (_content.length == 0) {
        errorMsg += "<p>采购意向描述不可为空</p>";
    }
    if (errorMsg.length > 0) {
        $a(errorMsg);
        showProc(src, false);
        return;
    }
    $.post("/ajax.ashx?action=submitorder&t=" + Math.random(), {
        oid: _oid,
        contact: _contact,
        compName: _compName,
        tel: _tel,
        mobile: _mobile,
        email: _email,
        addr: _addr,
        content: _content
    }, function(msg) {
        var sta = gav(msg, "state");
        var sMsg = gav(msg, "msg");
        if (sta == "1") {
            $a(sMsg, 1);
        } else {
            $a(msg);
        }
    });
    showProc(src, false);
}

/*首页关键字end*/
/********************
* 初始化头部热门关键字信息
* 回应 : html代码
********************/
function InitHeaderKeywords(_s) {
    if (_s == "") _s = "6";
    $.post("/ajax.ashx?action=initcommonheaderkeywords&t=" + Math.random(), {
        s: _s
    }, function(msg) {
        $j("commonHeaderkeywords").html(msg);
    });
}

/*友情链接start*/
function getFriends() {
    $.get("/ajax.ashx?action=friendslink", function(msg) {
        $j("divFriendlink").html(msg);
    });
}
/*友情链接end*/