$(function() {
	$('.goodsImg').lazyload({ effect: "fadeIn",failurelimit : 10,skip_invisible : false,threshold: 100,placeholder:window.conf.RESOURCE_PATH+'/'+window.conf.GOODS_LOGO});//商品默认图片
	$('.shopsImg').lazyload({ effect: "fadeIn",failurelimit : 10,skip_invisible : false,threshold: 100,placeholder:window.conf.RESOURCE_PATH+'/'+window.conf.SHOP_LOGO});//店铺默认头像
	$('.usersImg').lazyload({ effect: "fadeIn",failurelimit : 10,skip_invisible : false,threshold: 100,placeholder:window.conf.RESOURCE_PATH+'/'+window.conf.USER_LOGO});//会员默认头像
});
WST.initVisitor = function(){
	WST.dropDownLayer(".j-dorpdown",".j-dorpdown-layer");
	WST.dropDownLayerCart(".j-cart",".j-cart-layer");
	WST.searchIpt();
	WST.Sidebar();
	WST.getSysMessages('message,cart');
	if(WST.conf.TIME_TASK=='1'){
		setInterval(function(){
			WST.getSysMessages('message,cart');
		},10000);
	}
}
WST.initUserCenter = function(){
	WST.dropDownLayer(".j-dorpdown",".j-dorpdown-layer");
	WST.dropDownLayerCart(".j-cart",".j-cart-layer");
	WST.searchIpt();
	WST.getSysMessages('message,cart,userorder');
	if(WST.conf.TIME_TASK=='1'){
		setInterval(function(){
			WST.getSysMessages('message,cart,userorder');
		},10000);
	}
}
WST.searchIpt = function(){
	$('.j-search-box').hover(function(){
		$(".j-type-list").show();
		$(this).find('i').removeClass('arrow').addClass('over');
		$(this).css({"border-left":"2px solid #e23c3d"});
	},function(){
		$(".j-type-list").hide();
		$(this).css({"border-left":"2px solid #e23c3d"});
		$(this).find('i').removeClass('over').addClass('arrow');
	});

	$('j-type-list').hover(function(){
		$(".j-type-list").show();
		$(this).find('i').removeClass('arrow').addClass('over');
		$(this).css({"border-left":"2px solid #e23c3d"});
	});

	$(".j-type-list div").click(function(){
		$("#search-type").val($(this).attr("data"));
		$(".j-search-type span").html($(this).html());
		if($(this).attr("data")==1){
			$(this).attr("data",0);
			$(this).html('商品');
			$('#search-ipt').attr('placeholder',$('#adsWordsSearch').val());
		}
		$(".j-type-list").hide();
		$(".j-search-type").find('i').removeClass('over').addClass('arrow');
	});
}
WST.search = function(){
		WST.goodsSearch($.trim($('#search-ipt').val()));
}
WST.goodsSearch = function(v){
	location.href = WST.U('home/goods/search','keyword='+v);
}
WST.Sidebar = function(){
	$(".wst-classify").hover(function(){
		$('.catImgs').lazyload({failurelimit : 10,skip_invisible : false,threshold: 100,placeholder:window.conf.RESOURCE_PATH+'/'+window.conf.GOODS_LOGO});//商品默认图片
		$('.wst-classify .list').css('height','auto');
		$('.cat-hide').show();
	},function(){
		$('.wst-classify .list').css('height','420');
		$('.cat-hide').hide();
    });
	$(".wst-classify .list").children("li").hover(function(){
		$(this).addClass("active");
    },function(){
    	$(this).removeClass("active");
    });
	$(".wst-nav-items ul").children(".category").hover(function(){
		$(".wst-classify").show();
	},function(){
		$(".wst-classify").hide();
    });
	$(".wst-classify.cats").mouseover(function(){
		$(".wst-classify").show();
	});
	$(".wst-classify").mouseout(function(){
		$(".wst-classify.cats").hide();
	});
}
WST.dropDownLayer = function(dropdown,layer){
	$(dropdown).hover(function () {
        $(this).find(layer).show();
    }, function () {
    	$(this).find(layer).hide();
    });
	$(layer).hover(function () {
		$(this).find(layer).show();
    }, function () {
    	$(this).find(layer).hide();
    });
}

