﻿/**
 * 
 **/

/**拍卖逻缉客户端*******************************************************/
//倒计时的显示
function getTimeout(t, ms) {
    if (t < 0) return "已结束";
    return getTimeoutA(t, ms);
}
function getTimeoutA(t, ms) {
    var n_t = setLength(Math.floor(t / 3600000), "0", 2)
         + ":" + setLength(Math.floor(t / 60000) % 60, "0", 2)
         + ":" + setLength(Math.floor((t / 1000) % 60), "0", 2);
//    if (ms) {
//        n_t += "." + setLength(Math.floor(Math.floor(t / 100) % 10), "0", 1);
//    }
    return n_t;
}
//竞拍商品，id为商品id，su在竞拍成功后被调用
function bid(id, su, err, end) {
    $.ajax({
        url: bid.url,
        data: {
            "id": id
        },
        type: "post",
        success: function (d) {
            if (d.substr(0, 5) == "error") {
                //程序错误信息，暂时使用弹出框
                alert2(decodeURI(d.substr(5, d.length - 5)));
            }
            else {
                var s = new Function("return " + d + ";")();
                if (s.Code == 1) {
                    if (su) su();
                }
                else {
                    //拍卖不成功的信息，暂时使用弹出框
                    alert2(s.Detail);
                }
                if (bid.onbided) bid.onbided(id, s);
            }
        },
        error: err,
        complete: end
    });
}
bid.url = "http://bid.5pai.com/BidAction.aspx";
//if (_5Pai.isDebug()) bid.url = "http://localhost:49670/bid/BidAction.aspx";
function bidFocus(id) {
    alertAjax("数据加载…", (_5Pai.is5pai_bid() ? (_5Pai.getRoot() + "/Part/Focus.aspx") : "http://www.5pai.com/Part/Focus.aspx") + "?id=" + id);
}
//时间显示的刷新
function refreshTimer(lst, tmp, fun) {
    for (var i in lst) {
        var o = lst[i];
        if (o && o.State >= 0) {
            var t = o.Timeout;
            var tm = o.serverTime ? o.serverTime : tmp;
            if (o.State != 3 && o.State != 2) t += tm.getTime() - new Date().getTime();
            var msg = "";
            if (o.Message) msg = decodeURI(o.Message);
            else if (o.State == 1 && t <= 0 && o.Timeout > 0) {
                if (t >= -1000) msg = getTimeout(0, true);
                else msg = "通信中";
            }
            else if (o.State >= 5) msg = "已结束";
            else if (o.State == 4) msg = "已中止";
            else if (o.State == 3 || o.State == 2) msg = "即将开拍";
            else if (o.State == 0) msg = "即将开拍";
            else msg = getTimeout(t, t <= 10000);
            if (o.State != 1) t = -1;
            fun(o, t, msg);
        }
    }
}
//商品显示托管基础
function BidManagerBase() {
    this.list = {};
    this.timelist = {};
    this.serverTime = new Date();
    this.serverTime.setTime(getBidInfo.getServerTime());
    var _this = this;
    this.timerEvent = function (o, t, msg) { _this.ontimer(o, t, msg); };
}
BidManagerBase.prototype = {
    refresh: function (lst, time) {
        this.serverTime = time;
        if (this.onok && this.onok(lst) == false) return;
        var currentuid = 0;
        if (_5Pai.isLogin()) {
            currentuid = _5Pai.getUser().userid;
        }
        var issended = false;
        for (var k = 0; k < lst.length; ++k) {
            var _last = this.timelist[lst[k].Id];
            var pi = $.extend({}, _last, lst[k]);
            for (var _i in lst[k]) if (lst[k][_i] == null) pi[_i] = undefined;
            pi.serverTime = time;
            this.timelist[lst[k].Id] = pi;
            var f = this.list[lst[k].Id];
            if (f) f(pi);
            if ((!_last || _last.State == 1)
                && pi.State == 5) {
                this.ongetproduct(pi);
            }
            if (_last && pi && currentuid > 0 && this.bidShower[pi.Id].length>0 &&this.bidShower[pi.Id][0].epoint>0&&
            pi.Userid == currentuid && _last.Userid != currentuid && issended == false) {
                $.ajax({
                    url: "http://www.5pai.com/Part_Default/AccountInfo.aspx",
                    type: "post",
                    success: function (d) {
                       if(d != ""){
                        var bided = _5Pai.static_bided_callbacks._bid_callback;
                        if (bided) bided(d);
                        }
                    }
                });
                issended = true;
            }
            if (this.onrefresh) this.onrefresh(_last, pi);
        }
    },
    //添加托管
    add: function (id, fun) {
        this.list[id] = fun;
    },
    //添加多个商品的托管，使用相同的托管方式
    addRange: function (ids, fun) {
        if (typeof (ids) == "string") ids = ids.split(",");
        for (var i = 0; i < ids.length; ++i) {
            this.add(ids[i], fun);
        }
    },
    remove: function (id) {
        this.list[id] = undefined;
        this.timelist[id] = undefined;
    },
    start: function () {
        if (this.isrunning) return;
        if (this.onstart) this.onstart();
        this.isrunning = true;
        var _this = this;
        this.timer = setInterval(function () {
            _this.refreshTimer();
        }, 40);
    },
    stop: function () {
        if (!this.isrunning) return;
        this.isrunning = false;
        clearInterval(this.timer);
    },
    //竞拍
    bid: function (id) {
        var _this = this;
        if (this.onprebid) this.onprebid(id);
        var ok = false;
        bid(id, function () {
            ok = true;
            if (_this.onbidok) _this.onbidok(id);
        }, function () {
            alert2("连接服务器失败");
        }, function () {
            if (_this.onbidcomplite) _this.onbidcomplite(id, ok);
        });
        if (this.onbid) this.onbid(id);
    },
    //刷新显示
    refreshTimer: function () {
        if (!this.ontimer || !this.serverTime) return;
        refreshTimer(this.timelist, this.serverTime, this.timerEvent);
    },
    ongetproduct: function (p) {
        var n_t = this;
        if (n_t.isgettingproduct) return;
        n_t.isgettingproduct = p.Id;
        if (p.Userid > 0) {
            tongueAjax("http://bid.5pai.com/check.aspx?id=" + p.Id, function (c) { if (c == "complete") n_t.isgettingproduct = 0; });
        }
    }
};
//竞拍状态显示
function BidShower(userid, id, root, init,epoint) {
    if (this == window) {
        var bs = new BidShower(userid, id, root, init, epoint);
        return function (i) {
            return bs.refresh(i);
        }
    }
    this.list = {};
    if(init) this.initInfo = getBidInfo.expand(init);
    this.productId = id;
    this.userid = userid;
    this.epoint = epoint;
    if (root) this.rootElement = $(root);
    else this.rootElement = $("#_bid_" + id);
}
$.extend(BidShower.prototype, {
    getMoneyString: function (m) { return "￥" + formatNum(m, 2); },
    getMoney: function () { return this.rootElement.find(".n_m"); },
    getMoneyFadeout: function () { return this.rootElement.find(".n_f"); },
    getUser: function () { return this.rootElement.find(".n_u"); },
    getState: function () { return this.rootElement.find(".n_s"); },
    getTime: function () { return this.rootElement.find(".n_t"); },
    getBidding: function () { return this.rootElement.find(".n_bid_btn"); },
    tryGet: function (k) {
        if (this.list[k] == undefined)
            this.list[k] = this["get" + k]();
        return this.list[k];
    },
    refresh: function (i) {
        var r = this.rootElement;

        var n_m = this.tryGet("Money");
        var lm = n_m.html();
        var cm = this.getMoneyString(i.Price);

        //点击变化后
        if (this.lastValue == null ? lm != cm : this.lastValue.Price != i.Price) {
            //显示价格
            n_m.html(cm);

            //高亮显示价格
            var n_f = this.tryGet("MoneyFadeout");
            n_f.html(cm);
            n_f.show();
            n_f.fadeOut();

            //显示用户
            var n_u = this.tryGet("User");
            n_u.html(decodeURIComponent(i.Username));
            n_u.each(function (v1, v2) {
                v2.href = "http://user.5pai.com/Profile.aspx?id=" + i.Userid;
                v2.title = "查看用户“" + i.Username + "”的详细信息";
            });

            //触发事件
            if (this.onchange) this.onchange(i, this.lastValue);
        }

        //状态变化之后
        if (this.lastValue == null || this.lastValue.State != i.State) {
            var n_s = this.tryGet("State");
            n_s.each(function (v1, v2) {
                var _v2 = $(v2);
                var ex = _v2.attr("state");
                if (ex) {
                    try {
                        var isShow = new Function("var a=arguments;var s=a[0];var i=a[1];var b=a[2];return " + ex + ";").call(v2, i.State, i, this);
                        if (isShow) _v2.show();
                        else _v2.hide();
                    }
                    catch (exp) { }
                }
            });

            //触发事件
            if (this.onstatechange) this.onstatechange(i, this.lastValue);
            if (this.onchange) this.onchange(i, this.lastValue);
        }

        this.lastValue = i;
    },
    timer: function (i, t, msg) {
        if (msg == this.lastMessage) return;
        this.lastMessage = msg;
        var n_t = this.tryGet("Time");
        n_t.html(msg);
        if (t <= 5000 && t >= 0) {
            if (this.lastSeconds != 1) {
                this.lastSeconds = 1;
                n_t.css("background", "red");
                n_t.css("color", "white");
            }
        }
        else if (t <= 10000 && t >= 5000) {
            if (this.lastSeconds != 2) {
                this.lastSeconds = 2;
                n_t.css("background", "none");
                n_t.css("color", "red");
            }
        }
        else {
            if (this.lastSeconds) {
                this.lastSeconds = 0;
                n_t.css("background", "none");
                n_t.css("color", "");
            }
        }
    },
    showBidding: function () {
        clearTimeout(this.hideBidding_timer);
        var b = this.tryGet("Bidding");
        if (b) {
            b.find(".n_bid_ok").hide();
            var w = b.find(".n_wait");
            if (!w.length) {
                w = $('<img src="http://static.5pai.com/new/wait.gif" class="n_wait" />');
                b.append(w);
            }
            w.show();
        }
    },
    hideBidding: function (id, ok) {
        var b = this.tryGet("Bidding");
        if (b) {
            b.find(".n_wait").hide();
            var w = b.find(".n_bid_ok");
            w.hide();
            if (!ok) return;
            if (!w.length) {
                w = $('<span class="n_bid_ok">出价成功</span>');
                b.append(w);
            }
            w.show();
            this.hideBidding_timer = setTimeout(function () {
                w.fadeOut();
            }, 1500);
        }
    }
});
$.extend(BidManagerBase.prototype, {
    //把显示控制对象绑定到管理对象中去
    bindShower: function (s) {
        var m = this;
        if (!m.bidShower) {
            m.bidShower = {};
        }
        var ids = new Array();
        for (var i in s) {
            if (!m.bidShower[i]) m.bidShower[i] = new Array();
            m.bidShower[i].push(s[i]);
            ids.push(i);
            if (s[i].initInfo) m.timelist[i] = $.extend({}, m.timelist[i], s[i].initInfo);
        }
        m.addRange(ids, function (i) {
            var n_s = m.bidShower[i.Id];
            for (var k = 0; k < n_s.length; ++k) n_s[k].refresh(i);
        });
    },
    //把显示控制对象绑定到管理对象中去
    bindShowerRange: function (ids, fun) {
        var ss = {};
        for (var i = 0; i < ids.length; ++i) ss[ids[i]] = fun(ids[i]);
        this.bindShower(ss);
    },
    ontimer: function (i, t, msg) {
        if (!this.bidShower) return;
        var n_s = this.bidShower[i.Id];
        if (n_s) for (var k = 0; k < n_s.length; ++k) n_s[k].timer(i, t, msg);
    },
    removeShower: function (e) {
        for (var i in this.bidShower) {
            var b = this.bidShower[i];
            var sb = new Array();
            for (var k = 0; k < b.length; ++k) {
                if (b[k].rootElement.selector == e.selector) continue;
                sb.push(b[k]);
            }
            this.bidShower[i] = sb;
        }
    },
    eachShower: function (fun) {
        for (var i in this.bidShower) {
            var b = this.bidShower[i];
            for (var k = 0; k < b.length; ++k) fun(b[k]);
        }
    },
    onprebid: function (id) {
        if (!this.bidShower) return;
        var n_s = this.bidShower[id];
        if (n_s) for (var k = 0; k < n_s.length; ++k) n_s[k].showBidding(id);
    },
    onbidcomplite: function (id, ok) {
        if (!this.bidShower) return;
        var n_s = this.bidShower[id];
        if (n_s) for (var k = 0; k < n_s.length; ++k) n_s[k].hideBidding(id, ok);
    }
});

