﻿//通过Ajax访问一个链接的功能
function doHref(t, ok) {
    $.ajax({
        url: t.href,
        type: 'post',
        success: function (d) { alert2(d); },
        error: function (d) { },
        complete: function (d) { if (ok) ok(); }
    });
}
//格式化字符串，把长度不满len的str使用n在前面填充到len。
function setLength(str, n, len) {
    str = str.toString();
    while (str.length < len) str = n + str.toString();
    return str;
}
//格式化小数，并四舍五入。如：formatNum(12.345678, 4)
function formatNum(n1, n2) {
    n1 = n1.toString();
    n2 = parseInt(n2);
    var ps = n1.indexOf('.');
    if (ps == -1) {
        var k = n1 + ".";
        for (var i = 0; i < n2; ++i) k += "0";
        return k;
    }
    var vl = ps + n2 + 1;
    if (n1.length <= vl) {
        for (var i = 0; i < vl - n1.length; ++i) n1 += "0";
        return n1;
    }
    var b = n1.substring(0, vl);
    var c = n1.substring(vl, vl + 1);
    if (c == "" || parseInt(c) < 5) return b;
    return formatNum(((Math.round(parseFloat(b) * Math.pow(10, n2)) + Math.round(parseFloat(Math.pow(0.1, n2).toString().substring(0, Math.pow(0.1, n2).toString().indexOf('.') + n2 + 1)) * Math.pow(10, n2))) / Math.pow(10, n2)), n2);
}
function setCookie(key, value, day) {
    day = parseInt(day);
    if (!isNaN(day)) {
        var expireDate = new Date();
        expireDate.setTime(expireDate.getTime() + (day * 24 * 3600000));
        document.cookie = key + "=" + value + ";expires=" + expireDate.toGMTString();
    }
    else { document.cookie = key + "=" + value; }
}
function getCookie(str, _ck) {
    var reg = new RegExp("(^| )" + str + "=([^;]*)(;|$)", "gi");
    if (!_ck) _ck = document.cookie;
    var ck = reg.exec(_ck);
    try { if (ck[2] == null || typeof (ck[2]) == "undefined") return null; }
    catch (e) { return null; }
    return ck[2];
}