WST.tips = function(content, selector, options){
	var opts = {};
	opts = $.extend(opts, {tips:1, time:2000, maxWidth: 260}, options);
	return layer.tips(content, selector, opts);
}
WST.open = function(options){
	var opts = {};
	opts = $.extend(opts, {offset:'100px'}, options);
	return layer.open(opts);
}
WST.confirm = function(options){
	var opts = {};
	opts = $.extend(opts, {title:'系统提示',offset:'200px'}, options);
	return layer.confirm(opts.content,{icon: 'wst3', title:opts.title,offset:opts.offset},options.yes,options.cancel);
}
WST.load = function(options){
	var opts = {};
	opts = $.extend(opts,{time:0,icon:'wstloading',shade: [0.4, '#000000'],offset: '200px'},options);
	return layer.msg(opts.msg, opts);
}
WST.msg = function(msg, options, func){
	var opts = {};
	if(options){
		if(options.icon==1){
			options.icon='wst1';
		}else if(options.icon==2 || options.icon==5){
			options.icon='wst2';
		}else if(options.icon==3){
			options.icon='wst3';
		}
	}
	//有抖動的效果,第二位是函數
	if(typeof(options)!='function'){
		opts = $.extend(opts,{time:1000,shade: [0.4, '#000000'],offset: '200px'},options);
		return layer.msg(msg, opts, func);
	}else{
		return layer.msg(msg, options);
	}
}
WST.toJson = function(str,noAlert){
	var json = {};
	try{
		if(typeof(str )=="object"){
			json = str;
		}else{
			json = eval("("+str+")");
		}
		if(typeof(noAlert)=='undefined'){
			if(json.status && json.status=='-999'){
				WST.msg('对不起，您已经退出系统！请重新登录',{icon:5},function(){
					if(window.parent){
						window.parent.location.reload();
					}else{
						location.reload();
					}
				});
			}else if(json.status && json.status=='-998'){
				WST.msg('对不起，您没有操作权限，请与管理员联系');
				return;
			}
		}
	}catch(e){
		WST.msg("系统发生错误:"+e.getMessage,{icon:5});
		json = {};
	}
	return json;
}

//刷新验证码
WST.logout = function(){
	$.post(WST.U('home/users/logout'),{},function(data,textStatus){
		var json = WST.toJson(data);
		WST.msg(json.msg,{icon:1});
		location.href=WST.U('home/index/index');
	});
}

function shopApply(){
	layer.open({
	    type: 1,
	    title: false,
	    shadeClose: true,
	    shade: 0.8,
	    offset: '80px',
	    area: ['760px',  '760px'],
	    closeBtn: 0,
	    content: $('#wst-shopapp'),
	//    content: [WST.U('home/Shopapplys/toApply'),'no'],
	    end: function(index, layero){
	    	//layer.close(index);
	    }
	});
	WST.getVerify('#verifyImg3');
	$('.layui-layer').css('background','transparent');
	$('.layui-layer').css('box-shadow','none');
}
/**
* 上传图片
*/
WST.upload = function(opts){
	var _opts = {};
	_opts = $.extend(_opts,{auto: true,swf: WST.conf.ROOT +'/static/plugins/webuploader/Uploader.swf',server:WST.U('home/index/uploadPic')},opts);
	var uploader = WebUploader.create(_opts);
	uploader.on('uploadSuccess', function( file,response ) {
	    var json = WST.toJson(response._raw);
	    if(_opts.callback)_opts.callback(json,file);
	});
	uploader.on('uploadError', function( file ) {
		if(_opts.uploadError)_opts.uploadError();
	});
	uploader.on( 'uploadProgress', function( file, percentage ) {
		percentage = percentage.toFixed(2)*100;
		if(_opts.progress)_opts.progress(percentage);
	});
    return uploader;
}

WST.goTo = function(obj){
	location.href = $(obj).attr('data');
}
WST.getVerify = function(id){
    $(id).attr('src',WST.U('home/index/getVerify','rnd='+Math.random()));
}
WST.loginWindow = function(){
	WST.currentUrl();
	$.post(WST.U('home/users/toLoginBox'),{},function(data){
		WST.open({type:1,area:['560px','460px'],offset:'auto',title:'用户登录',content:data});
	});
}
WST.currentUrl = function(url){
	if(!url)var url = window.location.href;
	$.post(WST.U('home/index/currenturl'),{url:url},function(data){});
}
/********************* 选项卡切换隐藏 **********************/
$.fn.TabPanel = function(options){
	var defaults = {tab: 0}; 
	var opts = $.extend(defaults, options);
	var t = this;
	$(t).find('.wst-tab-nav li').click(function(){
		$(this).addClass("on").siblings().removeClass();
		var index = $(this).index();
		$(t).find('.wst-tab-content .wst-tab-item').eq(index).show().siblings().hide();
		if(opts.callback)opts.callback(index);
	});
	$(t).find('.wst-tab-nav li').eq(opts.tab).click();
}
/**
 * 去除url中指定的参数(用于分页)
 */