/**后台信息读取***********************************************************/
//得到拍卖中的商品的信息
function getBidInfo(callback, id, err, end, lsTime) {
    if (id == "") {
        if (!end) end();
        return;
    }
    var p = { "id": id, "t": lsTime, "v": 1};
    if (getBidInfo.checkNew) p["n"] = "True";
    $.ajax({
        url: getBidInfo.url,
        data: p,
        timeout: 5000,
        cache: false,
        type: "get",
        beforeSend: function (r) {
            r.setRequestHeader("place", window.location);
        },
        success: function (d, v, r) {
            if (d.substr(0, 5) == "error") {
                //错误信息，暂时使用弹出框
                //alert(decodeURI(d.substr(5, d.length - 5)));
            }
            else if (d != "") {
                //把得到的商品信息返回
                var lst = new Function("return " + d + ";")();
                var ps = new Array();
                for (var i = 0; i < lst.Ps.length; ++i) {
                    ps.push(getBidInfo.expand(lst.Ps[i]));
                }
                lst.Ps = ps;
                getBidInfo.addStack({
                    headTime: new Date(r.getResponseHeader("Date")).getTime(),
                    serverTime: lst.Time,
                    sendTime: this._5pai_sendtime.getTime(),
                    getTime: this._5pai_gettime.getTime()
                });
                if (!(lst.New && getBidInfo.onnew && getBidInfo.onnew(lst) == false)) callback(lst);

            }
        },
        error: function (v1, v2, v3) {
            if (err != null) err(v1, v2, v3);
        },
        complete: function (v1) { if (end != null) end(v1); }
    });
}
getBidInfo.expandMap = {
    a: "Price",
    b: "Userid",
    c: "Username",
    d: "Userphone",
    e: "Timeout",
    f: "State",
    g: "Message",
    h: "Id"
};
getBidInfo.expand = function (x) {
    if (x.Id) return x;
    var y = getBidInfo.expandMap;
    var r = {};
    for (var i in x) if (y[i]) r[y[i]] = x[i];
    return r;
}
getBidInfo.addStack = function (ai) {
    var range = getBidInfo.range || {};
    var min = ai.serverTime - ai.sendTime;
    if (range.min == undefined) range.min = min;
    else range.min = Math.min(min, range.min);
    var max = ai.serverTime - ai.getTime;
    if (range.max == undefined) range.max = max;
    else range.max = Math.max(max, range.max);
    range.value = ai.getTime - (ai.serverTime - (range.max + range.min) / 2);
    getBidInfo.range = range;
}
getBidInfo.getServerTime = function () {
    if (!getBidInfo.range) return new Date().getTime();
    return Math.round(new Date().getTime() - getBidInfo.range.value);
}
//自定义获取商品信息的地址
getBidInfo.url = "http://bid.5pai.com/BidInfo.axd";
//if (_5Pai.isDebug()) getBidInfo.url = "http://localhost:49670/bid/BidInfo.axd";
//商品拍卖管理器
function BidInfo() {
    this.list = {};
    this.markTime = 0;
    var _this = this;
    this.nextClick = function () {
        _this.clickOnce();
    };
    this.clickOk = function (lst) {
        _this.markTime = lst.Time;
        _this.lastTime = new Date();
        _this.dTime = _this.lastTime.getTime() - _this.lastSendTime.getTime();
        _this.serverTime = new Date();
        _this.serverTime.setTime(getBidInfo.getServerTime());
        if (_this.onok) _this.onok(lst.Ps);
    };
    this.clickError = function (v1, v2) {
        if (_this.onerror) _this.onerror(v1, v2);
    };
    this.clickComplite = function (v1) {
        _this.isInClickOnce = false;
        clearTimeout(_this.timer);
        if (_this.ongetend) _this.ongetend();
        if (_this.isrunning) {
            _this.timer = setTimeout(function () { _this.nextClick(); }, 1000);
        }
    };
}
//托管商品
$.extend(BidInfo.prototype, {
    add: function (id) {
        this.list[id] = true;
    },
    //撤销商品托管
    remove: function (id) {
        this.list[id] = undefined;
    },
    //托管多个商品
    addRange: function (ids) {
        if (typeof (ids) == "string") ids = ids.split(",");
        for (var i = 0; i < ids.length; ++i) {
            this.add(ids[i]);
        }
    },
    //得到托管商品的列表
    getList: function () {
        var arr = new Array();
        for (var i in this.list) {
            if (this.list[i]) arr.push(i);
        }
        return arr;
    },
    //连接服务器得到所有托管商品的最新信息
    clickOnce: function () {
        if (this.isInClickOnce) return;
        this.isInClickOnce = true;
        clearTimeout(this.timer);
        this.lastSendTime = new Date();
        getBidInfo(this.clickOk,
            this.getList().toString(),
            this.clickError,
            this.clickComplite,
            this.markTime);
    },
    //开始托管程序
    start: function () {
        if (this.isrunning) return;
        this.isrunning = true;
        this.clickOnce();
    },
    //停止托管程序
    stop: function () {
        if (!this.isrunning) return;
        this.isrunning = false;
        clearTimeout(this.timer);
    }
});
//商品显示托管
function BidManager() {
    BidManagerBase.call(this);
    this.bidinfo = new BidInfo();
    var _this = this;
    this.bidinfo.onok = function (lst) {
        _this.serverTime = this.serverTime;
        _this.refresh(lst, _this.serverTime);
    }
}
$.extend(BidManager.prototype, BidManagerBase.prototype, {
    add: function (id, fun) {
        BidManagerBase.prototype.add.call(this, id, fun);
        this.bidinfo.add(id);
    },
    //撤销托管
    remove: function (id) {
        BidManagerBase.prototype.add.call(this, id, fun);
        this.bidinfo.remove(id);
    },
    //启动托管程序
    start: function () {
        if (this.isrunning) return;
        this.bidinfo.start();
        BidManagerBase.prototype.start.call(this);
    },
    //停止托管程序
    stop: function () {
        if (!this.isrunning) return;
        this.bidinfo.stop();
        BidManagerBase.prototype.stop.call(this);
    },
    //竞拍
    onbidok: function () {
        this.bidinfo.clickOnce();
    }
});

/**附加方法**************/

function tryBindShower(n_s) {
    if (window.M) M.bindShower(n_s);
    else $(function () { M.bindShower(n_s); });
}

function loadFavStates() {
    if (!_5Pai.isLogin() || !window.M) return;
    var favs = $(".n_pi_fav");
    var ids = {},str = [];
    favs.each(function(i, o){
        var id = $(o).attr("productid");
        ids[id] = true;
    });
    for (var i in ids) str.push(i);

    if (str.length <= 0) return;
    $.ajax({
        url: "http://www.5pai.com/Part/GetFavs.aspx",
        data: { "id": str.join(",") },
        type: "post",
        success: function (d) {
            var l = new Function("return [" + d + "];")();
            favs.each(function (i, o) {
                var _o = $(o);
                _o.removeClass("n_pi_faved");
                for (var k = 0; k < l.length; ++k) {
                    if (_o.attr("productid") == l[k].toString()) {
                        _o.addClass("n_pi_faved");
                        return;
                    }
                }
            });
        }
    });
}

$(loadFavStates);