﻿$(function () {
    $("ul.switch-li").each(function () {
        var dom = $(this);
        var li = dom.find("li");
        var count = li.length;

        // 设置按钮
        var sel = $("<div></div>");
        var txt = [];
        txt.push('<div style="margin:auto;width:' + (50 + count * 16) + 'px"><a class="icon iswitch ileft" href="#left" hidefocus></a>');
        for (var i = 0; i < count; i++) {
            txt.push('<a class="icon icase ' + (i ? "" : "icheck") + '" href="#' + i + '" hidefocus></a>');
        }
        txt.push('<a class="icon iswitch iright" href="#right" hidefocus></a></div>');
        sel.html(txt.join(""));
        dom.after(sel);

        var ca = sel.find("a.icase");
        var now = 0;
        var avgw = this.offsetWidth;

        li.each(function (i) {
            $(this).css({
                left: i ? avgw : 0,
                position: "absolute"
            });
        });

        // 按钮事件
        sel.click(function (event) {
            var target = event.target;
            if (target.tagName == "A") {
                var key = target.href.replace(/http:.+#/i, "");

                switch (key) {
                    case "left": return show(now - 1);
                    case "right": return show(now + 1);
                    default: return show(parseInt(key));
                }
            }
        });

        var auto = 0;
        var dt = 3500;
        var isauto = this.getAttribute("data-auto") != null;
        var ischeck = false;
        // 执行函数
        function show(val) {
            if (val < 0)
                val = count - 1;
            else if (val >= count)
                val = 0;

            if (now != val && !ischeck) {
                clearTimeout(auto);
                ischeck = true;
                $(li[now]).animate({
                    left: -avgw
                }, "fast", function () {
                    $(this).css("left", avgw);
                    ischeck = false;
                    if (isauto) auto = setTimeout(function () { show(now + 1); }, dt);
                });

                $(li[val]).animate({
                    left: 0
                }, "fast");

                $(ca[now]).removeClass("icheck");
                $(ca[val]).addClass("icheck");

                now = val;
            }
            return false;
        }

        if (isauto) {
            dom.hover(function () {
                clearTimeout(auto);
            }, function () {
                auto = setTimeout(function () { show(now + 1); }, dt);
            });

            auto = setTimeout(function () { show(now + 1); }, dt);
        }
    });

    $("ul.imgwarp img").each(function () {
        if (!this.complete) {
            this.onload = function () { var top = (96 - this.height) / 2; this.style.marginTop = top + "px"; }
        } else {
            var top = (96 - this.height) / 2;
            this.style.marginTop = top + "px";
        }
    });

    $("ul.tab").each(function () {
        var dom = $(this);
        var li = dom.find("li");

        var bd = $(dom.attr("data-target"));
        var card = bd.find(".tab-card");

        var now = 0;
        var avgw = bd[0].offsetHeight;

        function tabswitch(val) {
            if (now != val) {
                $(li[now]).removeClass("check");
                $(li[val]).addClass("check");

                $(card[now]).animate({
                    top: -avgw
                }, "fast", function () {
                    $(this).css("top", avgw);
                    ischeck = false;
                });

                $(card[val]).animate({
                    top: 0
                }, "fast");

                now = val;
            }
            return false;
        }

        card.each(function (i) {
            $(this).css({
                top: i ? avgw : 0,
                position: "absolute"
            });
        });

        dom.click(function (event) {
            var target = event.target;
            if (target.tagName == "A") {
                var href = target.href;
                if (href.indexOf("#") != -1) {
                    var key = href.replace(/http:.+#/i, "");

                    switch (key) {
                        default: return tabswitch(parseInt(key));
                    }
                }
            }
        });
    });


    $("#player").each(function () {
        var dom = $(this);
        var isShow = false;

        function check() {
            if (!isShow) {
                var path = this.getAttribute("data-path");
                this.innerHTML = '<embed width="280" height="230" src="http://tv.baozang.com/common/swf/MediaPlayback.swf" allowfullscreen="True" allowscriptaccess="always" wmode="transparent" flashvars="&amp;src=rtmp://211.155.224.2:1935/vod/' + path + '&amp;autoHideControlBar=true&amp;streamType=recorded&amp;autoPlay=true" type="application/x-shockwave-flash">';
                isShow = true;
            }
            return false;
        }
        dom.bind("click", check);
    })

    $("div.adbox").each(function () {
        var a = $(this).find("a");
        var max = a.length;

        var index = 10000;
        a.each(function () {
            $(this).css({
                top: 0,
                left: 0,
                position: "absolute",
                zIndex: index--
            });
        });

        var now = 0;
        setInterval(function () {
            $(a[now]).fadeOut(function () {
                $(this).show().css("zIndex", index--);
            });

            now = now + 1 == max ? 0 : now + 1;
        }, 3500);
    });
});

// old files 

(function () {
    $.evalJSON = function (s) {
        if ($.type(s) != 'string' || !s.length) return null;
        return eval('(' + s + ')');
    };
})();

/** 用户 */
var User = {
    PostDir: "/Common/Ashx/Member/",
    ajaxPost: null,
    /// <summary>
    /// 登陆栏
    /// </summary>
    topbar: {
        notin: '<a href="javascript:;" onclick="User.OnPopLog()">登录</a> | <a href="http://my.baozang.com/signup/">注册</a>',
        hasin: '<span><a href="http://my.baozang.com/" title="进入我的用户中心">欢迎 {userid}, 进入我的用户中心 </a> <a href="javascript:void(0)" onclick="User.SingOut();">注销</a></span>',
        loading: 'loading...'
    },
    /// <summary>
    /// 检查是否已经登陆
    /// </summary>
    isSingIn: function () {
        $("#sign").html(User.topbar.loading);
        $.ajax({
            url: User.PostDir + "checkSign.ashx?n=" + Math.random(),
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                //alert(XMLHttpRequest.responseText);
                $("#sign").html(User.topbar.notin);
            },
            success: function (JsonData) {
                var json = $.evalJSON(JsonData)
                if (json.success == 1) {
                    $("#sign").html(User.topbar.hasin.replace("{userid}", json.BzUID));
                }
                else {
                    $("#sign").html(User.topbar.notin);
                }
            }
        });
    },
    /// <summary>
    /// 登陆
    /// </summary>
    /// <param name="options">Post的用户登陆数据{uin,upwd}</param>
    SingIn: function () {
        //alert(User.OnValid());
        if (User.OnValid()) {
            $(".loading").show();
            User.ajaxPost = $.ajax({
                url: User.PostDir + "signin.ashx?n=" + Math.random(),
                async: true,
                type: "POST",
                data: { username: $("#unpop").val(), password: $("#pswpop").val() },
                complete: function () {
                    $(".loading").hide();
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    $("#sign").html(User.topbar.notin);
                    alert(XMLHttpRequest.responseText);
                },
                success: function (resTxt) {
                    var json = $.evalJSON(resTxt);
                    if (resTxt == "" || resTxt.length == 0 || resTxt == null) {
                        alert("登录请求已取消");
                        return;
                    }
                    if (json.success == 1) {
                        $("#sign").html(User.topbar.hasin.replace("{userid}", json.BzUID));
                        $("#popLogin").find(".text").val("");
                        $("#cover2, #popLogin, .loading").hide();
                        $.cookie('uin', json.BzUID, { expires: 7, path: '/', domain: 'baozang.com', secure: false });
                    }
                    else {
                        alert(json.err);
                        $("#sign").html(User.topbar.notin);
                    }
                }
            });
        }

    },
    /// <summary>
    /// 退出
    /// </summary>
    SingOut: function (options) {
        $("#sign").html(User.topbar.loading);
        $.ajax({
            url: User.PostDir + "signout.ashx?n=" + Math.random(),
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest.responseText);
            },
            success: function (rssTxt) {
                if (rssTxt == "1") {
                    setTimeout(function () {
                        $("#sign").html(User.topbar.notin);
                    }, 50);
                }
                else {
                    alert("注销失败,请重试");
                }
            }
        });
    },

    OnPopLog: function () {
        var pageW = document.body.clientWidth;
        var pageH = document.body.clientHeight;
        var winW = $(window).width();
        var winH = $(window).height();
        var scrlL = $(document).scrollLeft();
        var scrlT = $(document).scrollTop();

        $("#cover2").css({
            "width": pageW,
            "height": pageH,
            "opacity": "0.5"
        }).show();

        $("#popLogin").css({
            "top": "150px",
            "left": parseInt((winW - $("#popLogin").width()) / 2)
        }).show();

        $(window).bind("resize scroll", function () {
            pageW = document.body.clientWidth;
            pageH = document.body.clientHeight;
            winW = $(window).width();
            winH = $(window).height();
            scrlL = $(document).scrollLeft();
            scrlT = $(document).scrollTop();

            $("#cover2").css({
                "width": pageW + scrlL,
                "height": pageH,
                "opacity": "0.5"
            });

            if (winH > ($("#popLogin").height() + 150)) {
                $("#popLogin").css({
                    "top": parseInt(scrlT) + 150,
                    "left": parseInt((winW - $("#popLogin").width()) / 2)
                });
            } else if (winH > ($("#popLogin").height())) {
                $("#popLogin").css({
                    "top": parseInt(scrlT) + (winH - parseInt($("#popLogin").height())) / 2,
                    "left": parseInt((winW - $("#popLogin").width()) / 2)
                });
            } else {
                $("#popLogin").css({
                    "top": parseInt(scrlT),
                    "left": parseInt((winW - $("#popLogin").width()) / 2)
                });
            }
        });

        $(".cls, #cover2").click(function () {
            if (User.ajaxPost) {
                User.ajaxPost.abort();
            }
            $("#popLogin").find(".text").val("");
            $("#cover2, #popLogin, .loading").hide();
        });

        return false;

    },
    checkEnter: function (e) {
        var keycode;
        if (window.event) {
            keycode = e.keyCode;
        } else if (e.which) {
            keycode = e.which;
        }
        if (keycode != 13) return;
        $("#submit").trigger("click");
    },
    OnValid: function () {
        var usn = $("#unpop").val().trim();
        var psw = $("#pswpop").val().trim();
        if (usn == "" || psw == "") {
            alert("用户名或密码不能为空!");
            return false;
        }
        return true;
    }
};

function pos(obj) {
    $(".hasMenu").removeClass("selected");
    obj.addClass("selected");
    p = obj.position();
    $(".submenu").hide();
    navId = obj.attr("id");
    $("#sub_" + navId).show();
}

function globel_header() {
    pos($("#menu1"));
    $(".hasMenu").hover(function () {
        pos($(this));
        if ($(this).attr("id") != "menu1") {
            $("#menu1").addClass("currMenu");
        } else {
            $("#menu1").removeClass("currMenu");
        }
    });
    $(".srcInput input").focus(function () {
        $(this).parent().removeClass("addBg");
    }).blur(function () {
        if ($(this).val() != "") { return; }
        $(this).parent().addClass("addBg");
    });
}