WST.splitURL = function(spchar){
	var url = location.href;
	var urlist = url.split("?");
	var furl = new Array();
	var fparams = new Array();
		furl.push(urlist[0]);
	if(urlist.length>1){
		var urlparam = urlist[1];
			params = urlparam.split("&");
		for(var i=0; i<params.length; i++){
			var vparam = params[i];
			var param = vparam.split("=");
			if(param[0]!=spchar){
				fparams.push(vparam);
			}
		}
		if(fparams.length>0){
			furl.push(fparams.join("&"));
		}
		
	}
	if(furl.length>1){
		return furl.join("?");
	}else{
		return furl.join("");
	}
}
WST.addCart = function(goodsId){
	if(window.conf.IS_LOGIN==0){
		WST.loginWindow();
		return;
	}
	var load = WST.load({msg:'正在处理,请稍后...'});
	$.post(WST.U('home/carts/addCart'),{goodsId:goodsId,buyNum:1},function(data,textStatus){
		 layer.close(load);
	     var json = WST.toJson(data);
	     if(json.status==1){
	     	 WST.getSysMessages('cart');
	    	 WST.msg(json.msg,{icon:1,time:600,shade:false});
	     }else{
	    	 WST.msg(json.msg,{icon:2});
	     }
	});
}

WST.delCart = function(id){
	WST.confirm({content:'您确定要删除该商品吗？',yes:function(index){
		$.post(WST.U('home/carts/delCart'),{id:id,rnd:Math.random()},function(data,textStatus){
		     var json = WST.toJson(data);
		     if(json.status==1){
		    	 WST.msg(json.msg,{icon:1,time:2000},function(){
		    	 	 location.href=WST.U('home/carts/index');
		    	 });
		     }else{
		    	 WST.msg(json.msg,{icon:2});
		     }
		});
	}});
}
WST.changeCartGoods = function(id,buyNum,isCheck){
	$.post(WST.U('home/carts/changeCartGoods'),{id:id,isCheck:isCheck,buyNum:buyNum,rnd:Math.random()},function(data,textStatus){
	     var json = WST.toJson(data);
	     if(json.status!=1){
	    	 WST.msg(json.msg,{icon:2});
	     }
	});
}
WST.dropDownLayerCart = function(dropdown,layer){
	$(dropdown).hover(function () {
        $(this).find(layer).show();
        WST.checkCart();
    }, function () {
    	$(this).find(layer).hide();
    });
	$(layer).hover(function (event) {
		event.stopPropagation();
		$(this).show();
    }, function (event) {
		event.stopPropagation();
    	$(this).hide();
    });
	
}

