/// 列表页googleAD的回调函数以及参数
var google_afs_request_done = function(google_ads){ }
,    google_afs_qry_lnk = ""
,    google_afs_qry_ctxt = ""
,    google_afs_query = ""
,    google_afs_ad = 'w0' // specify the number of ads you are requesting
,    google_afs_client = "ganji-dir" // substitute your client ID
,    google_afs_channel = "" // enter your comma-separated channel IDs
,    google_afs_adpage = ""
,    google_afs_ie = 'utf8' // select input encoding scheme
,    google_afs_oe = 'utf8' // select output encoding scheme
,    google_afs_adsafe = 'medium' // specify level for filtering non-family-safe ads
,    google_afs_adtest = 'off' // ** set parameter to off before launch to production
,    google_afs_hl = 'zh-CN' // enter your interface language if not English
,    google_afs_gl = 'cn'
;

/// 详情页googleAD的回调函数以及参数
var google_ad_request_done = function(google_ads){ }
,    google_ad_client = ""
,    google_ad_output = 'js'
,    google_ad_type = 'text'
,    google_gl = 'CN'
,    google_language = 'zh-CN'
,    google_encoding = 'utf8'
,    google_safe = 'high'
,    google_adtest = 'off'
,    google_ad_section = 'default'
,    google_feedback = 'on'
,    google_ad_channel = ''
,    google_max_num_ads = 6
;


/************************************************************************************************/
/*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^以上GOOGLEAD必须参数^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/
/************************************************************************************************/

