var swfu,swfuBanner;
var cfg_lang="zh-cn";
if(cfg_lang=="zh-cn"){
	var lang = ["上传图片","正在上传","上传成功","Ajax处理失败","删除后不可恢复，是否确认删除？",'远程图片'];
}else{
	var lang = ["Upload","Uploading","Success","Ajax Error","Deleted and unrecoverable, whether to confirm the deletion?"];
}
var swfu_settings = {
	upload_url : "/plugins/swfupload/upload.php",
	flash_url : "/plugins/swfupload/flash/swfupload.swf",
	file_size_limit : "2 MB",
	button_placeholder_id : "spanSWFUploadButton",
	button_image_url : "/plugins/swfupload/uploadBtn.png",
	button_width : 89,
	button_height : 30,
	debug:false,
	button_text:"<span class='redText'>"+lang[0]+"</span>",
	button_text_style:".redText { color: #0055B8; font-weight:bold; font-size:14px; word-spacing : 100px;text-align:center;}",
	button_text_top_padding:3,
	button_window_mode:"opaque",
	file_post_name:"Filedata",
	file_upload_limit:0,
	file_queue_limit:1,
	post_params:{
		"type":"",
		"createThumb":"false"
	},
	file_types:"*.jpg;*.gif;*.png;*.rar;*.zip",
	swfupload_loaded_handler:function(){
		//alert("swfupload loaded");
	},
	file_dialog_start_handler:function(){
		//alert("file dialog start");
	},
	file_queued_handler:function(){
		//alert("file_queued");
		swfu.startUpload();
	},
	file_queue_error_handler:function(){
		alert("file_queue_error");
	},
	upload_start_handler:function(){
		//alert("upload_start");
		swfu.setButtonText("<span class='redText'>"+lang[1]+"</span>");
		swfu.setButtonDisabled(true);
	},
	upload_progress_handler:function(){
		//alert("upload_progress");
	},
	upload_error_handler:function(){
		alert("upload_error");
	},
	upload_success_handler:function(obj,data,resp){
		alert(lang[2]);
	},
	upload_complete_handler:function(){
	}
}
function SetHome(obj,vrl){
        try{
                obj.style.behavior='url(#default#homepage)';obj.setHomePage(vrl);
        }
        catch(e){
                if(window.netscape){
                        try{
                                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");  
                        }catch (e){
                        		alert("抱歉！您的浏览器不支持直接设为首页。请在浏览器地址栏输入“about:config”并回车然后将[signed.applets.codebase_principal_support]设置为“true”，点击“加入收藏”后忽略安全提示，即可设置成功。");
                        }
                        var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
                        prefs.setCharPref('browser.startup.homepage',vrl);
                 }else{  
		        alert('抱歉，您的浏览器不支持自动设置首页, 请使用浏览器菜单手动设置!');
		    }
        }
}

function addFavorite(){var b=window.location.href;var a=document.title;try{window.external.addFavorite(b,a);}catch(c){try{window.sidebar.addPanel(a,b,"");}catch(c){alert("加入收藏失败，请使用Ctrl+D进行添加");}}}
var Z=0;

