function recGetDomain() {
    var RecCurrentUrl = location.href;
    if (/360buy\.com/.test(RecCurrentUrl)) {
        return "jd.com";
    }
    if (/jd\.com/.test(RecCurrentUrl)) {
        return "jd.com";
    }
};
reCookieName = "reWidsThirdRec";
var RecRecommendCorrentDomain = recGetDomain();
var wids = "";
var atthref = "http://my." + RecRecommendCorrentDomain + "/personal/guess.html";
function readPinCookie(name)//读取cookies函数
{
    var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
    if (arr != null) return arr[2]; return '';
}

callback1 = function(data) {
    ;
}
log = function(type1, type2, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10) {
    var loguri = "http://csc." + RecRecommendCorrentDomain + "/log.ashx?type1=$type1$&type2=$type2$&data=$data$&pin=$pin$&referrer=$referrer$&jinfo=$jinfo$&callback=?";
    var data = '';
    for (i = 2; i < arguments.length; i++) {
        data = data + arguments[i] + '|||';
    }
    var url = loguri.replace(/\$type1\$/, escape(type1));
    url = url.replace(/\$type2\$/, escape(type2));
    url = url.replace(/\$data\$/, escape(data));
    url = url.replace(/\$pin\$/, escape(decodeURIComponent(readPinCookie("pin"))));
    url = url.replace(/\$referrer\$/, escape(document.referrer));
    url = url.replace(/\$jinfo\$/, escape(''));
    $.getJSON(
            url,
            callback1
        );
    var traceurl = ("https:" == document.location.protocol ? "https://mercuryssl" : "http://mercury") + ".jd.com/log.gif"
                + "?t=other.000000"
                + "&m=UA-J2011-1"
                + "&v=" + encodeURIComponent('t1=' + type1 + '$t2=' + type2 + '$p0=' + data)
                + "&ref=" + encodeURIComponent(document.referrer)
                + "&rm=" + (new Date).getTime();
    var d = new Image(1, 1);
    d.src = traceurl;
};
function skutype(b) {
    if (b) {
        var a = b.toString().length;
        return a == 10 ? 1 : 0
    }
    return 0
}
function clsPVAndShowLog(wpid, psku, markId, op) {
    var key = wpid + "." + markId + "." + skutype(psku) + "." + op;
    log('d', 'o', key);
}
function clsClickLog(wpid, psku, rsku, markId, num, reCookieName) {
    var key = wpid + "." + markId + "." + skutype(psku);
    appendCookie(reCookieName, rsku, key);
    log('d', 'o', key + ".c");
}
function appendCookie(reCookieName, sku, key) {
    var reWidsCookies = eval("(" + getCookie(reCookieName) + ")");
    if (reWidsCookies == null || reWidsCookies == "") {
        reWidsCookies = new Object()
    }
    if (reWidsCookies[key] == null) {
        reWidsCookies[key] = ""
    }
    var pos = reWidsCookies[key].indexOf(sku);
    if (pos < 0) {
        reWidsCookies[key] = reWidsCookies[key] + "," + sku
    }
    setCookie(reCookieName, $.toJSON(reWidsCookies), 15)
}