WST.delCheckCart = function(id,func){
	$.post(WST.U('home/carts/delCart'),{id:id,rnd:Math.random()},function(data,textStatus){
	     var json = WST.toJson(data);
	     if(json.status==1){
	    	 WST.checkCart();
	     }else{
	     }
	});
}
WST.checkCart = function(){
	$('#settlement-carts').html('');
	$('#list-carts').html('<div id="loading" style="padding:24px 0px 9px 0px;text-align: center;"><div class="loader"></div></div>');
	$.post(WST.U('home/carts/getCartInfo'),'',function(data) {
		var json = WST.toJson(data,true);
		if(json.status==1){
			json = json.data;
			if(json.list.length>0){
				var gettpl = document.getElementById('list-cart').innerHTML;
				laytpl(gettpl).render(json, function(html){
					$('#list-carts').html(html);
				});
				$('#settlement-carts').html('<div class="left"><p>共'+json.goodsTotalNum+'件商品</p><p class="price">'+json.goodsTotalMoney+'<span>元</span></p></div><a href="'+window.conf.ROOT+'/home/carts/index" class="right">去购物车结算</a><div class="wst-clear"></div>');
				$('.goodsImgc').lazyload({ effect: "fadeIn",failurelimit : 10,skip_invisible : false,threshold: 200,placeholder:window.conf.RESOURCE_PATH+'/'+window.conf.GOODS_LOGO});//商品默认图片
				WST.dropDownLayer(".j-cartgoods",".j-cartgoods-layer");
				if(json.list.length>5){
					$('#list-carts').css('overflow-y','scroll').css('height','445');
				}else{
					$('#list-carts').css('overflow-y','hidden').css('height','auto');
				}
			}else{
				$('#list-carts').html('<p class="carts">购物车中还没有商品，赶紧选购吧！</p>');
			}
			$('#goodsTotalNum').html(json.goodsTotalNum);
		}else{
			$('#list-carts').html('<p class="carts">购物车中还没有商品，赶紧选购吧！</p>');
			$('#goodsTotalNum').html(0);
		}
	});
}
WST.changeIptNum = function(diffNum,iptId,btnId,id,func){
	var suffix = (id)?"_"+id:"";
	var iptElem = $(iptId+suffix);
	var minVal = parseInt(iptElem.attr('data-min'),10);
	var maxVal = parseInt(iptElem.attr('data-max'),10);
	var tmp = 0;
	if(maxVal<minVal){
		tmp = maxVal;
		maxVal = minVal;
		minVal = tmp;
	}
	var num = parseInt(iptElem.val(),10);
	num = num?num:1;
	num = num + diffNum;
	btnId = btnId.split(',');
	$(btnId[0]+suffix).css('color','#666');
	$(btnId[1]+suffix).css('color','#666');
	if(minVal>=num){
		num=minVal;
		$(btnId[0]+suffix).css('color','#ccc');
	}
	if(maxVal<=num){
		num=maxVal;
		$(btnId[1]+suffix).css('color','#ccc');
	}
	iptElem.val(num);
	if(suffix!='')WST.changeCartGoods(id,num,-1);
	if(func){
		var fn = window[func];
		fn();
	}
}
WST.shopQQ = function(val){
	if(WST.blank(val) !=''){
      return [
              '<a href="tencent://message/?uin='+val+'&Site=QQ交谈&Menu=yes">',
		      '<img border="0" src="http://wpa.qq.com/pa?p=1:'+val+':7" alt="QQ交谈" width="71" height="24" />',
		      '</a>'
		      ].join('');
	}else{
		return '';
	}
}
WST.shopWangWang = function(val){
	if(WST.blank(val) !=''){
		return [
	           '<a target="_blank" href="http://www.taobao.com/webww/ww.php?ver=3&touid='+val+'&siteid=cntaobao&status=1&charset=utf-8">',
		       '<img border="0" src="http://amos.alicdn.com/realonline.aw?v=2&uid='+val+'&site=cntaobao&s=1&charset=utf-8" alt="和我联系" />',
	           '</a>'
		       ].join('');
	}else{
		return '';
	}
}
WST.cancelFavorite = function(obj,type,id,fId,word){
	if(window.conf.IS_LOGIN==0){
		WST.loginWindow();
		return;
	}
	var param = {},str = '商品';
	param.id = fId;
	param.type = type;
	str = (type==1)?'店铺':'商品';
	$.post(WST.U('home/favorites/cancel'),param,function(data,textStatus){
	    var json = WST.toJson(data);
	    if(json.status=='1'){
	       WST.msg(json.msg,{icon:1});
	       $(obj).removeClass('j-fav j-fav3').addClass('j-fav2');
	       if(!word){
		       $(obj).html('关注'+str)[0].onclick = function(){
		    	   WST.addFavorite(obj,type,id,fId); 
		       };
	       }else{
		       $(obj)[0].onclick = function(){
		    	   WST.addFavorite(obj,type,id,fId,1);
		       };
	       }
	    }else{
	       WST.msg(json.msg,{icon:5});
	    }
    });
}
WST.addFavorite = function(obj,type,id,fId,word){
	if(window.conf.IS_LOGIN==0){
		WST.loginWindow();
		return;
	}
	$.post(WST.U('home/favorites/add'),{type:type,id:id},function(data,textStatus){
	     var json = WST.toJson(data);
	     if(json.status==1){
	    	 WST.msg(json.msg,{icon:1});
	    	 $(obj).removeClass('j-fav2').addClass('j-fav  j-fav3');
	    	 if(!word){
		    	 $(obj).html('已关注')[0].onclick = function(){
		    		 WST.cancelFavorite(obj,type,id,json.data.fId); 
		    	 };
	    	 }else{
		    	 $(obj)[0].onclick = function(){
		    		 WST.cancelFavorite(obj,type,id,json.data.fId,1); 
		    	 };
	    	 }
	     }else{
	    	 WST.msg(json.msg,{icon:2});
	     }
	});
}
/**
 * 循环调用及设置商品分类
 * @param id           当前分类ID
 * @param val          当前分类值
 * @param childIds     分类路径值【数组】
 * @param isRequire    是否要求必填
 * @param className    样式，方便将来获取值
 * @param beforeFunc   运行前回调函数
 * @param afterFunc    运行后回调函数
 */