var sWeek = new Array("星期日","星期一","星期二","星期三","星期四","星期五","星期六");
var dNow = new Date();
var CalendarData=new Array(100);var madd=new Array(12);var tgString="甲乙丙丁戊己庚辛壬癸";var dzString="子丑寅卯辰巳午未申酉戌亥";var numString="一二三四五六七八九十";var monString="正二三四五六七八九十冬腊";var weekString="日一二三四五六";var sx="鼠牛虎兔龙蛇马羊猴鸡狗猪";var cYear,cMonth,cDay,TheDate;
CalendarData = new Array(               0xA4B,0x5164B,0x6A5,0x6D4,0x415B5,0x2B6,0x957,0x2092F,0x497,0x60C96,                     0xD4A,0xEA5,0x50DA9,0x5AD,0x2B6,0x3126E, 0x92E,0x7192D,0xC95,0xD4A,                       0x61B4A,0xB55,0x56A,0x4155B, 0x25D,0x92D,0x2192B,0xA95,0x71695,0x6CA,                   0xB55,0x50AB5,0x4DA,0xA5B,0x30A57,0x52B,0x8152A,0xE95,0x6AA,0x615AA,                     0xAB5,0x4B6,0x414AE,0xA57,0x526,0x31D26,0xD95,0x70B55,0x56A,0x96D,                    0x5095D,0x4AD,0xA4D,0x41A4D,0xD25,0x81AA5, 0xB54,0xB6A,0x612DA,0x95B,
0x49B,0x41497,0xA4B,0xA164B, 0x6A5,0x6D4,0x615B4,0xAB6,0x957,0x5092F,
0x497,0x64B, 0x30D4A,0xEA5,0x80D65,0x5AC,0xAB6,0x5126D,0x92E,0xC96,                   0x41A95,0xD4A,0xDA5,0x20B55,0x56A,0x7155B,0x25D,0x92D,0x5192B,0xA95,                   0xB4A,0x416AA,0xAD5,0x90AB5,0x4BA,0xA5B, 0x60A57,0x52B,0xA93,0x40E95);
madd[0]=0;madd[1]=31;madd[2]=59;madd[3]=90;
madd[4]=120;madd[5]=151;madd[6]=181;madd[7]=212; 
madd[8]=243;madd[9]=273;madd[10]=304;madd[11]=334; 
var D=new Date(); 
var yy=D.getFullYear(); 
var mm=D.getMonth()+1; 
var dd=D.getDate(); 
var ww=D.getDay(); 
var ss=parseInt(D.getTime() / 1000); 
var COLDialog=null;
jQuery(function(){
	jQuery("a#J_setHome").click(function(){
		SetHome(this,location.href);
		return false;
	});
	jQuery("a#J_addFav").click(function(){
		addFavorite();
		return false;
	});

	if($("#week").length==1){
		$("#week").html(getDayOfWeek());
	}
	if($("#lunarDay").length==1){
		$("#lunarDay").html(GetLunarDay(yy,mm,dd));
	}
	
	jQuery("form#navSearchForm").submit(function(){
			var key = jQuery("form#navSearchForm").find("input[name='key']").val();
			if(key=="输入商品名称进行搜索"){
				jQuery("form#navSearchForm").find("input[name='key']").focus();
				return false;
			}
	});
	jQuery.fn.fb = function(param){
			$(this).val(param);
			$(this).focus(function(){
				var val = $(this).val();
				if(val==param){$(this).val("");}
				$(this).css({color:"#000"})
			});
			$(this).blur(function(){
				var val = $(this).val();
				if(val==""){$(this).val(param);$(this).css({color:"#999"})}
			});
	};
	$(".J_submit").click(function(){
		$(this).parent("div").parent("div").parent("form").submit();
	});
	if($(".transSelect").length>0 && $.fn.jqTransform){
		$(".transSelect").jqTransSelect();
	}

	$("#J_logout").click(function(){
		//if(!confirm("是否确认退出？")){return false;}
		location.href = "/user/logout";
	});
	if(("select[name='provinceId']").length>0){
		$("select[name='provinceId']").change(function(){
			var dom = $(this).parent("div.element");var id = $(this).val();if(id==''){ return false; }
				var sdata = 'inajax=1&act=sub&id='+id; var surl = '/data/district';
				$.ajax({ type:"POST",url:surl,data:sdata,cache:false,dataType:"json",success:function(json){
						if(json.success){
							if(json.data.length>0){
								var option = '';
								for(var i=0;i<json.data.length;i++){ var item = json.data[i];option += '<option value="'+item.id+'">'+item.name+'</option>'; }
								$('select[name="cityId"]').find("option").eq(0).siblings().remove();$('select[name="cityId"]').append(option);
								if($('select[name="cityId"]').hasClass('transSelect')){
									$('select[name="cityId"]').siblings().remove();
									$('select[name="cityId"]').removeClass("jqTransformHidden").unwrap();
									$('select[name="cityId"]').jqTransSelect();
								}
							}
						}
					}
				});
		});
		$('select[name="cityId"]').change(function(){
			var dom = $(this).parent("div.element");
			var id = $(this).val();
			if(id==''){ return false; }
				var sdata = 'inajax=1&act=sub&id='+id;var surl = '/data/district';
				$.ajax({ type:"POST",url:surl,data:sdata,cache:false,dataType:"json",success:function(json){
						if(json.success){
							if(json.data.length>0){
								var option = '';
								for(var i=0;i<json.data.length;i++){ var item = json.data[i];option += '<option value="'+item.id+'">'+item.name+'</option>'; }
								$('select[name="countyId"]').find("option").eq(0).siblings().remove();$('select[name="countyId"]').append(option);
								if($('select[name="countyId"]').hasClass('transSelect')){
									$('select[name="countyId"]').siblings().remove();
									$('select[name="countyId"]').removeClass("jqTransformHidden").unwrap();
									$('select[name="countyId"]').jqTransSelect();
								}
							}
						}
					}
				});
		});
	}
	if($("#uploadBtn").length==1){
		var doc = document,
		wa = doc.createElement('script'),
		s = doc.getElementsByTagName('script')[0];
		wa.type = 'text/javascript';
		wa.charset = 'utf-8';
		wa.async = true;
		wa.src = '/plugins/swfupload/swfupload.js';
		s.parentNode.insertBefore(wa, s).onreadystatechange=function(){
			if(this.readyState=="loaded"){
			swfu_settings.button_placeholder_id = "uploadBtn";
			swfu = new SWFUpload(swfu_settings);
			swfu.uploadSuccess = function(obj,data,resp){
					var data = eval('('+data+')');
					if(data.success){
						var url = decodeURIComponent(data.url);
						swfu.setButtonText("<span class='redText'>上传成功</span>");
						swfu.setButtonDisabled(false);
						$("#img-src").attr("src","/"+url);
						$("#thumbId").val(data.id);
					}
			}
			}
		}
	}

	$("#J_cartAdd_submit").click(function(){
		var goodsId =$(this).attr('goodsId');
		var  pnum = $("#goodsCount").val();var spec = $("#spec").val();var remark = $("#goodsRemark").val();
		if(!pnum){pnum=1;}
		if(!spec || typeof(spec)=='undefined'){spec='';}if(!remark || typeof(remark)=='undefined'){remark='';}
		$(".btn_box").css('height','100px');
		$(this).attr('disabled','disabled');
		if(!isNaN(parseInt(pnum,10)) && goodsId && !isNaN(parseInt(goodsId,10))){
			var sdata = "inajax=1&act=add&goodsId="+goodsId+"&pnum="+pnum+"&spec="+spec+"&remark="+remark;
			$.ajax({
				type:"POST",
				url:"/purchase/shoppingcart",
				data:sdata,
				dataType:"json",
				cache:false,
				success:function(data){
					if($.type(data)=="object"){
						//G.ui.popup.showMsg(data.message,{type:data.type});
						icon='error';if(data.type==1){icon='warn';}else if(data.type==3){icon='right';}
						if(data.cart){
							var cartInfo_number  = $('#cartInfo_number').html();
							if(isNaN(parseInt(cartInfo_number,10))){cartInfo_number=0;}
							cartInfo_number++;
							$('#cartInfo_number').html(cartInfo_number);
						}
						if(data.data=="nologin"){
							COLDialog = COL.dialog.open('/user/login?style=dialog',{width:430,boder : 'thin',delay:0,head:'none',close:function(){ $("#J_cartAdd_submit").removeAttr('disabled');$(".btn_box").css('height','50px');userHello(); }});
							return;
							//COL.dialog({head:false,content:'系统繁忙，请稍后再试！'});
							//location.href="/user/login";
							//var favDialog=$('<div id="layer_global" class="layer_global"><div class="layer_global_mod"><b class="icon icon_msg4 icon_msg4_'+icon+'"></b><h4 class="layer_global_tit">'+data.message+'</h4></div></div>').dialog({ title:'提示',width:450,height:150,modal:true,resizable:false,buttons:{ '确定':function(){ favDialog.dialog('destroy'); },'马上登录':function(){ location.href="/user/login/?cb=/purchase/shoppingcart"; } } });
						}else if(data.success==true){
							$("#J_cartAdd_submit").removeAttr('disabled');$(".btn_box").css('height','50px');
							//var favDialog=$('<div id="layer_global" class="layer_global"><div class="layer_global_mod"><b class="icon icon_msg4 icon_msg4_'+icon+'"></b><h4 class="layer_global_tit">'+data.message+'</h4></div></div>').dialog({ title:'提示',width:450,height:150,modal:true,resizable:false,buttons:{ '确定':function(){ favDialog.dialog('destroy'); },'马上付款':function(){ location.href="/purchase/shoppingcart"; } } });
							COLDialog = COL.dialog({head:'none',border:5,padding:"30px 30px 20px 30px",content:'<div class="cart_win_con" id="cart_win_con"><p class="cart_win_txt"><i class="cart_win_txt_icon"></i><span id="J_popCart_msgTxt">'+data.message+'</span></p><p class="cart_win_msg none">3秒后自动关闭</p><p class="cart_win_btn"><a class="cwb_cart" href="/purchase/shoppingcart">查看购物袋</a><a class="cwb_vip" href="javascript:void(0)">返回页面</a></p></div>',close:function(){ userHello(); }});
							$("#cart_win_con").find("a.cwb_vip").click(function(){ COLDialog.close(); });
							//var c = setTimeout(function(){ COLDialog.close(); },3000);
							return;
						}else if(data.success==false){
							COL.dialog.mini({type:'error',content:data.message});
						}
						if(data.success){
							COL.dialog.mini({type:'success',content:data.message});
						}
						$("#J_cartAdd_submit").removeAttr('disabled');$(".btn_box").css('height','50px');
					}
				},error:function(){
					COL.dialog.mini('系统繁忙，请稍后再试！');
					$("#J_cartAdd_submit").removeAttr('disabled');
					$(".btn_box").css('height','50px');
				}
			});
		}
	});
});