function reClick2(type2, pwid, sku, num) {
    var reWidsClubCookies = eval('(' + getCookie(reCookieName) + ')');
    if (reWidsClubCookies == null || reWidsClubCookies == '') {
        reWidsClubCookies = new Object();
    }
    if (reWidsClubCookies[type2] == null) {
        reWidsClubCookies[type2] = '';
    }
    var pos = reWidsClubCookies[type2].indexOf(sku);
    if (pos < 0) {
        reWidsClubCookies[type2] = reWidsClubCookies[type2] + "," + sku;
    }

    setCookie(reCookieName, $.toJSON(reWidsClubCookies), 15);

    sku = sku.split("#");
    log(3, type2, sku[0]);
    //log('RC', 'CK', type2, pwid, sku[0], num);
}
// 截取固定长度子字符串 sSource为字符串,iLen为截取的长度
function getInterceptedStr(sSource, iLen) {
    if (sSource.replace(/[^\x00-\xff]/ig, "xx").length <= iLen) {
        return sSource;
    }
    var str = ""; var l = 0; var schar;
    for (var i = 0; schar = sSource.charAt(i); i++) {
        l += (schar.match(/[^\x00-\xff]/ig) != null ? 2 : 1);
        if (l < iLen - 1) { str += schar; } else { break; };
    }
    return str + "...";
}
function setCookie(name, value, date)//两个参数，一个是cookie的名子，一个是值
{
    var Days = date; //此 cookie 将被保存 30 天
    var exp = new Date();    //new Date("December 31, 9998");
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/;domain=." + RecRecommendCorrentDomain + "";
}
function getCookie(name)//读取cookies函数
{
    var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
    if (arr != null) return unescape(arr[2]); return null;
}

//三级列表页推荐--------start------------------------------------
var Sort = "";
var type = "";
var key = "";
var BrandId = "";
function ClubSimiGoods() {
    var wids = new Array();
    $("#plist ul li .p-img a").each(function(i, o) {
        if (i >= 4) { return false; }
        var being = o.href.lastIndexOf("/") + 1;
        var end = o.href.lastIndexOf(".");
        wids.push(o.href.substring(being, end));
        return true;
    })
    var Wid = wids[parseInt(wids.length * Math.random())];
    $.getJSONP("http://simigoods." + RecRecommendCorrentDomain + "/ThridRec/ThridRec.aspx?ip=" + getCookie("ipLocation") + "&Wid=" + Wid + "&type=" + type + "&key=" + key + "&callback=ClubSimiGoodsCallback", ClubSimiGoodsCallback);
}
function GetKeyWords() {
    var keyword = "";
    var crumb = $(".crumb a");
    var crumbIndex = 3;
    if (crumb.length == 0) {
        crumb = $(".breadcrumb a");
        crumbIndex = 2;
    }
    keyword = $(crumb[crumbIndex]).text()
    return keyword;
}
ClubSimiGoodsCallback = function(json) {
    var keyWords = getInterceptedStr(GetKeyWords(), 12);
    if (json.AttentionRec != null && json.AttentionRec.length > 0) {
        var template = "<div class=\"mt\"></div><div class=\"mc\"><ul>{for item in AttentionRec}{if item_index==0}<li class='fore' onclick = 'reClick2(\"" + Sort + "&ThirdRec\",\"\",\"${item.Wid}\",\"${item_index}\")'>{else}<li onclick = 'reClick2(\"" + Sort + "&ThirdRec\",\"\",\"${item.Wid}\",${item_index})'>{/if}<div class='p-img'><a href='${item.Href}' title='${item.Wname}&#13;${item.Promotitle}' target=\"_blank\"><img width='100' height='100' src='${item.Img}' alt='${item.Wname}&#13;${item.Promotitle}'></a>{if item.AllNum != 0}{else}{/if}</div><div class='rate'>{if item.Count > 0}<strong>${item.Count}%会买：</strong>{else}{/if}<a href='${item.Href}' title='${item.Wname}&#13;${item.Promotitle}' target=\"_blank\">${item.Wname}<font style=\"color:#ff0000\">${item.Promotitle}</font></a></div><div class='p-price'>${item.Priceimg}</div></li>{/for}</ul><div class=\"more\"><a target=\"_blank\" title=\"查看更多\" href=\"" + atthref + "\" clstag='click|keycount|recthird|persmore'>查看更多推荐</a></div></div>";
        var html = template.process(json);
        $('#finalbuy').html(html);
        $("#finalbuy .mt").html("<h2>浏览<font color=\"red\">" + keyWords + "</font>最终购买</h2>")
        $('#finalbuy').show();
        ischoiceonetag();
        log(Sort + "&ThirdRec", 'Show');
    }
    var keyWords2 = getInterceptedStr(GetKeyWords(), 12);
    if (json.AttentionBuy != null && json.AttentionBuy.length > 0) {
        var template = "<div class=\"mt\"></div><div class=\"mc\"><ul>{for item in AttentionBuy}{if item_index==0}<li class='fore' onclick = 'reClick2(\"" + Sort + "&ThirdBuy\",\"\",\"${item.Wid}\",\"${item_index}\")'>{else}<li onclick = 'reClick2(\"" + Sort + "&ThirdBuy\",\"\",\"${item.Wid}\",${item_index})'>{/if}<div class='p-img'><a href='${item.Href}' title='${item.Wname}&#13;${item.Promotitle}' target=\"_blank\"><img width='100' height='100' src='${item.Img}' alt='${item.Wname}&#13;${item.Promotitle}'></a>{if item.AllNum != 0}{else}{/if}</div><div class='rate'><a href='${item.Href}' title='${item.Wname}&#13;${item.Promotitle}' target=\"_blank\">${item.Wname}<font style=\"color:#ff0000\">${item.Promotitle}</font></a></div><div class='p-price'>${item.Priceimg}</div></li>{/for}</ul></div>"
        var html = template.process(json);
        $('#alsobuy').html(html);
        $("#alsobuy .mt").html("<h2>浏览<font color=\"red\">" + keyWords2 + "</font>还购买了</h2>")
        $('#alsobuy').show();
        log(Sort + "&ThirdBuy", 'Show');
    }
}