//重写alert函数
if ($.prototype.dialog) {
    window.alert = function (msg, _btn) {
        msg = msg + "";
        var _dialog = $('<div class="ui-corner-all ui-state-default" title="提示"><span style="float:left;display:block;" class="ui-icon ui-icon-alert"></span><p style="text-align:left;float:left;width:245px;margin:0px;padding-left:7px;"></p></div>');
        var _message = _dialog.find("p");
        if (msg) msg = $.trim(msg);
        if (msg && msg.length > 0 && msg.charAt(0) != "<") msg = msg.replace(/\r\n/g, "<br />");
        _message.html(msg);
        var div, _r;
        if (!_btn) {
            _btn = {
                autoOpen: false,
                modal: true,
                buttons: {
                    "确定": function () {
                        $(this).dialog('close');
                    }
                }
            };
        }
        else {
            var _btn_b = _btn.beforeclose;
            _btn.beforeclose = function () {
                if (div) div.remove();
                if (_r) _r.remove();
                if (_btn_b) _btn_b.apply(this, arguments);
            }
        }
        _r = _dialog.dialog(_btn);
        _dialog.dialog('open');
        div = _r.parent();
        return div;
    }
    jQuery.prototype._5pai_alert = function (_o) {
        _5pai_alert.call(this, _o);
    }

    window._5pai_alert = $.extend(function (_o) {
        var _t = _5pai_alert;
        if (_o == "close") {
            _t.close();
        }
        else {
            _t.show(this);
        }
    }, {
        modelLayer: $('<div style="z-index: 2001; position:absolute;left:0px;top:0px;width:100%;bottom:0px;" class="ui-widget-overlay"></div>'),
        posLayer: $('<div style="z-index: 2002; position:absolute;left:0px;width:100%;"></div>'),
        show: function (msg) {
            this.posLayer.css("visibility", "hidden");
            this.posLayer.children().remove();
            this.posLayer.append(msg);
            $(document.body).append(this.modelLayer);
            $(document.body).append(this.posLayer);
            this.showA();
            $("select").hide();
            $("object").hide();
            this.posLayer.css("visibility", "visible");
        },
        showA: function () {
            //this.modelLayer.width(document.documentElement.scrollWidth);
            this.modelLayer.height(document.documentElement.scrollHeight);
            this.posLayer.css("top", Math.max(0, (((window.innerHeight || document.documentElement.offsetHeight || document.body.offsetHeight) - this.posLayer.height()) / 2
                + (document.documentElement.scrollTop || document.body.scrollTop))) + "px");
            this.posLayer.children().css("margin", "0px auto");
        },
        close: function () {
            $("select").show();
            $("object").show();
            this.modelLayer.remove();
            this.posLayer.remove();
        }
    });
    String.prototype._5pai_alert = function (f) {
        var _l = $("<div style='width:300px;background:#ff9;padding:3px 10px;padding-right:15px;position:relative;'><div>"
            + this + "<div><a style='color:red;display:block;right:5px;top:3px;position:absolute;' href='#'>X</a></div>");
        _l.find("a").bind("click", function () {
            _5pai_alert.close();
            if (f) f();
        });
        _l._5pai_alert();
    }
    window.changeTongue = function (tongueDiv, tongue1, tongueMain) {
        var action = tongueMain.attr("action");
        if (action == "0") {
            tongue1.css("visibility", "hidden");
            tongueDiv.removeClass("close_tongue").addClass("close_tongueopen");
            tongueMain.effect("slide", { direction: "right", mode: "show" }, 450, function () {
                tongue1.css("visibility", "visible");
                tongue1.show();
                tongueMain.attr("action", "1");
            });
        } else {
            tongue1.css("visibility", "hidden");
            tongueMain.effect("slide", { direction: "right", mode: "hide" }, 450, function () {
                tongue1.css("visibility", "visible");
                tongue1.show();
                tongueDiv.removeClass("close_tongueopen").addClass("close_tongue");
                tongueMain.attr("action", "0");
            });
        }
    }
    window.tongueAjax = function (ajax_url, complete) {
        if (tongueAjax.tongueDiv) tongueAjax.tongueDiv.remove();
        var tongueDiv = $('<div class="close_tongue clearfix">');
        tongueAjax.tongueDiv = tongueDiv;
        var tongue1 = $('<a class="close_tongue1"><span class="close_tongue_bg"></span></a>');
        var tongueMain = $('<div class="close_tonguem"action="0" ><div class="close_tonguembg"></div>');
        var tongueMain2 = $('<div class="close_tonguembd"></div>');
        var tongue2 = $('<div class="close_tongue2"><span class="close_tongue_bg"></span></div>');
        tongueMain.append(tongueMain2);
        tongueDiv.append(tongue1);
        tongueDiv.append(tongueMain);
        tongueDiv.append(tongue2);
        tongue1.click(function () { changeTongue(tongueDiv, tongue1, tongueMain); });
        tongue2.click(function () { changeTongue(tongueDiv, tongue1, tongueMain); });
        $(document.body).append(tongueDiv);
        tongueDiv.fadeIn();
        $.ajax({
            url: ajax_url,
            type: "post",
            success: function (d) {
                tongueMain2.html(d);
                changeTongue(tongueDiv, tongue1, tongueMain);
                if (complete) complete("success", d);
            },
            error: function (d) {
                alert(d.responseText);
                if (complete) complete("error");
            },
            complete: function () {
                if (complete) complete("complete");
            }
        });
    }

    
    window.alertAjax = function (loading, ajax_url, complete) {
        var r = null;
        var abort = false;
        if (loading) loading._5pai_alert(function () { abort = true; if (r) r.abort(); });

        r = $.ajax({
            url: ajax_url,
            type: "post",
            success: function (d) {
                if (abort) return;
                "已加载…"._5pai_alert();
                _5pai_alert.posLayer.css("visibility", "hidden");
                _5pai_alert.posLayer.html(d);
                _5pai_alert.showA();
                _5pai_alert.posLayer.css("visibility", "visible");
                if (complete) complete("success", d);
            },
            error: function (d) {
                if (abort) return;
                _5pai_alert.close();
                alert(d.responseText);
                if (complete) complete("error");
            },
            complete: function () {
                if (abort) return;
                if (complete) complete("complete");
            }
        });
    }
    window.alert2 = function (d, t) {
        var _ttimer1 = null;
        var _dia = alert(d, {
            autoOpen: true,
            modal: false,
            buttons: {
                "我知道啦": function () {
                    $(this).dialog('close');
                }
            },
            beforeclose: function () {
                try { clearTimeout(_ttimer1); }
                catch (_e) { }
            }
        });
        _dia.css("border", "1px solid #333");
        _ttimer1 = setTimeout(function () {
            try { _dia.fadeOut(function () { _dia.dialog('close'); }); }
            catch (_e) { }
        }, t || 3000);
    };
}