function addToCart(goodsId,d){
	var  pnum = $("#goodsCount").val();var spec = $("#spec").val();var remark = $("#goodsRemark").val();
	if(!pnum){pnum=1;}
	if(!spec || typeof(spec)=='undefined'){spec='';}if(!remark || typeof(remark)=='undefined'){remark='';}
	if(!isNaN(parseInt(pnum,10)) && goodsId && !isNaN(parseInt(goodsId,10))){
			var sdata = "inajax=1&act=add&goodsId="+goodsId+"&pnum="+pnum+"&spec="+spec+"&remark="+remark;
			$.ajax({
				type:"POST",
				url:"/purchase/shoppingcart",
				data:sdata,
				dataType:"json",
				cache:false,
				success:function(data){
					$(".btn_box").css('height','50px');
					if($.type(data)=="object"){
						//G.ui.popup.showMsg(data.message,{type:data.type});
						icon='error';if(data.type==1){icon='warn';}else if(data.type==3){icon='right';}
						if(data.cart){
							var cartInfo_number  = $('#cartInfo_number').html();
							if(isNaN(parseInt(cartInfo_number,10))){cartInfo_number=0;}
							cartInfo_number++;
							$('#cartInfo_number').html(cartInfo_number);
						}
						if(data.data=="nologin"){
							COLDialog = COL.dialog.open('/user/login?style=dialog',{width:430,boder : 'thin',delay:0,head:'none',close:function(){ $("#J_cartAdd_submit").removeAttr('disabled');$(".btn_box").css('height','50px');userHello(); }});
							return;
							//COL.dialog({head:false,content:'系统繁忙，请稍后再试！'});
							//location.href="/user/login";
							//var favDialog=$('<div id="layer_global" class="layer_global"><div class="layer_global_mod"><b class="icon icon_msg4 icon_msg4_'+icon+'"></b><h4 class="layer_global_tit">'+data.message+'</h4></div></div>').dialog({ title:'提示',width:450,height:150,modal:true,resizable:false,buttons:{ '确定':function(){ favDialog.dialog('destroy'); },'马上登录':function(){ location.href="/user/login/?cb=/purchase/shoppingcart"; } } });
						}else if(data.success==true){
							$("#J_cartAdd_submit").removeAttr('disabled');$(".btn_box").css('height','50px');
							//var favDialog=$('<div id="layer_global" class="layer_global"><div class="layer_global_mod"><b class="icon icon_msg4 icon_msg4_'+icon+'"></b><h4 class="layer_global_tit">'+data.message+'</h4></div></div>').dialog({ title:'提示',width:450,height:150,modal:true,resizable:false,buttons:{ '确定':function(){ favDialog.dialog('destroy'); },'马上付款':function(){ location.href="/purchase/shoppingcart"; } } });
							COLDialog = COL.dialog({head:'none',border:5,padding:"30px 30px 20px 30px",content:'<div class="cart_win_con" id="cart_win_con"><p class="cart_win_txt"><i class="cart_win_txt_icon"></i><span id="J_popCart_msgTxt">'+data.message+'</span></p><p class="cart_win_msg none">3秒后自动关闭</p><p class="cart_win_btn"><a class="cwb_cart" href="/purchase/shoppingcart">查看购物袋</a><a class="cwb_vip" href="javascript:void(0)">返回页面</a></p></div>',close:function(){ userHello(); }});
							$("#cart_win_con").find("a.cwb_vip").click(function(){ COLDialog.close(); });
							//var c = setTimeout(function(){ COLDialog.close(); },3000);
							return;
						}else if(data.success==false){
							COL.dialog.mini({type:'error',content:data.message});
						}
						if(data.success){
							COL.dialog.mini({type:'success',content:data.message});
						}						
					}
				},error:function(){
					COL.dialog.mini({type:'error',content:'系统繁忙，请稍后再试！'});
					$(".btn_box").css('height','50px');
				}
			});
	}
}

