/**
 * Created by nvting on 2014/11/27.
 */
//第三方页面集成

(function() {
    if (checkBrowser()) {
        var url = 'http://ydclient.voicecloud.cn/joker/resetIframe.html'; //测试环境地址， 正式上线需变更
        var load = false;
        var iframe = document.createElement("iframe");
        iframe.style.display = 'none';
        document.getElementsByTagName('body')[0].appendChild(iframe);

        window.onload = function() {
            load = true;
            window.lingxi_resetIframe();
        };
        window.lingxi_resetIframe = function(str) { //@喜马拉雅 加载更多完成时候，需要调用该函数
            if (str == undefined) {
                iframe.src = url + "?height=" + document.body.offsetHeight;
            } else {
                if (str == 'onload') {
                    iframe.src = url + "?onload=true&height=" + document.body.offsetHeight;
                } else { // str = 2000 ; str = '2000'
                    iframe.src = url + "?height=" + str;
                }
            }
        };

        window.lingxi_resetIframe('onload'); //新页面加载
        sendmsg();
    }

    function sendmsg() {
        if (load) return;
        setTimeout(function() {
            window.lingxi_resetIframe();
            sendmsg();
        }, 1000);
    }

    function checkBrowser() {
        var ret = false;
        try {
            //检测平台是否是安卓灵犀
            (browserView.isSupportRecognize()) && (ret = "A");
        } catch (e) {}
        try {
            //检测平台是否是iPhone灵犀
            var str = navigator.userAgent;
            if (str.indexOf("iPhone") > 0 && str.indexOf("LingXi") > 0) {
                ret = "I";
            }
        } catch (e) {}
        return ret;
    }
})();
(function($){
    $.fn.autoTextarea = function(options) {
        var defaults={
            maxHeight:null,//文本框是否自动撑高，默认：null，不自动撑高；如果自动撑高必须输入数值，该值作为文本框自动撑高的最大高度
            minHeight:$(this).height() //默认最小高度，也就是文本框最初的高度，当内容高度小于这个高度的时候，文本以这个高度显示
        };
        var opts = $.extend({},defaults,options);
        return $(this).each(function() {
            $(this).bind("paste cut keydown keyup focus blur change",function(){
                var height,style=this.style;
                this.style.height =  opts.minHeight + 'px';
                if (this.scrollHeight > opts.minHeight) {
                    if (opts.maxHeight && this.scrollHeight > opts.maxHeight) {
                        height = opts.maxHeight;
                        style.overflowY = 'scroll';
                    } else {
                        height = this.scrollHeight;
                        style.overflowY = 'hidden';
                    }
                    style.height = height  + 'px';
                }
            });
        });
    };
})(jQuery);

$.strformat=function(){
    var format = /\{([\d\w\.]+)\}/g;
    var args = Array.prototype.slice.call(arguments),
        v;
    str = args.shift() + '';
    if (args.length == 1 && typeof(args[0]) == 'object') {
        args = args[0];
    }
    format.lastIndex = 0;
    return str.replace(format, function(m, n) {
        v = args[n];
        return v === undefined ? m : v;
    });
}
function parseAvatar(id, pic){
    if (!id || !pic || pic === 'null') {  // ''|'null'|null 三种都要判断
        return 'http://static.qiushibaike.com/images/thumb/missing.png'
    }
    return $.strformat(
        "http://pic.qiushibaike.com/system/avtnew/{0}/{1}/medium/{2}",
        parseInt(id / 10000), id, pic
    )
}

function check_speed_level(){
    if(!(window.performance && window.performance.timing)){
        return;
    }
    var resp_time = window.performance.timing.responseEnd - window.performance.timing.domainLookupStart ;
    var span = [50,100,150,200,250,300,350,400,500,550,600,650,700,750,800,850,900,950,1000,10000];
    var speed_level = 99;
    if(resp_time > 0){
        for(var i=0;i<span.length;i++){
            if(resp_time <span[i]){
                speed_level = i;
                break;
            }
        }
    }
    return speed_level;
    //window._hmt = _hmt || [];
    //_hmt.push(['_trackEvent', "s", "spd_l"+speed_level, null,resp_time]);
}

/*
function try_download_apk(){
    //带尾巴，速度快的用户，android用户, 从gxws来的用户
    var speed_level = check_speed_level();
    if(speed_level<=5 && 
            !$.readCookie('apk_downloaded') &&
            qblib.urlParam('ref')=="gxws" && 
            !/ipad|iphone|mac/i.test(navigator.userAgent)){
        var iFrame = document.createElement("IFRAME");
        iFrame.setAttribute("src", "http://static.qiushibaike.com/qiushibaike_7.3.0_touch_down.apk")
        document.body.appendChild(iFrame); 
        $.setCookie('apk_downloaded','true',{})
        window._hmt = _hmt || [];
        _hmt.push(['_trackEvent', "a", "apk_download"]);
    }
}
*/