function FilterNoResults(type) {
    FilterNoResultsShow(type);
    clsPVAndShowLog("", "", 32, "p")
}
function FilterNoResultsShow(type) {
    $.getJSONP("http://simigoods." + RecRecommendCorrentDomain + "/ThridRec/FilterNoResults.aspx?ip=" + getCookie("ipLocation") + "&type=" + type + "&callback=FilterNoResultsCallback", FilterNoResultsCallback);
}
FilterNoResultsCallback = function(json) {
    if (json.FilterNoResults != null && json.FilterNoResults.length > 0) {
        var template = "<div class=\"mt\"><h2>降价促销商品推荐</h2></div><ul class=\"list-h\">{for item in FilterNoResults}<li onclick=\"clsClickLog('', '', '${item.Wid}', 32,'${item_index}', 'rodGThirdRec');\"><div class=\"p-img\"><a href='${item.Href}' title='${item.Wname}&#13;${item.Promotitle}' target=\"_blank\"><img alt='${item.Wname}&#13;${item.Promotitle}' src='${item.Img}' onerror=\"this.src='http://www." + RecRecommendCorrentDomain + "/images/none/none_150.gif'\"></a></div><div class=\"p-name\"><a href='${item.Href}' title='${item.Wname}&#13;${item.Promotitle}' target=\"_blank\">${item.Wname}<font style=\"color:#ff0000\">${item.Promotitle}</font></a></div><div class=\"p-price\">${item.Priceimg}</div></li>{/for}</ul>";
        var html = template.process(json);
        $('#co-product').html(html);
        $('#co-product').show();
        clsPVAndShowLog("", "", 32, "s")
    }
}

function ThirdTypeRec() {
    var strUrl = this.location.href;
    var Thirdkey = 0; var ThirdType = 0; var firsttype = 0; var Brand = 0;
    var Sbegin = strUrl.lastIndexOf("/");
    var Send = strUrl.lastIndexOf(".");
    var strUrlS = strUrl.substring(Sbegin + 1, Send);
    var strUrlSplit = strUrlS.split("-");
    ThirdType = strUrlSplit[2]; firsttype = strUrlSplit[0]; Thirdkey = "";
    Brand = $('#select-brand .content div a[class=curr]').attr("id");
    for (var i = 3; i < strUrlSplit.length - 3; i++) {
        Thirdkey += strUrlSplit[i] + "-";
        if (i >= 9)
        { break; }
    }
    Thirdkey = Thirdkey.substring(0, Thirdkey.length - 1);
    if (Thirdkey == "0-0-0-0-0-0-0") {
        Thirdkey = "";
    }
    var r = /^\+?[1-9][0-9]*$/;
    if (r.test(firsttype) && r.test(ThirdType)) {
        Sort = firsttype; type = ThirdType; BrandId = Brand;
    }
    atthref = "http://my." + RecRecommendCorrentDomain + "/product/likes.html?tid=" + type;
    key = Thirdkey;
    ClubSimiGoods();
    log(Sort + "&ThirdPage", 'Show');
}
function ischoiceonetag() {
    if ($('#finalbuy div').length > 0) {
        var data = $($('#finalbuy ul li .p-img').find('a')[0]).attr('href');
        var a = data.split('/')[data.split('/').length - 1];
        var b = a.split('.');
        wids = b[0];
        atthref = "http://my." + RecRecommendCorrentDomain + "/product/likes.html?id=" + wids;
        $($('#finalbuy .more').find('a')[0]).attr("href", atthref);
    }
}
ThirdTypeRec();