WST.ITSetGoodsCats = function(opts){
	var obj = $('#'+opts.id);
	obj.attr('lastgoodscat',1);
	var level = $('#'+opts.id).attr('level')?(parseInt($('#'+opts.id).attr('level'),10)+1):1;
	if(opts.childIds.length>0){
		opts.childIds.shift();
		if(opts.beforeFunc){
			if(typeof(opts.beforeFunc)=='function'){
				opts.beforeFunc({id:opts.id,val:opts.val});
			}else{
			   var fn = window[opts.beforeFunc];
			   fn({id:opts.id,val:opts.val});
			}
		}
		$.post(WST.U('home/goodscats/listQuery'),{parentId:opts.val},function(data,textStatus){
		     var json = WST.toJson(data);
		     if(json.data && json.data.length>0){
		    	 opts.isLast = false;
			     json = json.data;
		         var html = [];
		         var tid = opts.id+"_"+opts.val;
		         html.push("<select id='"+tid+"' level='"+level+"' class='"+opts.className+"' "+(opts.isRequire?" data-rule='required;' ":"")+">");
			     html.push("<option value=''>-请选择-</option>");
			     for(var i=0;i<json.length;i++){
			       	 var cat = json[i];
			       	 html.push("<option value='"+cat.catId+"' "+((opts.childIds[0]==cat.catId)?"selected":"")+">"+cat.catName+"</option>");
			     }
			     html.push('</select>');
			     $(html.join('')).insertAfter(obj);
			     var tidObj = $('#'+tid);
			     if(tidObj.val()!=''){
			    	obj.removeAttr('lastgoodscat');
			    	tidObj.attr('lastgoodscat',1);
				    opts.id = tid;
				    opts.val = tidObj.val();
				    WST.ITSetGoodsCats(opts);
				 }
			     tidObj.change(function(){
				    opts.id = tid;
				    opts.val = $(this).val();
				    WST.ITGoodsCats(opts);
				 })
		     }else{
		    	 opts.isLast = true;
		    	 opts.lastVal = opts.val;
		     }
		     if(opts.afterFunc){
		    	 if(typeof(opts.afterFunc)=='function'){
		    		 opts.afterFunc(opts);
		    	 }else{
		    	     var fn = window[opts.afterFunc];
		    	     fn(opts);
		    	 }
		     }
		});
	}
}

/**
 * 循环创建商品分类
 * @param id            当前分类ID
 * @param val           当前分类值
 * @param className     样式，方便将来获取值
 * @param isRequire     是否要求必填
 * @param beforeFunc    运行前回调函数
 * @param afterFunc     运行后回调函数
 */
WST.ITGoodsCats = function(opts){
	opts.className = opts.className?opts.className:"j-goodsCats";
	var obj = $('#'+opts.id);
	obj.attr('lastgoodscat',1);
	var level = parseInt(obj.attr('level'),10)+1;
	$("select[id^='"+opts.id+"_']").remove();
	if(opts.isRequire)$('.msg-box[for^="'+opts.id+'_"]').remove();
	if(opts.beforeFunc){
		if(typeof(opts.beforeFunc)=='function'){
			opts.beforeFunc({id:opts.id,val:opts.val});
		}else{
		   var fn = window[opts.beforeFunc];
		   fn({id:opts.id,val:opts.val});
		}
	}
	opts.lastVal = opts.val;
	if(opts.val==''){
		obj.removeAttr('lastgoodscat');
		var lastId = 0,level = 0,tmpLevel = 0,lasObjId;
		$('.'+opts.className).each(function(){
			tmpLevel = parseInt($(this).attr('level'),10);
			if(level <= tmpLevel && $(this).val()!=''){
				level = tmpLevel;
				lastId = $(this).val();
				lasObjId = $(this).attr('id');
			}
		})
		$('#'+lasObjId).attr('lastgoodscat',1);
		opts.id = lasObjId;
    	opts.val = $('#'+lasObjId).val();
	    opts.isLast = true;
	    opts.lastVal = opts.val;
		if(opts.afterFunc){
			if(typeof(opts.afterFunc)=='function'){
				opts.afterFunc(opts);
			}else{
	    	    var fn = window[opts.afterFunc];
	    	    fn(opts);
			}
	    }
		return;
	}
	$.post(WST.U('home/goodscats/listQuery'),{parentId:opts.val},function(data,textStatus){
	     var json = WST.toJson(data);
	     if(json.data && json.data.length>0){
	    	 opts.isLast = false;
	    	 json = json.data;
	         var html = [];
	         var tid = opts.id+"_"+opts.val;
	         html.push("<select id='"+tid+"' level='"+level+"' class='"+opts.className+"' "+(opts.isRequire?" data-rule='required;' ":"")+">");
		     html.push("<option value='' >-请选择-</option>");
		     for(var i=0;i<json.length;i++){
		       	 var cat = json[i];
		       	 html.push("<option value='"+cat.catId+"'>"+cat.catName+"</option>");
		     }
		     html.push('</select>');
		     $(html.join('')).insertAfter(obj);
		     $("#"+tid).change(function(){
		    	opts.id = tid;
		    	opts.val = $(this).val();
		    	if(opts.val!=''){
		    		obj.removeAttr('lastgoodscat');
		    	}
		    	WST.ITGoodsCats(opts);
		     })
	     }else{
	    	 opts.isLast = true;
	    	 opts.lastVal = opts.val;
	     }
	     if(opts.afterFunc){
	    	 if(typeof(opts.afterFunc)=='function'){
	    		 opts.afterFunc(opts);
	    	 }else{
	    	     var fn = window[opts.afterFunc];
	    	     fn(opts);
	    	 }
	     }
	});
}
/**
 * 获取最后已选分类的id
 */
