$(function(){


	buildMarketMenu = function(supId,target){
		var _path=buildHTTP("/prod/type/api/child/"+supId+".shtml");
		$.ajax({
			url: _path, 
			type: "get", 
			dataType: "json",
			contentType:"application/json",
			success: function(data) { 
				if(data.code=='01'){
					types = data.content;
					if(target=='1'){
						buildFirstTabs(types);
					}
				}
			}
		});
	}

	var SUP_ID = 1; // 商城定级分类编号
	buildMarketMenu(SUP_ID,'1');

	buildFirstTabs = function(types){
		var vHtml = "";
		var cHtml = "";

		$.each(types,function(i,type){
			var typeId = type.typeId;
			if(i==0){
				vHtml += "<a href=\"#tab"+typeId+"\" class=\"tab-link button active\">"+type.name+"</a>";
				cHtml += "<div id=\"tab"+typeId+"\" class=\"tab active\">";

			}else{
				vHtml += "<a href=\"#tab"+typeId+"\" class=\"tab-link button\">"+type.name+"</a>";
				cHtml += "<div id=\"tab"+typeId+"\" class=\"tab\">";
			}

			cHtml += "<div class=\"content-block\" style='height:35px;padding-left:18px;'>";
			var childs = type.children;
			if(childs.length>0){
				$.each(type.children,function(idx,child){
					cHtml += "<span onclick='showType("+child.typeId+")'>"+child.name+"</span>&nbsp;&nbsp;&nbsp;&nbsp;";
				});
			}else{
				cHtml += "暂无商家入驻，<a href='settled.html' class='link-title external'>现在入驻</a>";
			}
			cHtml += "</div>";
			cHtml += "</div>";
		});
		$("#firstTabs").html(vHtml);
		$("#firstTabContent").html(cHtml);

	};


	//=================================================================================================
	var typeId = 0;
	var page=1;
	var loading = false; // 加载flag
	var maxItems = 0;// 最多可加载的条目
	var itemsPerLoad = 10;// 每次加载添加多少条目
	var lastIndex = 10;

	showType = function(_id){
		$(".list-container").html("");
		typeId = _id;
		productlist(1);
	};

	productlist = function(_page){
		this.page=_page;
		var _path=buildHTTP("/prod/api/find.shtml");
		var params={
				page: _page,
				typeId:typeId,
				status:'1'
		};
		$.ajax({
			url: _path, 
			type: "post", 
			dataType: "json",
			data:$.toJSON(params),   
			contentType:"application/json",
			success: function(data) { 
				maxItems = data.rowCount;
				if(data.rowCount <=lastIndex){
					$('.infinite-scroll-preloader').remove();
				}
				if(data.records.length==0){
					var vhtml = template('noprodHtml', data);
					$(".list-container").html(vhtml);
				}else{
					var vhtml = template('productHtml', data);
					$('.list-container').append(vhtml);
				}			
			}
		});
	}; 

	productlist(page);

	$(document).on('infinite', '.infinite-scroll',function(e) {
		// 如果正在加载，则退出
		if (loading) return;
		// 设置flag
		loading = true;

		setTimeout(function() {
			loading = false;
			page++;
			lastIndex = page * itemsPerLoad;// 更新最后加载的序号

			if (lastIndex >= maxItems) {
				$.detachInfiniteScroll($('.infinite-scroll'));
				$('.infinite-scroll-preloader').remove();
				return;
			}

			productlist(page);

		}, 1000);
	});

	$.init();
});