var listRank_TPL = '<ul class="tabcon">'
            + ' {for item in data }'
            + ' 	<li {if parseInt(item_index) == 0} class="fore fore1" {/if} {if parseInt(item_index) == 1} class="fore2" {/if} {if parseInt(item_index) == 2} class="fore3" {/if} onclick="clsClickLog(\'\', \'\', \'${item.sku}\', 31, ${parseInt(item_index)+1}, \'rodGThirdRec\');Recommend.newImage(\'${item.clk}&m=UA-J2011-1&ref=${encodeURIComponent(document.referrer)}\', true)"><span>${parseInt(item_index)+1}</span>'
            + '     	{if parseInt(item_index) == 0}'
            + '         	<div class="p-img">'
            + '         	<a href="http://item.jd.com/${item.sku}.html" title="${item.t}" target="_blank"><img src="${pageConfig.FN_GetImageDomain(item.sku)}n5/${item.img}" width="50" height="50" data-img="1" /></a>'
            + '         	</div>'
            + '     	{else}'
            + '         	<div class="p-img" style="display: none;">'
            + '         	<a href="http://item.jd.com/${item.sku}.html" title="${item.t}" target="_blank"><img src="${pageConfig.FN_GetImageDomain(item.sku)}n5/${item.img}" width="50" height="50" data-img="1" /></a>'
            + '         	</div>'
            + '     	{/if}'
            + ' 	<div class="p-name"><a href="http://item.jd.com/${item.sku}.html" target="_blank">${item.t}</a></div>'
            + '		{if parseInt(item_index) == 0}'
            + '     	{if item.jp == -1}'
            + '         	<div class="p-price"><strong>暂无报价</strong></div>'
            + '     	{else}'
            + '         	<div class="p-price"><strong>￥${item.jp}</strong></div>'
            + '     	{/if}'
            + ' 	{else}'
            + ' 		{if item.jp == -1}'
            + ' 			<div class="p-price" style="display: none;"><strong>暂无报价</strong></div>'
            + ' 		{else}'
            + ' 			<div class="p-price" style="display: none;"><strong>￥${item.jp}</strong></div>'
            + ' 		{/if}'
            + ' 	{/if}'
            + ' </li>'
            + ' {/for}'
            + '</ul>';