function addToFavorite(goodsId){
	if(goodsId && !isNaN(parseInt(goodsId,10))){
			var sdata = "inajax=1&act=add&goodsId="+goodsId;
			$.ajax({
				type:"POST",
				url:"/user/favorite/",
				data:sdata,
				dataType:"json",
				cache:false,
				success:function(data){
					if($.type(data)=="object"){
						COL.dialog.mini({type:(data.success?"success":"error"),content:data.message});
					}else{
						COL.dialog.mini({type:'error',content:'系统繁忙，请稍后再试！'});
					}
				}
			});
	}
}


   function getDayOfWeek(){
      var day = new Date(); 
      var today = new Array("星期天","星期一","星期二","星期三","星期四","星期五","星期六");
      return today[day.getDay()]; //day.getDay();根据Date返一个星期中的某其中0为星期日
   }



function getFullYear(d){// 修正firefox下year错误
yr=d.getYear();if(yr<1000)
yr+=1900;return yr;}

function GetBit(m,n) {  return (m>>n)&1; }
function e2c()
{  
TheDate= (arguments.length!=3) ? new Date() : new Date(arguments[0],arguments[1],arguments[2]);  
var total,m,n,k;  
var isEnd=false;  
var tmp=TheDate.getFullYear();  
 total=(tmp-1921)*365+Math.floor((tmp-1921)/4)+madd[TheDate.getMonth()]+TheDate.getDate()-38;  if (TheDate.getYear()%4==0&&TheDate.getMonth()>1) { total++;}  for(m=0;;m++)  {    k=(CalendarData[m]<0xfff)?11:12;    for(n=k;n>=0;n--)    {      if(total<=29+GetBit(CalendarData[m],n))      {        isEnd=true; break;      }      total=total-29-GetBit(CalendarData[m],n);    }    if(isEnd) break;  }  cYear=1921 + m; cMonth=k-n+1; cDay=total;  if(k==12)   {    if(cMonth==Math.floor(CalendarData[m]/0x10000)+1) { cMonth=1-cMonth; }    if(cMonth>Math.floor(CalendarData[m]/0x10000)+1)  { cMonth--; }   }}