WST.ITGetAllGoodsCatVals = function(srcObj,className){
	var goodsCatId = '';
	$('.'+className).each(function(){
		if($(this).attr('lastgoodscat')=='1')goodsCatId = $(this).attr('id')+'_'+$(this).val();
	});
	goodsCatId = goodsCatId.replace(srcObj+'_','');
	return goodsCatId.split('_');
}
/**
 * 获取最后分类值
 */
WST.ITGetGoodsCatVal = function(className){
	var goodsCatId = '';
	$('.'+className).each(function(){
		if($(this).attr('lastgoodscat')=='1')goodsCatId = $(this).val();
	});
	return goodsCatId;
}
/**
 * 循环创建地区
 * @param id            当前分类ID
 * @param val           当前分类值
 * @param className     样式，方便将来获取值
 * @param isRequire     是否要求必填
 * @param beforeFunc    运行前回调函数
 * @param afterFunc     运行后回调函数
 */
WST.ITAreas = function(opts){
	opts.className = opts.className?opts.className:"j-areas";
	var obj = $('#'+opts.id);
	obj.attr('lastarea',1);
	var level = parseInt(obj.attr('level'),10)+1;
	$("select[id^='"+opts.id+"_']").remove();
	if(opts.isRequire)$('.msg-box[for^="'+opts.id+'_"]').remove();
	if(opts.beforeFunc){
		if(typeof(opts.beforeFunc)=='function'){
			opts.beforeFunc({id:opts.id,val:opts.val});
		}else{
		   var fn = window[opts.beforeFunc];
		   fn({id:opts.id,val:opts.val});
		}
	}
	opts.lastVal = opts.val;
	if(opts.val==''){
		obj.removeAttr('lastarea');
		var lastId = 0,level = 0,tmpLevel = 0,lasObjId;
		$('.'+opts.className).each(function(){
			tmpLevel = parseInt($(this).attr('level'),10);
			if(level <= tmpLevel && $(this).val()!=''){
				level = tmpLevel;
				lastId = $(this).val();
				lasObjId = $(this).attr('id');
			}
		})
		$('#'+lasObjId).attr('lastarea',1);
		opts.id = lasObjId;
    	opts.val = $('#'+lasObjId).val();
	    opts.isLast = true;
	    opts.lastVal = opts.val;
		if(opts.afterFunc){
			if(typeof(opts.afterFunc)=='function'){
				opts.afterFunc(opts);
			}else{
	    	    var fn = window[opts.afterFunc];
	    	    fn(opts);
			}
	    }
		return;
	}
	$.post(WST.U('home/areas/listQuery'),{parentId:opts.val},function(data,textStatus){
	     var json = WST.toJson(data);
	     if(json.data && json.data.length>0){
	    	 json = json.data;
	         var html = [],tmp;
	         var tid = opts.id+"_"+opts.val;
	         html.push("<select id='"+tid+"' level='"+level+"' class='"+opts.className+"' "+(opts.isRequire?" data-rule='required;' ":"")+">");
		     html.push("<option value='' >-请选择-</option>");
		     for(var i=0;i<json.length;i++){
		    	 tmp = json[i];
		       	 html.push("<option value='"+tmp.areaId+"'>"+tmp.areaName+"</option>");
		     }
		     html.push('</select>');
		     $(html.join('')).insertAfter(obj);
		     $("#"+tid).change(function(){
		    	opts.id = tid;
		    	opts.val = $(this).val();
		    	if(opts.val!=''){
		    		obj.removeAttr('lastarea');
		    	}
		    	WST.ITAreas(opts);
		     })
	     }else{
	    	 opts.isLast = true;
	    	 opts.lastVal = opts.val;
	     }
	     if(opts.afterFunc){
	    	 if(typeof(opts.afterFunc)=='function'){
	    		 opts.afterFunc(opts);
	    	 }else{
	    	     var fn = window[opts.afterFunc];
	    	     fn(opts);
	    	 }
	     }
	});
}
/**
 * 循环调用及设置地区
 * @param id           当前地区ID
 * @param val          当前地区值
 * @param childIds     地区路径值【数组】
 * @param isRequire    是否要求必填
 * @param className    样式，方便将来获取值
 * @param beforeFunc   运行前回调函数
 * @param afterFunc    运行后回调函数
 */