var listOldRank_TPL = '<ul class="tabcon">'
            + ' {for item in tablist }'
            + ' 	<li {if parseInt(item_index) == 0} class="fore fore1" {/if} {if parseInt(item_index) == 1} class="fore2" {/if} {if parseInt(item_index) == 2} class="fore3" {/if} onclick="clsClickLog(\'\', \'\', \'${item.Wid}\', 31, ${parseInt(item_index)+1}, \'rodGThirdRec\');"><span>${parseInt(item_index)+1}</span>'
            + ' 		{if parseInt(item_index) == 0}'
            + ' 			<div class="p-img">'
            + ' 			<a href="http://item.jd.com/${item.Wid}.html" title="${item.Wname}" target="_blank"><img src="${pageConfig.FN_GetImageDomain(item.Wid)}n5/${item.Img}" width="50" height="50" data-img="1" /></a>'
            + ' 			</div>'
            + ' 		{else}'
            + ' 		<div class="p-img" style="display: none;">'
            + ' 		<a href="http://item.jd.com/${item.Wid}.html" title="${item.Wname}" target="_blank"><img src="${pageConfig.FN_GetImageDomain(item.Wid)}n5/${item.Img}" width="50" height="50" data-img="1" /></a>'
            + ' 		</div>'
            + ' 		{/if}'
            + ' <div class="p-name"><a href="http://item.jd.com/${item.Wid}.html" target="_blank">${item.Wname}</a></div>'
            + ' 	{if parseInt(item_index) == 0}'
            + ' 		{if item.WMeprice == undefined}'
            + ' 			<div class="p-price"><strong>暂无报价</strong></div>'
            + ' 		{else}'
            + ' 			<div class="p-price"><strong>￥${item.WMeprice}</strong></div>'
            + ' 		{/if}'
            + ' 	{else}'
            + ' 		{if item.WMeprice == undefined}'
            + ' 			<div class="p-price" style="display: none;"><strong>暂无报价</strong></div>'
            + ' 		{else}'
            + ' 			<div class="p-price" style="display: none;"><strong>￥${item.WMeprice}</strong></div>'
            + ' 		{/if}'
            + ' 	{/if}'
            + ' 	</li>'
            + ' {/for}'
            + '</ul>';

var Recommend = {
    init: function(BrandId, locId, loc, c3) {
        this.BrandId = BrandId;
        this.locId = locId;
        this.loc = loc;
        this.c3 = c3;

        this.pin = readCookie('pin');
        this.pid = locId === null ? 1 : locId.split('-')[0];
        var __jda = readCookie('__jda');

        // split uuid
        if (__jda) {
            if (__jda.split('.')[1] == '-') {
                this.uuid = -1;
            } else {
                this.uuid = __jda.split('.')[1];
            }
        } else {
            this.uuid = -1;
        }
        if (this.BrandId > 0) {
            //this.getOldBuyBuy();
            this.getNewBuyBuy();
        }
    },
    newImage: function(src, random, callback) {
        var img = new Image();
        src = random ? (src + '&random=' + Math.random() + '' + (new Date)) : src;

        img.setAttribute('src', src);

    },
    getOldBuyBuy: function() {
        var _this = this;

        var param = {
            ip: _this.loc,
            BrandId: _this.BrandId,
            type: _this.c3,
            callback: 'Recommend.setOldRank'
        };
        $.ajax({
            url: 'http://simigoods.360buy.com/ThridRec/RankHandler.ashx',
            data: param,
            cache: true,
            dataType: 'script',
            success: function(r) {

            }
        });
    },
    setOldRank: function(r) {
        var desElement = $('#weekRank');

        if (r.length < 1) {
            return;
        }
        var list = { tablist: r };
        desElement.show().find('.mc').html(listOldRank_TPL.process(list));

    },
    getNewBuyBuy: function() {
        var _this = this;

        var param = {
            p: 503000,      // 买了又买了
            hi: "bid:" + _this.BrandId,
            c3: _this.c3,
            lid: _this.pid,
            lim: 10,
            uuid: _this.uuid,
            ec: 'gbk',
            callback: 'Recommend.setNewRank'
        };

        if (this.pin) {
            param.pin = this.pin;
        }
        $.ajax({
            url: 'http://diviner.jd.com/diviner',
            data: param,
            dataType: 'script',
            cache: true,
            success: function(r) {
            }
        });
    },
    setNewRank: function(r) {
        var desElement = $('#weekRank');

        if (!r || !r.success || r.data.length < 1) {
            return;
        }

        desElement.show().find('.mc').html(listRank_TPL.process(r));
        this.newImage(r.impr+"&m=UA-J2011-1&ref="+encodeURIComponent(document.referrer));
        weekRank2Effect();
    }
};

Recommend.init(BrandId, readCookie('ipLoc-djd'), readCookie('ipLocation'), type);