//客户端代理
window.ClientProxy = $.extend(function (_r) {
    this.iframe = $('<iframe style="display:none;" src="' + _r + '"></iframe>')[0];
    var _this = this;
    this.isproxy = true;
    $(function () { document.body.appendChild(_this.iframe); });
}, {
    list: {},
    getHost: function (url) {
        return this.getHostA(url).host;
    },
    getHostA: function (url) {
        var n_u = url.toLowerCase();
        var _i = n_u.indexOf("://");
        if (_i < 0) return false;
        var _i2 = n_u.indexOf("/", _i + 3);
        if (_i2 < 0) _i2 = n_u.length;
        return {
            host: n_u.substring(_i + 3, _i2),
            root: n_u.substring(0, _i2)
        };
    },
    ajax: function (s, fun) {
        var _h = this.getHostA(s.url);
        var n_s = _h.host;
        if (!this.list[n_s]) this.list[n_s] = new ClientProxy(this.getProxyUrl(_h));
        return this.list[n_s].ajax(s, fun);
    },
    getProxyUrl: function (_h) {
        var url = "/ClientProxy.axd";
        if (_h.host == "static.5pai.com") url = "/proxy.htm";
        return _h.root + url;
    }
});
$.extend(ClientProxy.prototype, {
    ajax: function (s, fun) {
        if (!this.complite) {
            if (!this.list) this.list = new Array();
            var n_t = this;
            var len = n_t.list.length;
            var w = {
                n_s: s,
                n_f: function (r) {
                    w.xhr = r;
                    if (fun) fun(r);
                },
                abort: function () {
                    if (w.xhr) w.xhr.abort();
                    else n_t.list.reverse(len, 1);
                }
            };
            n_t.list.push(w);
            return w;
        }
        else {
            return this.ajaxA(s, fun);
        }
    },
    ajaxA: function (s, fun) {
        var _this = this;
        var r = null;
        s.xhr = function () {
            r = _this.iframe.contentWindow.createXMLHttpRequest();
            return r;
        };
        var beforeSend = s.beforeSend;
        s.beforeSend = function () {
            r.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            if (beforeSend) beforeSend.apply(s, arguments);
        };
        s._5pai_sendtime = new Date();
        r = _5Pai.ajax(s) || r;
        if (fun != null) fun(r);
        return r;
    },
    docomplite: function () {
        this.complite = true;
        if (this.list) {
            for (var i = 0; i < this.list.length; ++i) this.ajaxA(this.list[i].n_s, this.list[i].n_f);
            this.list = undefined;
        }
    }
});