WST.ITSetAreas = function(opts){
	var obj = $('#'+opts.id);
	obj.attr('lastarea',1);
	var level = $('#'+opts.id).attr('level')?(parseInt($('#'+opts.id).attr('level'),10)+1):1;
	if(opts.childIds.length>0){
		opts.childIds.shift();
		if(opts.beforeFunc){
			if(typeof(opts.beforeFunc)=='function'){
				opts.beforeFunc({id:opts.id,val:opts.val});
			}else{
			   var fn = window[opts.beforeFunc];
			   fn({id:opts.id,val:opts.val});
			}
		}
		$.post(WST.U('home/areas/listQuery'),{parentId:opts.val},function(data,textStatus){
		     var json = WST.toJson(data);
		     if(json.data && json.data.length>0){
		    	 json = json.data;
		         var html = [],tmp;
		         var tid = opts.id+"_"+opts.val;
		         html.push("<select id='"+tid+"' level='"+level+"' class='"+opts.className+"' "+(opts.isRequire?" data-rule='required;' ":"")+">");
			     html.push("<option value=''>-请选择-</option>");
			     for(var i=0;i<json.length;i++){
			    	 tmp = json[i];
			       	 html.push("<option value='"+tmp.areaId+"' "+((opts.childIds[0]==tmp.areaId)?"selected":"")+">"+tmp.areaName+"</option>");
			     }
			     html.push('</select>');
			     $(html.join('')).insertAfter(obj);
			     var tidObj = $('#'+tid);
			     if(tidObj.val()!=''){
			    	obj.removeAttr('lastarea');
			    	tidObj.attr('lastarea',1);
				    opts.id = tid;
				    opts.val = tidObj.val();
				    WST.ITSetAreas(opts);
				 }
			     tidObj.change(function(){
				    opts.id = tid;
				    opts.val = $(this).val();
				    WST.ITAreas(opts);
				 })
		     }else{
		    	 opts.isLast = true;
		    	 opts.lastVal = opts.val;
		     }
		     if(opts.afterFunc){
		    	 if(typeof(opts.afterFunc)=='function'){
		    		 opts.afterFunc(opts);
		    	 }else{
		    	     var fn = window[opts.afterFunc];
		    	     fn(opts);
		    	 }
		     }
		});
	}
}
/**
 * 获取最后地区的值
 */
WST.ITGetAreaVal = function(className){
	var areaId = '';
	$('.'+className).each(function(){
		if($(this).attr('lastarea')=='1')areaId = $(this).val();
	});
	return areaId;
}
/**
 * 获取最后已选分类的id
 */
WST.ITGetAllAreaVals = function(srcObj,className){
	var areaId = '';
	$('.'+className).each(function(){
		if($(this).attr('lastarea')=='1')areaId = $(this).attr('id')+'_'+$(this).val();
	});
	areaId = areaId.replace(srcObj+'_','');
	return areaId.split('_');
}
/**记录广告点击**/
WST.recordClick = function(adId){
	$.post(WST.U('home/ads/recordClick'),{id:adId},function(data){});
}
/**购物车**/
WST.goodsCart = function(adId){
	WST.currentUrl(WST.U('home/carts/index'));
	location.href=WST.U('home/carts/index');
}
/**
 * 获取用户信息
 */