function GetcDateString(){ var tmp="";  tmp+=tgString.charAt((cYear-4)%10); 
tmp+=dzString.charAt((cYear-4)%12);  
tmp+="年 "; 
if(cMonth<1) { tmp+="(闰)"; tmp+=monString.charAt(-cMonth-1); } else {tmp+=monString.charAt(cMonth-1);}  tmp+="月";  tmp+=(cDay<11)?"初":((cDay<20)?"十":((cDay<30)?"廿":"三十")); 
if (cDay%10!=0||cDay==10) { tmp+=numString.charAt((cDay-1)%10); }  
return tmp;
}
function GetLunarDay(solarYear,solarMonth,solarDay)
{
 if (solarYear<1921 || solarYear>2020)  {          return ""; 
  }        else        {          solarMonth = (parseInt(solarMonth)>0) ? (solarMonth-1) : 11;          e2c(solarYear,solarMonth,solarDay); return GetcDateString();        }
  
 }
function showDate() {
	var sValue = getFullYear(dNow)+"年"+(dNow.getMonth()+1)+"月"+dNow.getDate()+"日"+" "+sWeek[dNow.getDay()]+" ";
	sValue+=GetLunarDay(yy,mm,dd);
	    document.getElementById("pDate").innerHTML = sValue;
};
function login(){
	if(COL&&COL.dialog){
		COLDialog = COL.dialog.open('/user/login?style=dialog&mod=login',{boder : 'thin',head:'none',close:function(){ userHello(); }});		
	}else{
		return location.href="/user/login?cb="+escape(location.href).replace(/\//g,"%2F"),!1;
	}
}
function regist(){
		if(COL&&COL.dialog){
		COLDialog = COL.dialog.open('/user/login?style=dialog&mod=register',{boder : 'thin',padding : '20px 30px',head:'none',close:function(){ userHello(); }});		
	}else{
		return location.href="/user/register?cb="+escape(location.href),!1
	}
}

$(function(){
	$.extend({
		slider:function(options){
			var defaults = {contentCls:"mfpSlide-con",navCls:"mfpSlide-nav",linkCls:"mScm-link",timer:3000,activeTriggerCls:"selected",intval:null};
			var opts = $.extend(defaults,options);
			var activeIndex = 0;
			var allIndex = $("."+opts.contentCls).find("li").length;
			function init(){
				navtrigger();
				opts.intval = setInterval(function(){slide();},opts.timer);
			}
			function navtrigger(){
				$("."+opts.contentCls+" li a."+opts.linkCls).mouseover(function(){
					clearInterval(opts.intval);
				}).mouseout(function(){
					opts.intval = setInterval(function(){slide();},opts.timer);
				});
				$("."+opts.navCls).find("li").each(function(index){
					$(this).click(function(){
						clearInterval(opts.intval);
						targetIndexTmp=index;
						activeIndex=$("li."+opts.activeTriggerCls).index();
						$("."+opts.navCls).find("li").eq(activeIndex).removeClass(opts.activeTriggerCls);
						$("."+opts.navCls).find("li").eq(targetIndexTmp).addClass(opts.activeTriggerCls);
						var acp = $("."+opts.contentCls).find("li").eq(activeIndex);
						var ncp = $("."+opts.contentCls).find("li").eq(targetIndexTmp);
						if(acp.find("b").length==1){acp.find("b").animate({top:-40,opacity:0});}
						opts.intval = setInterval(function(){slide();},opts.timer);
						acp.fadeOut('slow',function(){
							ncp.fadeIn('slow');
							if(ncp.find("b").length==1){ncp.find("b").animate({top:-10,opacity:1});}
							activeIndex=targetIndexTmp;
						});
					});
				});
			}
			function slide(targetIndex){
				targetIndex = activeIndex+1;
				if(targetIndex>=allIndex){targetIndex=0;}
				$("."+opts.navCls).find("li").eq(activeIndex).removeClass(opts.activeTriggerCls);
				$("."+opts.navCls).find("li").eq(targetIndex).addClass(opts.activeTriggerCls);
				var acp = $("."+opts.contentCls).find("li").eq(activeIndex);
				var ncp = $("."+opts.contentCls).find("li").eq(targetIndex);
				if(acp.find("b").length==1){acp.find("b").animate({top:-40,opacity:0});}
				acp.fadeOut('slow',function(){
					ncp.fadeIn('fast');
					if(ncp.find("b").length==1){ncp.find("b").animate({top:-10,opacity:1});}
					activeIndex=targetIndex;
				});
			}
			init();
		}
	});
	$.ajax({url:"/user/hello?r="+Math.random(),dataType:"jsonp",scriptCharset:"utf-8",success:function(a){a&&a.info&&$("#loginbar").html(a.info)}});
});
function userHello(){
	$.ajax({url:"/user/hello?r="+Math.random(),dataType:"jsonp",scriptCharset:"utf-8",success:function(a){a&&a.info&&$("#loginbar").html(a.info)}});
}