
/*********************焦点*************************/
pageConfig.TPL_MSlide={
    itemsWrap:"<ul class=\"slide-items\">{innerHTML}</ul>",
    itemsContent:"{for item in json}"
        +"<li data-tag=\"${item.aid}\">"
            +"{var v=item.data}"
            +"<a href=\"${v.href}\" target=\"_blank\" title=\"${v.alt}\" >"
                +"<img height=\"${v.height}\" width=\"${v.width}\" src=\"${v.src}\" data-img=\"2\" />"
            +"</a>"
        +"</li>"
    +"{/for}",
    controlsWrap:"<div class=\"slide-controls\">{innerHTML}</div>",
    controlsContent:"{for item in json}"
        +"<span class=\"{if parseInt(item_index)==0}curr{/if}\">${parseInt(item_index)+1}</span>"
    +"{/for}"
};

jQuery("#slide").Jslider({
    data:pageConfig.DATA_MSlide,
    auto:true,
    reInit:true,
    slideWidth:(screen.width>=1210)?730:550,
    slideHeight:270,
    maxAmount:8,
    slideDirection:2,
    template:pageConfig.TPL_MSlide
},function(object){
    pageConfig.FN_ImgError(object.get(0));
});

jQuery("*[data-widget=tabs]").each(function(){
	jQuery(this).Jtab({compatible:true});
});

$("#single-choice .mc .con").imgScroll({
    visible: (screen.width>1210)?4:3,
    speed:300,
    step: (screen.width>1210)?4:3,
    direction: 'x',
    loop: false,
    evtType: 'click',
    next: '#next2',
    prev: '#prev2',
    disableClass: 'disabled'
}, function(n, total, objs, exObjs) {
	objs.find('img').each(function() {
		if ( $(this).attr('data-lazyload') ) {
			$(this).attr('src', $(this).attr('data-lazyload'));
		}
	});	
});

$("#parts-center .mc .con").imgScroll({
    visible: (screen.width>1210)?9:7,
    speed:300,
    step: (screen.width>1210)?9:7,
    direction: 'x',
    loop: false,
    evtType: 'click',
    next: '#next',
    prev: '#prev',
    disableClass: 'disabled'
}, function(n, total, objs, exObjs) {
	objs.find('img').each(function() {
		if ( $(this).attr('data-lazyload') ) {
			$(this).attr('src', $(this).attr('data-lazyload'));
		}
	});	
});

defaultScreen();
//获取第一屏默认商品价格
function defaultScreen(){
	var skuids = [];
	//热销商品
	var hotProductLi=$("#bargain").find(".fore1").children(".mc").find("ul").children('li');
	if(hotProductLi.length>0){
		for (var i = 0; i < hotProductLi.length; i++) {
			 skuids.push( hotProductLi.eq(i).attr("sku") );
		 }
	}

	//楼层
	for(var f=1;f<6;f++){
		var li=$("#floor"+f).children(".mc").children(".con").find("ul").children('li');
		if(li.length>0){
			for(var z=0;z<li.length;z++){
				skuids.push(li.eq(z).attr("sku"));
			}
		}
	
	}
	
	//排行榜
	for(var f=1;f<6;f++){
		var li=$("#floor"+f+"-top").children(".mc").find("ul").children('li');
		if(li.length>0){
			for(var z=0;z<li.length;z++){
				skuids.push(li.eq(z).attr("sku"));
			}
		}
	
	}
	
	getPrice(skuids.join(",J_"));
} 
/**每个楼层从第二个tab标签开始异步获取价格**/
function getFloorPrice(data){
	var skuIds=[];
	for ( var i = 0, j = data.length; i < j; i++) {
		skuIds[i]=data[i].skuId;
		}
	getPrice(skuIds.join(",J_"));
}

/**获取价格**/
function getPrice(skuIds){
	$.ajax({
		"url": 'http://p.3.cn/prices/mgets?skuIds=J_' + skuIds + '&type=1',//价格时时调用
		"dataType": 'jsonp',
		"success": function(r) {
			if ( r && r.length>0 ) { 
			 for(var i=0,j=r.length;i<j;i++){
				 var skuId = r[i].id.replace("J_","");
					var price = r[i].p;
					if(price>0){
						$("li[sku='"+skuId+"']").find(".p-price strong").html( "\uffe5" + price + "" );
					}else{
						$("li[sku='"+skuId+"']").find(".p-price strong").html("暂无报价");
					}
				}
			 }
		}
		});
}