/**通用状态控制********************/
if (!window._5Pai) {
    window._5Pai = {
        ajax: jQuery.ajax,
        isDebug: function () {
            return window.location.hostname.toLowerCase() == 'local' + 'host';
        },
        is5pai: function () {
            var _h = window.location.host.toLowerCase();
            return _h == "5pai.com" || _h.indexOf(".5pai.com") > 0;
        },
        is5pai_bid: function () {
            return this.is5paisub("bid", "www.5pai.com", "5pai.com");
        },
        is5paisub: function (n, d) {
            n = n.toLowerCase();
            if (!d) d = n + ".5pai.com";
            if (this.isDebug()) return this.getRoot() == "/" + n;
            var _h = window.location.hostname.toLowerCase();
            if (_h == d) return true;
            for (var i = 2; i < arguments.length; ++i) if (_h == arguments[i]) return true;
            return false;
        },
        getRoot: function () {
            if (this.is5pai() || !this.isDebug()) return "";
            var n_s = window.location.pathname;
            var _i = n_s.indexOf("/", 1);
            if (_i < 0) return n_s;
            return n_s.substring(0, _i);
        },
        isLogin: function () {
            if (getCookie("userinfo")) return true;
            return false;
        },
        static_login_callbacks: {},
        set_login_callback: function (f) {
            window.login_callback = function () {
                var _sfs = _5Pai.static_login_callbacks;
                for (var k in _sfs) {
                    if (_sfs[k]) _sfs[k]();
                }
                if (f) f();
            };
        },
        static_bided_callbacks: {},
        getUser: function () {
            var n_u = getCookie("userinfo");
            if (!n_u) return null;
            n_u = n_u.split("&");
            var _user = {};
            for (var _k in n_u) {
                var _v = n_u[_k].split("=");
                _user[_v[0]] = _v[1];
            }
            return _user;
        },
        alert: window.alert
    };
    _5Pai.static_bided_callbacks._bid_callback = function (d) {
        var d = new Function("return " + d)();
        var e = d.epoint;
        if ($("#mainmyEpoint")) $("#mainmyEpoint").html(e);
        if ($("#topmyEpoint")) $("#topmyEpoint").html(e);
    };
    window.proxyPath = _5Pai.getRoot() + "/Proxy.axd";
    if (_5Pai.is5pai_bid()) window.isBidSite = _5Pai.getRoot();

    function doAjaxSuccess(d, s, r, v) {
        if (r) {
            var order = r.getResponseHeader("_5Pai-Ajax-Order");
            //执行登录命令
            if (order == '1') {
                if (window.alertAjax) {
                    //脚本回调
                    _5Pai.set_login_callback(function () { return $.ajax(s); });
                    //TODO:执行弹出登录框，登录成功后请执行callback操作（可能为null）
                    alertAjax("您还没有登录。正在加载登录界面…", "http://user.5pai.com/login/ajaxlogin.aspx");
                }
                else window.location = "http://user.5pai.com/login/login.aspx?__redirect=" + window.location.href;
            }
            else if (order == '2') {
                alert2(d);
            }
            else if (order == "3") {
                try {
                    new Function(d)();
                }
                catch (e2) {
                    if (s.error) s.error.call(this, r, "error", e2);
                }
            }
            else if (order == "4") {
                location = d;
            }
            else if (s.success) {
                s.success.call(this, d, v, r);
            }
        }
        else {
            if (s.success) s.success.call(this, d, v, r);
        }
    };

    //重写ajax函数，执行一些必要的拦截
    jQuery.ajax = function (s) {
        if (!s) return _5Pai.ajax();
        s._5pai_sendtime = new Date();
        var r = null;
        var n_s = $.extend({}, s);
        if (n_s.context) throw new Error("不支持context选项。");
        var _scs = function (d, v) {
            this._5pai_gettime = new Date();
            doAjaxSuccess.call(this, d, s, r, v);
        };
        n_s.success = _scs;
        var _url_h = ClientProxy.getHost(n_s.url);
        if (_url_h && _url_h != location.host.toLowerCase()) {
            if (_5Pai.is5pai()) {
                document.domain = "5pai.com";
                var _d, _v, _sok = false;
                n_s.success = function (d, v) {
                    if (r) _scs.call(this, d, v);
                    else {
                        _sok = true;
                        _d = d;
                        _v = v;
                    }
                }
                return ClientProxy.ajax(n_s, function (_sr) {
                    r = _sr;
                    if (_sok) _scs.call(n_s, _d, _v);
                });
            }
            else {
                n_s.url = proxyPath + "?url=" + encodeURIComponent(n_s.url);
            }
        }
        r = _5Pai.ajax(n_s);
        ///
        return r;
    }
}

///以上是框架级别的通用
///以下是应用级别的通用

//用户登录
$(function () {
    if ($(".n_user").length) {
        _5Pai.static_login_callbacks._top_user_info = function () {
            if (!_5Pai.isLogin()) return;
            $.ajax({
                url: "http://user.5pai.com/login/email_count.aspx",
                type: 'post',
                success: function (d) {
                    $(".n_user").html(d);
                }
            });
        }
    }
});

//加载广告
function loadAds(id) {
    document.write('<div id="__ads_' + id + '"></div>');
    $.ajax({
        url: "http://info.5pai.com/ads/item.aspx?id=" + id,
        success: function (d) { $("#__ads_" + id).html(d); }
    });
}

