(function(a, b) {
    $window = a(b),
        a.fn.lazyload = function(c) {
            function f() {
                var b = 0;
                d.each(function() {
                    var c = a(this);
                    if (e.skip_invisible && !c.is(":visible")) return;
                    if (!a.abovethetop(this, e) && !a.leftofbegin(this, e)) if (!a.belowthefold(this, e) && !a.rightoffold(this, e)) c.trigger("appear");
                    else if (++b > e.failure_limit) return ! 1
                })
            }
            var d = this,
                e = {
                    threshold: 0,
                    failure_limit: 0,
                    event: "scroll",
                    effect: "show",
                    container: b,
                    data_attribute: "original",
                    skip_invisible: !0,
                    appear: null,
                    load: null
                };
            return c && (undefined !== c.failurelimit && (c.failure_limit = c.failurelimit, delete c.failurelimit), undefined !== c.effectspeed && (c.effect_speed = c.effectspeed, delete c.effectspeed), a.extend(e, c)),
                $container = e.container === undefined || e.container === b ? $window: a(e.container),
            0 === e.event.indexOf("scroll") && $container.bind(e.event,
                function(a) {
                    return f()
                }),
                this.each(function() {
                    var b = this,
                        c = a(b);
                    b.loaded = !1,
                        c.one("appear",
                            function() {
                                if (!this.loaded) {
                                    if (e.appear) {
                                        var f = d.length;
                                        e.appear.call(b, f, e)
                                    }
                                    a("<img />").bind("load",
                                        function() {
                                            c.hide().attr("src", c.data(e.data_attribute))[e.effect](e.effect_speed),
                                                b.loaded = !0;
                                            var f = a.grep(d,
                                                function(a) {
                                                    return ! a.loaded
                                                });
                                            d = a(f);
                                            if (e.load) {
                                                var g = d.length;
                                                e.load.call(b, g, e)
                                            }
                                        }).attr("src", c.data(e.data_attribute))
                                }
                            }),
                    0 !== e.event.indexOf("scroll") && c.bind(e.event,
                        function(a) {
                            b.loaded || c.trigger("appear")
                        })
                }),
                $window.bind("resize",
                    function(a) {
                        f()
                    }),
                f(),
                this
        },
        a.belowthefold = function(c, d) {
            var e;
            return d.container === undefined || d.container === b ? e = $window.height() + $window.scrollTop() : e = $container.offset().top + $container.height(),
            e <= a(c).offset().top - d.threshold
        },
        a.rightoffold = function(c, d) {
            var e;
            return d.container === undefined || d.container === b ? e = $window.width() + $window.scrollLeft() : e = $container.offset().left + $container.width(),
            e <= a(c).offset().left - d.threshold
        },
        a.abovethetop = function(c, d) {
            var e;
            return d.container === undefined || d.container === b ? e = $window.scrollTop() : e = $container.offset().top,
            e >= a(c).offset().top + d.threshold + a(c).height()
        },
        a.leftofbegin = function(c, d) {
            var e;
            return d.container === undefined || d.container === b ? e = $window.scrollLeft() : e = $container.offset().left,
            e >= a(c).offset().left + d.threshold + a(c).width()
        },
        a.inviewport = function(b, c) {
            return ! a.rightofscreen(b, c) && !a.leftofscreen(b, c) && !a.belowthefold(b, c) && !a.abovethetop(b, c)
        },
        a.extend(a.expr[":"], {
            "below-the-fold": function(c) {
                return a.belowthefold(c, {
                    threshold: 0,
                    container: b
                })
            },
            "above-the-top": function(c) {
                return ! a.belowthefold(c, {
                    threshold: 0,
                    container: b
                })
            },
            "right-of-screen": function(c) {
                return a.rightoffold(c, {
                    threshold: 0,
                    container: b
                })
            },
            "left-of-screen": function(c) {
                return ! a.rightoffold(c, {
                    threshold: 0,
                    container: b
                })
            },
            "in-viewport": function(c) {
                return ! a.inviewport(c, {
                    threshold: 0,
                    container: b
                })
            },
            "above-the-fold": function(c) {
                return ! a.belowthefold(c, {
                    threshold: 0,
                    container: b
                })
            },
            "right-of-fold": function(c) {
                return a.rightoffold(c, {
                    threshold: 0,
                    container: b
                })
            },
            "left-of-fold": function(c) {
                return ! a.rightoffold(c, {
                    threshold: 0,
                    container: b
                })
            }
        })
})(jQuery, window);
function getBrowser() {
    var browser = {
            msie: false,
            firefox: false,
            opera: false,
            safari: false,
            chrome: false,
            netscape: false,
            appname: '未知',
            version: ''
        },
        userAgent = window.navigator.userAgent.toLowerCase();
    if (/(msie|firefox|opera|chrome|netscape)\D+(\d[\d.]*)/.test(userAgent)) {
        browser[RegExp.$1] = true;
        browser.appname = RegExp.$1;
        browser.version = RegExp.$2;
    } else if (/version\D+(\d[\d.]*).*safari/.test(userAgent)) {
        browser.safari = true;
        browser.appname = 'safari';
        browser.version = RegExp.$2;
    }
    return browser;
}
window.ppAjax = {
    alert: function(data) {
        window.ppData = data = toJson(data);
        if (window.ppExit) return;
    },
    submit: function(selector, callback, errCallback) {
        $(selector).submit(function() {
            ppAjax.post($(this).attr("action"), $(this).serialize(), callback, errCallback);
            return false;
        });
    },
    post: function(url, param, callback, errCallback) {
        $.ajax({
            type: "POST",
            cache: false,
            url: url,
            data: param,
            success: callback,
            error: function(html) {
                //console.log(html)
                if(html.status == 401) {
                    layer.msg('请登录', function () {
                        window.location.href = '/login?referer=' + window.location.href;
                        //window.location.reload();
                    });
                    return;
                }

                content = "提交数据失败，代码:" + html.status + "，请稍候再试";
                if (typeof html.responseJSON == 'string') {
                    content = html.status + ' ' + html.statusText
                } else if(typeof html.responseJSON.errors !== 'undefined' && html.responseJSON.errors !== null) {
                    data = html.responseJSON.errors
                    content = '';

                    Object.keys(data).map(function(key, index) {
                        value = data[key];

                        content += '<span style="color: #e74c3c">' + value[0] + '</span><br>';
                    });

                } else if(typeof html.responseJSON.message !== 'undefined' && html.responseJSON.message !== '') {
                    content = html.responseJSON.message
                }
                layer.alert(content, {
                    icon: 0,
                    shade: 0.6
                });
                if (typeof errCallback === 'function') errCallback(html.responseJSON)
            }
        });
    },
    get: function(url, param, callback, isAsync) {
        isAsync = typeof isAsync !== 'undefined' ? isAsync : true;
        $.ajax({
            type: "GET",
            cache: false,
            async: isAsync,
            url: url,
            data: param,
            success: callback,
            error: function(html) {
                //console.log(html)
                content = "提交数据失败，代码:" + html.status + "，请稍候再试";
                if (typeof html.responseJSON == 'string') {
                    content = html.status + ' ' + html.statusText
                } else if(typeof html.responseJSON.errors !== 'undefined' && html.responseJSON.errors !== null) {
                    data = html.responseJSON.errors
                    content = '';

                    Object.keys(data).map(function(key, index) {
                        value = data[key];

                        content += '<span style="color: #e74c3c">' + value[0] + '</span><br>';
                    });

                } else if(typeof html.responseJSON.message !== 'undefined' && html.responseJSON.message !== '') {
                    content = html.responseJSON.message
                }
                layer.alert(content, {
                    icon: 0,
                    shade: 0.6
                });
            }
        });
    },
};
function toJson(data) {
    var json = {};
    try {
        json = eval("(" + data + ")");
        if (json.kp_error) {
            ppAjax.debug(json);
            window.ppExit = true;
        } else {
            window.ppExit = false;
        }
    } catch(e) {
        alert(data);
    }
    return json;
}
$.cookie = function(name, value, options) {
    if (typeof value != 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        var path = options.path ? '; path=' + options.path: '';
        var domain = options.domain ? '; domain=' + options.domain: '';
        var secure = options.secure ? '; secure': '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
$.fn.scrollFix = function(fix, callback) {
    var position = function(element) {
        var top = element.position().top + fix;
        var isHandled = false;
        $(window).scroll(function() {
            var scrolls = $(this).scrollTop();
            if (scrolls > top) {
                if(!isHandled) callback(element);
                isHandled = true;
                // if (window.XMLHttpRequest) {
                //     element.css({
                //         'z-index': 999,
                //         position: "fixed",
                //         top: 0
                //     });
                // } else {
                //     element.css({
                //         top: scrolls
                //     });
                // }
            }else {
                if(isHandled) callback(element);
                isHandled = false;
                // element.css({
                //     position: pos,
                //     top: top
                // });
            }
        });
    };
    return $(this).each(function() {
        position($(this));
    });
};
$(document).ready(function() {
    $('#header').scrollFix(0,function (element) {
        var height = element.height();
        var fixclass = 'fix-header';
        if (!element.hasClass(fixclass)) {
            element.addClass(fixclass);
            element.before('<div class="js-header-padding" style="width:100%;height:' + height + 'px;"></div>');
        } else {
            element.removeClass(fixclass);
            $('.js-header-padding').remove();
        }
    });
    /*搜索框*/
    var is_active = $("#search_cids a.active").length;
    if (!is_active) {
        $("#search_cids a:first").addClass('active');
    }
    var select_width = $("#search_input_select").width();
    $("#search_cids.dropdown-menu").css({
        'width': select_width,
        'min-width': select_width
    });
    $("#select_cid").text($("#search_cids a.active").text());
    $("#search_mid").val($("#search_cids a.active").attr('mid'));
    $("#search_cids a").click(function() {
        $("#select_cid").text($(this).text());
        $("#search_mid").val($(this).attr('mid'));
    });
    /*二级菜单*/
    $('#navbar-nav li.dropdown').mouseover(function() {
        $(this).addClass('open');
    }).mouseout(function() {
        $(this).removeClass('open');
    });
    $("#navbar-nav .dropdown-toggle").click(function(e) {
        e.stopPropagation();
        if ($(this).attr('href')) window.location.href = $(this).attr('href');
    });
    $("#search_form").submit(function() {
        var keyword = $("#search_keyword").val();
        if (!keyword) {
            layer.tips('搜索词不能为空！', '#search_keyword', {
                tips: 3
            });
            return false;
        }
    });
    $('img[data-original]').lazyload();
    window.ctf_form_one = false;
    $("#ctf_submit").click(function() {
        if (window.ctf_form_one) {
            return false;
        }
        if ($("#ctf_content").length < 1) {
            return false;
        }
        var cont = $("#ctf_content");
        if ($("#ctf_author").length < 1) {
            var pp_author = '游客';
        } else {
            var pp_author = $("#ctf_author").val();
        }
        var browser = getBrowser();
        if (!browser.firefox) {
            $("#ctf_submit").attr("disabled", "disabled");
            setTimeout(function() {
                    if (!browser.firefox) $("#ctf_submit").removeAttr("disabled");
                    window.ctf_form_one = false;
                },
                2000);
        }
        if (!pp_author) {
            layer.msg('请填写昵称！',
                function() {});
            return false;
        }
        if (cont.val().length < 6) {
            layer.msg('评论内容太短至少6字符！',
                function() {});
            return false;
        }
        window.ctf_form_one = true;
        var _form = $('#ctf_form');
        $.post(_form.attr("action"), _form.serialize(),
            function(data) {
                try {
                    console.log(data);
                    var json = eval("(" + data + ")");
                    if (json.err == 0) {
                        layer.msg(json.msg);
                        cont.val('');
                        setTimeout(function() {
                                location.reload();
                            },
                            1000);
                    } else {
                        layer.msg(json.msg,
                            function() {});
                        window.ctf_form_one = false;
                    }
                } catch(e) {}
            });
        return false;
    }); (function() {
        var Uarr = location.href.split('#');
        if (Uarr[1] == "ctf") $("html,body").animate({
            scrollTop: $("#ctf").offset().top
        });
    })();
    $("#artbody img").addClass("img-responsive");
    $("#media .item").hover(function() {
            $(this).addClass("item-cur");
        },
        function() {
            $(this).removeClass("item-cur");
        });
    $(window).scroll(function() {
        if ($(window).scrollTop() > 100) {
            $("#back-to-top").fadeIn(1500);
        } else {
            $("#back-to-top").fadeOut(1500);
        }
    });
    $("#back-to-top").click(function() {
        $('body,html').animate({
                scrollTop: 0
            },
            1000);
        return false;
    });
});

(function($, window, document, undefined) {
    var ppAjax = window.ppAjax;
    var layer = window.layer;
    var topupOrderUrl = window.topupOrderUrl;
    var memurl = window.memurl;

    // 下单并使用积分立即支付
    window.checkPoint = function (usePoint, price, callback) {
        usePoint = typeof usePoint !== 'undefined' ? usePoint : 0;
        // todo
        canOrder = false;
        if (usePoint == 1) {
            accountApiUrl = window.accountApiUrl;
            // 检查余额是否足够
            // 如果足够，继续执行
            // 如果不足，提示去充值，附带充值链接
            ppAjax.get(accountApiUrl, {}, function (res) {
                if (res.code == 1) {
                    if (parseFloat(res.data.money) < parseFloat(price)) {
                        jumpUrl = res.url ? res.url : topupOrderUrl +'?price='+ (price - res.data.money) + '#main';
                        content = '学币不足，' + '<a href="' + jumpUrl + '" target="_blank" style="color:#00aa88;"> 点击跳转到充值页面 </a>'
                        layer.open({
                            title: ['友情提醒', 'font-weight:bold;color:green'],
                            type: 1,
                            shadeClose: true,
                            content: "<p class='alert text-danger'>" + content + "</p>"
                        });
                        canOrder = false;
                        // todo
                        // canOrder = true;
                    }else {
                        canOrder = true;
                    }
                } else {
                    canOrder = false;
                    layer.msg(res.msg, {
                        icon: 1,
                        time: 1500
                    }, function () {
                        window.location.href = '/login?referer=' + window.location.href;
                        //window.location.reload();
                    });
                }
                if(canOrder) {
                    callback();
                }

            });
        }else {
            canOrder = true;
            if(canOrder) {
                callback();
            }
        }

        return canOrder;
    };

    action = function(url, param, actionName, needAppend,method) {
        actionName = typeof actionName !== 'undefined' ? actionName : '操作';
        method = typeof method !== 'undefined' ? method : 'POST';
        needAppend = typeof needAppend !== 'undefined' ? needAppend : true;
        //if(usePoint && ! window.checkPoint(usePoint, price)) {
        //    return false;
        //}
        // 提交订单， 当usePoint = 1时, 后台业务逻辑为:'下单'+'支付'
        // 当usePoint = 0时， 后台业务逻辑为:只下单并跳转到支付页面
        if(method.toUpperCase() == 'GET') {
            ppAjaxAction = ppAjax.get
        } else {
            ppAjaxAction = ppAjax.post
        }
        layer.open({
            title: ['友情提醒', 'font-weight:bold;color:green'],
            btn:['确认','取消'],
            yes:function(index,layero){
                if(needAppend) {
                    var btn = layero.find('.layui-layer-btn'); //按钮组
                    var body = layero.find('.layui-layer-content'); //内容区
                    btn.hide();
                    body.append("<br/>请稍候...若无响应请到<a class='text-info' href="+memurl+" target='_blank'>会员中心</a>查看是否"+ actionName +"成功！");
                }
                ppAjaxAction(url, param, function (res) {
                    if (res.code == 1) {
                        if(jumpUrl = res.url) {
                            //content = res.msg + '<br><a href="' + jumpUrl + '" target="_blank" style="color:#00aa88;"> 点击进行'+ actionName +'操作</a>'
                            content = res.msg;
                            layer.close(index);
                            layer.open({
                                title: ['友情提醒', 'font-weight:bold;color:green'],
                                btn:['确认','取消'],
                                type: 1,
                                yes:function(index,layero){
                                    window.location.href = jumpUrl;
                                },
                                cancel:function(index){
                                    layer.close(index);
                                },
                                shadeClose: true,
                                content: "<p class='alert text-danger'>"+ content +"</p>"
                            });
                        } else {
                            layer.msg(res.msg, {icon: 1, time: 2000, shade: 0.6}, function () {
                                window.location.reload();
                            });
                        }
                    } else {
                        layer.msg(res.msg, function () {
                            //window.location.reload();
                        });
                    }
                });

            },
            cancel:function(index){
                layer.close(index);
            },
            shadeClose: true,
            content: '确认'+ actionName +'？'
        });
    };

    actionAndOpen = function(url, param, actionName, needAppend,method) {
        actionName = typeof actionName !== 'undefined' ? actionName : '操作';
        method = typeof method !== 'undefined' ? method : 'POST';
        needAppend = typeof needAppend !== 'undefined' ? needAppend : true;
        //if(usePoint && ! window.checkPoint(usePoint, price)) {
        //    return false;
        //}
        // 提交订单， 当usePoint = 1时, 后台业务逻辑为:'下单'+'支付'
        // 当usePoint = 0时， 后台业务逻辑为:只下单并跳转到支付页面
        if(method.toUpperCase() == 'GET') {
            ppAjaxAction = ppAjax.get
        } else {
            ppAjaxAction = ppAjax.post
        }

        layer.open({
            title: ['友情提醒', 'font-weight:bold;color:green'],
            btn: ['确认', '取消'],
            yes: function (index, layero) {
                if(needAppend) {
                    var btn = layero.find('.layui-layer-btn'); //按钮组
                    var body = layero.find('.layui-layer-content'); //内容区
                    btn.hide();
                    body.append("<br/>请稍候...若无响应请到<a class='text-info' href="+memurl+" target='_blank'>会员中心</a>查看是否"+ actionName +"成功！");
                }
                ppAjaxAction(url, param, function (res) {
                    if (res.code == 1) {
                        layer.close(index);
                        if (jumpUrl = res.url) {
                            content = res.msg;
                            // window.location.href = jumpUrl;
                            window.open(jumpUrl)
                            layer.confirm('请在弹出的窗口中完成' + actionName, {
                                btn: ['已' + actionName, '取消'], icon: 3, title: '提示'
                            }, function (index) {
                                window.location.reload();
                            });
                        } else {
                            layer.msg(res.msg, {icon: 1, time: 2000, shade: 0.6}, function () {
                                window.location.reload();
                            });
                            // window.location.reload();
                        }
                    } else {
                        layer.msg(res.msg, function () {
                            // layer.close(index);
                            // window.location.reload();
                        });
                    }

                });
            },
            cancel:function(index){
                layer.close(index);
            },
            shadeClose: true,
            content: '确认'+ actionName +'？'
        });
    };
})(jQuery, window, document);