/********今日特价、新品首发、应季热卖、寻宝清仓*********/
var jiaodianhtml='<ul>'
    +'{for item in data }'
    + '<li class="fore${item.ranKing}" sku="${item.skuId}">'
    +  '${item.iCDesc}<div class="p-img">'
    +   '<a target="_blank" href="http://item.jd.com/${item.skuId}.html" title="${item.skuName}">'
    +	 '<img width="160" height="160" src="${item.imageUrl}" alt="${item.skuName}" data-img="1"/>'
    +	'</a>'
    +  '</div>'
    +  '<div class="p-name">'
    +  	'<a href="http://item.jd.com/${item.skuId}.html" target="_blank" title="${item.skuName}">${item.skuName}<font color="#ff6600">${item.wareTitle}</font></a>'
    +  '</div>'
    +   '<div class="p-price">京东价：<strong></strong></div>'
    + '</li>'
    +'{/for}'
    +'</ul>';
jQuery('#bargain').Jtab({compatible: true},
    function( source, obj, n ) {
    if ( n != 0 && obj.find('li').length==0) {
        var data = null;
        if (n == 1 && recommendList2){
            data = recommendList2;
        }
        else if (n == 2 && recommendList3){
            data = recommendList3;
        }
        else if (n == 3 && recommendList4){
        	data = recommendList4;
            
        }
        if (data){
			var itemJson = {"1":"限量","2":"清仓","3":"首发","4":"满减","5":"满赠","6":"直降","7":"新品","8":"独家","9":"人气 ","10":"热卖","11":"抢"};
			for(var i=0,j=data.length;i<j;i++){
				if (itemJson[data[i].itemContent+""]){
					data[i].iCDesc = '<b class="pi pix1">'+itemJson[data[i].itemContent+""]+'</b>';
				}
				else{
					data[i].iCDesc = "";
				}
			}
            obj.html( jiaodianhtml.process( {"data":data} ));
            getFloorPrice(data);
        }
        pageConfig.FN_ImgError(obj[0]);
    }
});

/*********楼层广告************/


//配件中心
var AccessoryChoose = function(brand, type, category, btn) {
    this.brand = brand;
    this.type = type;
    this.category = category;
    this.btn = btn;
	
    this.url = 'http://rs.jd.com/carAccessorie/requestCarCenter?';
	
    this.init();
};