function showGameEntryRedFlag(){
    var game_entry = $(".game-entry");
    if(game_entry.length>0){
        if(!qblib.localstore.get('game_entry_clicked')){
            game_entry.find(".red-flag").css("display","inline-block")
            game_entry.click(function(){
                qblib.localstore.set("game_entry_clicked",'true')
            })
        }
        game_entry.on("touchstart",function(){
            window._hmt = _hmt || [];
            _hmt.push(['_trackEvent', "a", "game_entry_click"]);
        });
    }
}

function initeScroll() {
    this.pageNo = 1;
    this.pageSize = 20;
    this.totalCount = -1;
    this.isLoading = false;
    this.param = {};
};

initeScroll.prototype = {
    constructor: initeScroll,

    reset: function () {
        this.pageNo =1;
        this.pageSize = 20;//这里的分页是30
        this.totalCount = -1;
    },

    isScrollBottom: function() {
        var self = this;
        $(window).scroll(function() {
            var containerHeight = $(document).height(),
                scrollTop = $(window).scrollTop(),
                windowHeight = $(window).height();
            if (containerHeight - scrollTop - windowHeight < 1550) {
                self.loadMore();
            }

        })
    },

    loadMore: function (param) {
        var self = this;
        if (self.canBeLoad()) {
            self.pageNo++;
            self.isLoading = true;
            //加载并渲染
            self.loadAndRender();
        }
    },
    getUrlParam : function(paramName,url){
        url = url ? url : window.location.href;
        var reg = new RegExp('(\\?|&)' + paramName + '=([^&?]*)', 'i');
        var arr = url.match(reg);
        return arr ? arr[2] : null;
    },
    loadAndRender: function(){
        var url = window.location.href;
        var id = $("#comment_article_id").val();
        var list = this.getUrlParam("list");
        var s = this.getUrlParam("s");
        var p = $("#qiushi_comments_"+id).find(".comment-tips");
        var self = this;
        p.show();
        $.ajax({
            //正式拉取数据地址
            url:"/commentpage/"+id+"?list="+self.getUrlParam("list")+"&s="+self.getUrlParam("s")+"&page="+self.pageNo,
            cache:false,
            dataType:"json",
            success: function(r){
                //已经load完了
                self.isLoading = false;
                //出错时的情况
                self.totalCount = r.comments.total;
                self.pageSize= r.comments.count>self.pageSize?r.comments.count:self.pageSize;
                var render = template.compile($('#comments-render').html());
                template.helper("parseAvatar",parseAvatar);
                template.helper("content",function(c){
                    var c = template.utils.$escape(c);
                    return c.replace(/(\\n)/g,"<br>");
                });
                var html = render(r);
                p.hide().before(html);
                window.myCommentsCache = typeof(window.myCommentsCache) == "undefined" ? '' : window.myCommentsCache;
                if(self.pageNo*self.pageSize>=self.totalCount && window.myCommentsCache) {
                    p.before(window.myCommentsCache);
                    window.myCommentsCache = '';
                }
            }
        });
    },
    canBeLoad: function () {
        if (this.isLoading) {
            return false;
        } else {
            return this.isAllLoad();
        }
    },
    isAllLoad: function () {
        var pageNo = this.pageNo+1 ;
        var r = (this.totalCount == -1 || pageNo <= Math.ceil(this.totalCount/this.pageSize));
        return r;
    },
    loadComplete: function () {
        this.isAllLoad();
    }
};




$(function(){
    if($(".isCommentPage").length>0)
    {
        window.initescroll = new initeScroll();
        window.initescroll.isScrollBottom();
        window.initescroll.loadAndRender();
        $("body").css("background","f5f5f5");

    }

    qblib.setDownloadUrl();

    $(window).resize(function(){
        if( $(window).width()> $(window).height())
        {
            $(".foot-content").hide();
        }
        else
        {
            $(".foot-content").show();
        }
    })
    /* 投稿页面修改*/
    $("#article_picture").change(function()
    {
        if(this.value)
            $("#article_picture_tips").html(this.value);
        else
            $("#article_picture_tips").html("未选择文件");
    });
    if($("#isAddPage").length>0)
    {
        $("body").css("background-color","#e5e5e5");
    }


    showGameEntryRedFlag();

    //var weekDay = (new Date()).getDay();
    //if (weekDay == 3 || weekDay == 4 || weekDay == 5) {
    //    $('a[data-role="xiaoji"]').show();
    //} else {
    //    var rnd = Math.round(Math.random());
    //    if (rnd == 1) {
    //        $('a[data-role="xiaoji"]').show()
    //    } else {
    //        $('a[data-role="remix"]').show();
    //    }
    //}
    $('a[data-role="xiaoji"]').show();

});