(function(){
    /**
     * googleAD样式1
     */
    var initSp0 = function(){ /// 列表页(求职，招聘)-已经启用
            google_ad.wide_ad_s = "<div class='GcnAD_title'><a target='_blank' href='http://adwords.google.com/'>赞助商链接</a></div>";
            google_ad.fetchAd = function(ad, index){
                return '<dl class="GcnAD_cont">' + 
                     '<dt>' + 
                       '<a onmouseout="window.status=\'\';return true" onmouseover="window.status=\'http://' + ad.visible_url+'\';return true" target="_blank" href="' + ad.url + '">' + ad.line1 + '</a>' +
                     '</dt>&nbsp;' +
                     '<dd>' +
                       '<a target="_blank" href="' + ad.url + '">' + ad.visible_url + '</a>&nbsp;' + ad.line2 + 
                     '</dd>'+
                   '</dl>';
            };
            google_ad.wide_ad_e += "";
        }
    ,    initSp2 = function(){ /// 详情页-已经启用
            google_ad.wide_ad_s = "<div class='hackDiv'>&nbsp;</div><div class='GcnAD_detail_title'><a href='http://adwords.google.com/' target='_blank' >Google提供的广告</a></div>";
            google_ad.isValidAd = function(ad){
                return (GJ.isObject(ad));
            };
            google_ad.fetchAd = function(ad, index){
                var extend_class = (index == 1) ? ' nbod' : '';
                return '<dl class="GcnAD_cont' + extend_class + '">' + 
                         '<dt><a href="' + ad.url + '" target="_blank" >' + ad.line1 + '</a></dt>' +
                         '<dd>' + ad.line2  + '&nbsp;&nbsp;' + ad.line3 + '</dd>' +
                         '<dd><a class="GcnAD_adds" target="_blank" href="' + ad.url + '">' + ad.visible_url + '</a></dd>' +
                       '</dl>';
            };
        }
    ,    initSp3 = function(){ /// 列表页（服务）-已经启用
            google_ad.fetchTopAd = function(ad){
                return '<dl class="list">' +
                            '<dt><a href="' + ad.url + '" target="_blank"><img src="http://sta.ganjistatic1.com/src/image/service/google_ads.jpg"></a></dt>' +
                            '<dd>' +
                                '<p><a class="ft-14" onmouseout="window.status=\'\';return true" onmouseover="window.status=\'http://' + ad.visible_url+'\';return true" href="' + ad.url + '" target="_blank">' + ad.line1 + '</a> </p>' +
                                '<p class="fc-gray">' + ad.line2 + '</p>' +
                                '<p class="fc-gray"><a class="ft-14" href="' + ad.url + '" target="_blank">' + ad.visible_url + '</a></p>' +
                            '</dd>' +
                        '</dl>';
            };
        }
    ,    initSp4 = function(){ }
    ,    initSp5 = function(){ }
    ;
/******************************************************************************************************/
/*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<以上为预定义好的5套占位模版>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>*/
/******************************************************************************************************/

    GJ.googleAdPageType = {
        list : 1,
        detail : 2
    };
    var topAds = [], belowAds = [], showLog = true;
    var google_ad = {
        page_type : GJ.googleAdPageType.list,
        endum_top_ads : '',
        isSp : 1,
        afs_channel_id : 0,
        client_id : 'ganji-dir',
        keyword : '',
        top_count : 0,
        below_count : 0,
        top_div_id : 'GcnADId1',
        below_div_id : 'GcnADId2',
        wide_ad_s : "<div class='GcnAD_list'><div class='GcnAD_title'><a target='_blank' href='http://adwords.google.com/'>赞助商链接</a></div>",
        wide_ad_e : "</div>",

        detail_afc_client_id : 'pub-1496944590674366',
        detail_afc_count : 6,
        detail_afc_channel_id : '',
        isValidAd : function(ad){
            return (GJ.isObject(ad) && ad.type == "text/wide");
        },
        isTopValidAd : function(ad){
            return this.isValidAd(ad);
        },
        isBelowValidAd : function(ad){
            return this.isValidAd(ad);
        },
        fetchAd : function(ad, index){
            return '<p>' + 
                   '<a onmouseout="window.status=\'\';return true" onmouseover="window.status=\'http://' + ad.visible_url + '\';return true" target="_blank" href="' + ad.url + '">' +
                     replace_data(ad.line1) +
                   '</a>&nbsp; ' +
                   '<a target="_blank" href="' + ad.url + '">' +
                     replace_data(ad.visible_url ) +
                   '</a>&nbsp;' +
                     replace_data(ad.line2) +
                 '</p>';
        },
        renderAd : function(divId, ad){
            var o = document.getElementById(divId);
            if(o){
                o.innerHTML = this.wide_ad_s + ad + this.wide_ad_e;
                o.style.display = 'block';
            }
        },
        fetchTopAd : function(ad, index){
            return this.fetchAd(ad, index);
        },
        fetchBelowAd : function(ad, index){
            return this.fetchAd(ad, index);
        }
    };

    var getPageNum = function(){
        var url = window.location.href;
        var pattern = /\/f(\d+)\//;
        var matches = url.match(pattern);
        if(matches && matches[1]){
            var n = (matches[1]%50 == 0) ? 50 : 32;
            var pageNum = Math.floor(matches[1]/n) + 1;
            return pageNum;
        }
        return 1;
    },
    
    replace_data = function(str){
        return str.replace(/<\/?.+?>/g, "");
    },
    
    setGoogleParam = function(){
        google_ad.top_count = new Number(google_ad.top_count);
        google_ad.below_count = new Number(google_ad.below_count);

        var totalCount = google_ad.top_count + google_ad.below_count;

        if (totalCount > 0) {
            ///afc vars{
            google_ad_client = google_ad.detail_afc_client_id;
            google_ad_channel = google_ad.detail_afc_channel_id;
            google_max_num_ads = google_ad.detail_afc_count;
            ///}afc vars

            ///afs vars{
            google_afs_qry_lnk = google_ad.keyword;
            google_afs_query = google_ad.keyword;
            if(isPromotedAds()){
                google_afs_ad = 'p' + google_ad.top_count + 'n' + totalCount;
                google_ad.isTopValidAd = function(ad){
                    return ad.position == "Top";
                };
                google_ad.isBelowValidAd = function(ad){
                    return true;
                };
            }else{
                google_afs_ad = 'w' + totalCount;
            }
            google_afs_client = google_ad.client_id;
            google_afs_channel = google_ad.afs_channel_id;
            google_afs_adpage = getPageNum();
            ///}afs vars
        }
    },

    /**
     * 是否是类似详情页页面的AD
     */
    isShowAfc = function(){
        return (google_ad.page_type == GJ.googleAdPageType.detail);
    },
    
    /**
     * 是否是promotion AD
     */
    isPromotedAds = function(){
        return (google_ad.endum_top_ads == 'promoted');
    },

    requestAFC = function(){
        google_ad.isValidAd = function(ad){
            return (GJ.isObject(ad));
        };
        google_ad_request_done = request_done;
        document.write("<script type='text/javascript' src='http://pagead2.googlesyndication.com/pagead/show_ads.js'></script>");
    },

    request_done = function(google_ads){
        var googleADCount = google_ads.length;
        if(showLog){
            GJ.log('googleADCount:'+googleADCount);
        }
        for(var i = 0; i < googleADCount; i++){
          if(!GJ.isUndefined(google_ads[i])){
            if (topAds.length < google_ad.top_count && google_ad.isTopValidAd(google_ads[i])){
                topAds.push(google_ads[i]);
            }else if(google_ad.isBelowValidAd(google_ads[i])){
                belowAds.push(google_ads[i]);
            }
          }
        }
        var requestCount = topAds.length + belowAds.length
        ,   needCount = google_ad.top_count + google_ad.below_count
        ;
        if(google_max_num_ads > 0 && requestCount < needCount){
            google_max_num_ads = needCount - requestCount;
            if(showLog){
                GJ.log('googleAfc-->'+google_max_num_ads);
            }
            requestAFC();
            return;
        }
        if(requestCount>0){
            showAds();
        }
    },
    
    showAds = function(){
        var topAdCount = topAds.length
        ,    belowAdCount = belowAds.length
        ,    wideAdsP1 = ''
        ,    wideAdsP2 = ''
        ;

        if(showLog){
            GJ.log('------------------------------');
            GJ.log('topAdCount:'+topAdCount);
            GJ.log('belowAdCount:'+belowAdCount);
            GJ.log('------------------------------');
        }

        if(topAdCount < google_ad.top_count && belowAdCount > 0){
            var addCount = google_ad.top_count - topAdCount;
            topAds = topAds.concat(belowAds.splice(0, addCount));
            topAdCount = topAds.length;
            belowAdCount = belowAds.length;
        }
            

        if(topAdCount>0){
            for(i in topAds){
                 wideAdsP1 += google_ad.fetchTopAd(topAds[i]);
            }
            google_ad.renderAd(google_ad.top_div_id, wideAdsP1);
        }

        if(belowAdCount>0){
            for(i in belowAds){
                wideAdsP2 += google_ad.fetchBelowAd(belowAds[i]);
                if(i>=google_ad.below_count-1) break;
            }
            google_ad.renderAd(google_ad.below_div_id, wideAdsP2);
        }
    };

    /**
     * 入口
     */
    GJ.googleAD = function(options){
        for(key in options){
            google_ad[key] = options[key];
        }
        /// 模版自定义
        switch(google_ad.isSp){
            case 0:
                initSp0();
                break;
            case 2:
                initSp2();
                break;
            case 3:
                initSp3();
                break;
            case 4:
                initSp4();
                break;
            case 5:
                initSp5();
                break;
        }

        setGoogleParam();
        if(isShowAfc()){
            requestAFC();
        }else{
            if(showLog){
                GJ.log('googleAfs-->'+google_afs_ad);
            }
            google_afs_request_done = request_done;
            document.write("<script type='text/javascript' src='http://www.google.com/afsonline/show_afs_ads.js'></script>");
        }
    };

})();
GJ.add("js/app/google_ad/google_ad.js");