AccessoryChoose.prototype = {
    init: function() {
        
        // default load brands & category
        this.getBrands();
        // this.getCategory();
    },
    bindEvent: function(type) {
        var _this = this;

        if (type === 'onSelectBrand') {
            this.brand.unbind('change').bind('change', function() {
                var brandId = $(this).val();
				
				if (brandId === '') {
					_this.reset(0);
				} else {
					_this.getTypes(brandId);
				}
            });
        }
		if (type === 'onSelectType') {
			this.type.unbind('change').bind('change', function() {
				var typeId = $(this).val();
				
				if (typeId === '') {
					_this.reset(1);
				} else {
					_this.getCategory(typeId);
				}				
				
			});
		}
		
		if (type === 'onSelectCat') {
			this.category.unbind('change').bind('change', function() {
				var catId = $(this).val();
				if (catId === '') {
					_this.reset(2);
				} else {
					_this.getWid(catId);
				}	
			});
		}

    },
	reset: function(ind) {
		if (ind === 0) {
			this.type.html('<option value="">选择车系</option>');
			this.category.html('<option value="">选择车型</option>');
			this.btn.attr('href', 'http://rs.jd.com/carAccessorie/requestCarCenter');
			this.btn.attr('class','btn-find');
		}
		
		if (ind === 1) {
			this.category.html('<option value="">选择车型</option>');
			this.setResLink();
		}
		
		if (ind === 2) {
			this.setResLink();
		}
		
	},
    setResLink: function() {
        var _this = this,
        
			brandId = _this.brand.val(),
            carseriesId = _this.type.val(),
            carModeId = _this.category.val(),
            wid = _this.wid;

        //console.log(brandId + '\n' + carseriesId + '\n' + carModeId + '\n' + wid);
        if (carModeId) {
            _this.btn.attr( 'href', _this.url + $.param({
                brandId: brandId,
                carseriesId: carseriesId,
				carModeId: carModeId,
				wid: wid,	
				from: 'carEntrance'
            }));
            _this.btn.attr('class','btn-find');
        }else{
        	_this.btn.attr( 'href', _this.url + $.param({
                brandId: brandId,
                carseriesId: carseriesId,
				carModeId: carModeId,
				wid: '',	
				from: 'carEntrance'
            }));
            _this.btn.attr('class','btn-find');
        }
        
    },
    getBrands: function(loadDefault) {
        var _this = this;

        $.ajax({
            url: 'http://rs.jd.com/carAccessorie/getAllCarInfo.jsonp?parentId=0',
            dataType: 'jsonp',
			scriptCharset: 'utf-8',
            success: function(r) {
                if ( r && r.carInfo && r.carInfo.length > 0 ) {
					_this.setBrands(r);
				}
            }
        });
    },
    setBrands: function(data) {
        var optsTPL = '<option value="">选择品牌</option>{for item in carInfo}<option value="${item.id}">${item.name}</option>{/for}';
		var optsTPLWidthPlaceholder = '<option>选择品牌</option>{for item in carInfo}<option value="${item.id}">${item.name}</option>{/for}';

        this.brand.html( optsTPL.process(data) );

        this.bindEvent('onSelectBrand');

        // load first brand data
        if ( this.brand.val() !== '' ) {
            this.getTypes( this.brand.val() );
        } else {
			this.reset(0);
		}

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

        $.ajax({
            url: 'http://rs.jd.com/carAccessorie/getAllCarInfo.jsonp?parentId='+ brandId,
            dataType: 'jsonp',
			scriptCharset: 'utf-8',
            success: function(r) {
                if ( r && r.carInfo && r.carInfo.length > 0 ) {
					_this.setTypes(r);
				}
            }
        });
    },
    setTypes: function(data) {
        var optsTPL = '<option value="">选择车系</option>{for item in carInfo}<option value="${item.id}">${item.name}</option>{/for}';

        this.type.html( optsTPL.process(data) );
        
		this.bindEvent('onSelectType');

        // load first brand data
        if ( this.type.val() !== '' ) {
            this.getCategory( this.type.val() );
        } else {
			this.reset(1);
		}
		
    },
    getCategory: function(catId) {
        var _this = this;

        $.ajax({
            url: 'http://rs.jd.com/carAccessorie/getAllCarInfo.jsonp?parentId=' + catId,
            dataType: 'jsonp',
			scriptCharset: 'utf-8',
            success: function(r) {
                if ( r && r.carInfo && r.carInfo.length > 0 ) {
					_this.setCategory(r);
				}
            }
        });
    },
    setCategory: function(data) {
        var optsTPL = '<option value="">选择车型</option>{for item in carInfo}<option value="${item.id}">${item.name}</option>{/for}';

        this.category.html( optsTPL.process(data) );
		
		this.bindEvent('onSelectCat');
        
		if ( this.category.val() !== '' ) {
            this.getWid( this.category.val() );
        }else {
			this.reset(2);
		}
    },
	getWid: function(catId) {
		var _this = this;

		$.ajax({
            url: 'http://rs.jd.com/carAccessorie/getAllCarInfo.jsonp?parentId=' + catId,
            dataType: 'jsonp',
			scriptCharset: 'utf-8',
            success: function(r) {
                if ( r && r.carInfo && r.carInfo.length > 0 ) {
					_this.wid = r.carInfo[0].name;
					_this.setResLink();
				}
            }
        });
	}
};

$(function() {

    // AccessoryChoose
    var AS = new AccessoryChoose( $('#car-file select').eq(0), $('#car-file select').eq(1), $('#car-file select').eq(2), $('#car-file .btn-find') );

});