WST.getSysMessages = function(val){
	if(WST.conf.IS_LOGIN==0)return;
	$.post(WST.U('home/index/getSysMessages'),{tasks:val},function(data){
		var json = WST.toJson(data);
		if(json.message){
			$('#wst-user-messages').html(json.message.num);
			if(parseInt(json.message.num,10)>0){
				$('#wst-user-messages').css('color','#ff6700');
				if($('.j-message-count')[0])$('.j-message-count').show().html(json.message.num);
				if($('#mId_'+json.message.id)[0])$('#mId_'+json.message.id).addClass('wst-msg-tips-box').html(json.message.num);
			}else{
				$('#wst-user-messages').css('color','#666');
				if($('.j-message-count')[0])$('.j-message-count').hide();
				if($('#mId_'+json.message.id)[0])$('#mId_'+json.message.id).removeClass('wst-msg-tips-box').html('');
			}
		}
		if(json.cart){
			$('#goodsTotalNum').html(json.cart.goods);
			html='';
			if(json.cart.goods>0){
				 html +='<div class="cart-info2" onclick="javascript:WST.goodsCart();"><i class="iconfont"></i><span class="name">购物车</span><span class="num">（<span id="goodsTotalNum">'+json.cart.goods+'</span>）</span></div>';
			     if($('.j-cart-count')[0])$('.j-cart-count').show().html(json.cart.goods);
			     $('#goodsCarts').removeClass("active").addClass("active2");
			}else{
				 html +='<div class="cart-info" onclick="javascript:WST.goodsCart();"><i class="iconfont"></i><span class="name">购物车</span><span class="num">（<span id="goodsTotalNum">0</span>）</span></div>';
				 if($('.j-cart-count')[0])$('.j-cart-count').hide().html('');
				 $('#goodsCarts').removeClass("active2").addClass("active");
			}
			$('#goodsCart').html(html);
		}
		if(json.userorder){
			for(var key in json.userorder){
				if($('#mId_'+key)[0]){
					if(json.userorder[key]!='0'){
					    $('#mId_'+key).addClass('wst-msg-tips-box').html(json.userorder[key]);
					}else{
						$('#mId_'+key).removeClass('wst-msg-tips-box').html('');
					}
				}
			}
		}
		if(json.shoporder){
			for(var key in json.shoporder){
				if($('#mId_'+key)[0]){
					if(json.shoporder[key]!='0'){
					    $('#mId_'+key).addClass('wst-msg-tips-box').html(json.shoporder[key]);
					}else{
						$('#mId_'+key).removeClass('wst-msg-tips-box').html('');
					}
				}
			}
		}
	});
}
WST.position = function(mid){
	$.post(WST.U('home/index/position'),{menuId:mid},function(data){});
}
//关闭顶部广告
WST.closeAds = function(t){
  $(t).parent().remove();
  $.cookie('ads_cookie', '1', { expires: 1 }); 
}
WST.closeIframe = function(){
	var index = parent.layer.getFrameIndex(window.name);
	parent.layer.close(index);
}
//搜索选中
WST.searchSelected = function(type){
	if(type==1){
		$('#search-groom').hide();
		$('#search-keys').show();
		$('.wst-search').removeClass('ash').addClass('active');
	}else{
		$('#search-groom').show();
        setTimeout(function(){$('#search-keys').hide();},100);
		$('.wst-search').removeClass('active').addClass('ash');
	}
}
/*签到*/
WST.inSign = function(){
	$("#j-sign").attr('disabled', 'disabled');
	$.post(WST.U('home/userscores/signScore'),{},function(data){
		var json = WST.toJson(data,true);
		if(json.status==1){
			$("#j-sign").addClass('wst-button2').html('已签到');
			WST.msg(json.msg, {icon: 1});
		}else{
			WST.msg(json.msg, {icon: 5});
			$("#j-sign").removeAttr('disabled');
		}
	});
}


WST.slides = function(){
	var slide = $('#wst-slide'), li = slide.find("li");
	var slidecontrols = $('.wst-slide-controls').eq(0), 
		span = slidecontrols.find("span");
	var index = 1, _self = null;
	span.bind("mouseover", function() {
		_self = $(this);
		index = span.index(_self);
		span.removeClass("curr");
		span.eq(index).addClass("curr");
		li.addClass("hide");
		li.css("z-index", -1);
		li.css("display", "none");
		li.eq(index).css("display", "");
		li.eq(index).css("z-index", 1);
		li.eq(index).removeClass("hide");
		clearInterval(timer);
	});
	var timer = setInterval(function() {
		span.removeClass("curr");
		span.eq(index).addClass("curr");
		li.addClass("hide");
		li.css("z-index", -1);
		li.css("display", "none");
		li.eq(index).fadeToggle(500);
		li.eq(index).css("z-index", 1);
		li.eq(index).removeClass("hide");
		index++;
		if (index >= span.length)
			index = 0;
	}, 4000);
	span.bind("mouseout", function() {
		timer = setInterval(function() {
			span.removeClass("curr");
			span.eq(index).addClass("curr");
			li.addClass("hide");
			li.css("z-index", -1);
			li.css("display", "none");
			li.eq(index).fadeToggle(500);
			li.eq(index).css("z-index", 1);
			li.eq(index).removeClass("hide");
			index++;
			if (index >= span.length)
				index = 0;
		}, 4000);
	});
}