//滚动效果

function n_rollsA(r, a, b, i, c, f) {
    clearTimeout(r[0].r_timer);
    r[0].scrollTop = b + (a - b) * i / c;
    if (i >= c) {
        if (f) f();
    }
    else {
        r[0].r_timer = setTimeout(function () {
            n_rollsA(r, a, b, i + 1, c, f);
        }, 45);
    }
}
function n_rollsB(r, s, m, t) {
    if (r.attr("n_rools") == "pause") {
        n_rollsC(r, s, m, t);
    }
    else {
        clearTimeout(r[0].s_timer);
        var r1 = r.find(s);
        if (r1.length < 2) return;
        n_rollsA(r, r.height(), 0, 0, m, function () {
            $(r1[0]).remove();
            r.append(r1[0]);
            r[0].scrollTop = 0;
            r[0].s_timer = setTimeout(function () {
                n_rollsB(r, s, m, t);
            }, t);
        });
    }
}
function n_rollsC(r, s, m, t) {
    clearTimeout(r[0].n_timer);
    r[0].n_timer = setTimeout(function () {
        n_rollsB(r, s, m, t);
    }, t);
}
function n_rolls(r, s, m, t) {
    r.bind("mouseover", function () { r.attr("n_rools", "pause"); });
    r.bind("mouseout", function () { r.attr("n_rools", ""); });
    n_rollsC(r, s, m, t);
}

//提示信息
function n_hint_a(a) {
    if (!a || !a.length) return;
    var h = $('<span class="n_hint_a" style="display:none;"><span class="n_hint_ab"></span><span class="n_hint_at"></span><span class="n_hint_ac"></span></span>');
    h.find(".n_hint_at").html(a[0].title);
    h.css("top", a.height() + 2 + "px");
    h.css("left", a.width() / 2 - 159 + "px");
    a.css("position", "relative");
    a.css("z-index", "501");
    a.append(h);
    h.fadeIn("fast");
    var timer = setTimeout(function () { h.fadeOut("fast", function () { h.remove(); delete h; }); }, 6000);
    h.find(".n_hint_ac").click(function () { clearTimeout(timer); timer = 0; h.remove(); delete h; });
    h.bind("mouseover", function () { clearTimeout(timer); timer = 0; });
    h.bind("mouseout", function () { timer = setTimeout(function () { h.fadeOut("fast", function () { h.remove(); delete h; }); }, 1000); });
}

//输入框内容提示
function inputClick(v, oid, str) {
    var _n = $("#" + oid);
    if (v) {
        if (!_n._5pai_init) {
            _n._5pai_init = true;
            if (_n.val() != "" && _n.val() == str) {
                _n.val("");
            }
            _n.removeClass("unchecked");
        }
    }
    else if (_n.val() == "") {
        if (_n._5pai_init) return;
        _n.val(str);
        _n.addClass("unchecked");
    }
    else if (_n.val() == str) {
        _n.val(str);
        _n.addClass("unchecked");
    }
}

function inputOnblur(oid, str) {
    var _n = $("#" + oid);
    if (_n.val() == "") {
        _n._5pai_init = false;
        inputClick(false, oid, str)
    }
}

function changInputVal_do(oid, str) {
    var _n = $("#" + oid);
    _n.focus(function () {
        if (_n.val() == str) {
            inputClick(true, oid, str);
        }
    });
    _n.blur(function () {
        inputOnblur(oid, str);
    });
}


//加载分享
function loadShares(parent, title, content, img, url1) {
    $.ajax({
        url: "http://static.5pai.com/com/share.htm",
        cache: false,
        success: function (d) {
            var url1 = url1 || window.location.href;
            var content = content || $("meta[name=description]").attr("content") || document.title;
            var title = title || document.title;
            var img = img || "http://static.5pai.com/new/logo.png";
            parent.append(
                d.replace(/\{url\}/g, encodeURIComponent(url1))
                .replace(/\{title\}/g, encodeURIComponent(title))
                .replace(/\{content\}/g, encodeURIComponent(content))
                .replace(/\{image\}/g, encodeURIComponent(img))
                .replace(/\{url0\}/g, url1));
        }
    });
}