var isEmail = function(str){
	return /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(str);
};
var isMobile = function(str){
	return /^((\(\d{3}\))|(\d{3}\-))?1(3|5|8)\d{9}$/.test(str);
};
var isZipCode = function(str){
	return /^[0-9]\d{5}$/.test(str);
};
var isPhone = function(str){
	return /^((\(\d{3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}$/.test(str);
};

/**
* 头部数据ajax初始化
**/
$(document).ready(function(){
	$.ajax({
		type:"post",
		dataType:"json",
		url:"/ajax/headerinfo.jhtml",
		success:function(data){
			//用户名及登录
			if(data.userName!="")
				$("#username_div").html("<span class='username'>"+data.userName+"</span>");
			if(data.isLogin){
				$("#third_login").html("<a href='/logout.jhtml?ref="+window.location.href+"' class='a2'>[退出]</a>");
				$("#header_login_sp").remove();
				$("#third_register").remove();
				//检测用户是否存在未付款订单
				var notPayOrders = eval(data).notPayOrders;
				if(notPayOrders != null && notPayOrders != ""){
					if(notPayOrders.length == 1){
						$("#third_login").append('<a class="payimg" href="/center/orderdetail-'+notPayOrders[0]+'.jhtml" style="color:#B01F24;">您有1笔订单待支付</a>');
					}else if(notPayOrders.length > 1){
						$("#third_login").append('<a class="payimg" href="/center/centerorder.jhtml" style="color:#B01F24;">您有'+notPayOrders.length+'笔订单待支付</a>');
					}
				}
			}
			//头部购物车及购物车页面
			$("[name='carcount']").each(function(){$(this).html(data.carCount)});
			$("[name='carmoney']").each(function(){$(this).html("￥"+data.carTotalPrice+".00")});
		},
		error:function(){}
	});
});
/*显示购物车*/
var showCar = function(){
	if($("#goods_car_show").css("display") == "none"){
		if($("#goods_car_show").html() == ""){
			$.ajax({
				type:"post",
				dataType:"json",
				url:"/ajax/carlist.jhtml",
				beforeSend:function(XMLHttpRequest){
					/*showLoading();*/
				},
				success:function(data){
					var list = eval(data).carList;
					if(list == null || list == ""){
						var str = "";
						str +="<div class=\"goodsbox\">";
						str += "<div class=\"bold\" style=\"text-align:center;\">您还没有添加商品到购物车</div>";
						str +="</div>";
						$("#goods_car_show").html(str);
						$("#goods_car_show").slideToggle("normal",function(){
							$(document).click(function(){showCar();});
						});
					}else{
						var str = "";
						str +="<div class=\"goodsbox\">";
						var total = 0;
						var cont = 0;
						for(var i=0;i<list.length;i++){
							var product = list[i];
							var productCombo = product.productCombo;
							var pname = productCombo==null?product.productName+(product.sellingPoint==null?"":"&nbsp;"+product.sellingPoint):product.productName+(product.sellingPoint==null?"":"&nbsp;"+product.sellingPoint)+"（"+productCombo.comboName+"）";
							var ptitlename = productCombo==null?product.productName+(product.sellingPoint==null?"":" "+product.sellingPointText):product.productName+(product.sellingPoint==null?"":" "+product.sellingPointText)+"（"+productCombo.comboName+"）";
							var price = productCombo==null?product.shopPrice:product.shopPrice+productCombo.totalPrice;
							str += "<div class=\"goodsdiv\">";
							str += "<div class=\"imgbox\"><a href=\"/product/"+product.id+".html\"><img src=\""+product.mainImgUrlFull+"\"/></a></div>";
							str += "<dl>";
							str += "<dt title=\""+ptitlename+"\"><a href=\"/product/"+product.id+".html\">"+pname+"</a></dt>";
							str += "<dd><span class=\"float_l bold cl_red2\">￥"+price+".00×"+product.quantity+"</span><span class=\"float_r\"><a href=\"javascript:void(0);\" onclick=\"delToCar("+product.id+","+(productCombo==null?-1:productCombo.id)+");\" class=\"a2 car_del\">删除</a></span></dd>";
							str += "</dl>";
							str += "</div>";
							total = total + (price * product.quantity);
							cont = cont + product.quantity;
						}
						str += "</div>";
						str += "<div class=\"goods_total\">";
						str +="<p>共有<span class=\"cl_red\">"+cont+"</span>件商品</p>";
						str +="<p>合计：<span class=\"cl_red2 bold\">￥"+total+".00元</span></p>";
						str +="<p><a href=\"/shopping/cart.jhtml\"><img src=\"/images/goods_car_btn.gif\"/></a></p>";
						str += "</div>"
						$("#goods_car_show").html(str);
						$("#goods_car_show").slideToggle("normal",function(){
							$(document).click(function(){showCar();});
						});
					}
				},
				complete:function(XMLHttpRequest,textStatus){
					/*HideLoading();*/
				},
				error:function(){
					alertMsg("读取购物车错误");
				}
			});
		}else{
			$("#goods_car_show").slideToggle("normal",function(){
			$(document).click(function(){showCar();});
			});
		}
	}else if($("#goods_car_show").css("display") == "block"){
		$(document).unbind("click");
		$("#goods_car_show").slideToggle("normal");
	}
	
};
/*加入购物车*/
var addToCar = function(pid,quantity,comboId,reload,jump){
	if(comboId == null)
		comboId = -1;
	$.ajax({
		type:"post",
		dataType:"json",
		url:"/ajax/addtocar.jhtml",
		data:"pid="+pid+"&quantity="+quantity+"&comboid="+comboId,
		beforeSend:function(XMLHttpRequest){
			/*showLoading();*/
		},
		success:function(data,textStatus){
			$("#goods_car_show").html("");
			var msg = eval(data).msg;
			var success = eval(data).success;
			if(success)
				$("#carcount").html(parseInt($("#carcount").html())+1);
			alertMsg(msg,reload);
			if(jump)
				window.location.href="/shopping/cart.jhtml";
		},
		complete:function(XMLHttpRequest,textStatus){
			/*HideLoading();*/
		},
		error:function(){
			alertMsg("系统错误 添加商品失败");
		}
	});
};
/*购物车删除商品*/
var delToCar = function(pid,comboId){
	if(comboId == null){
		comboId = -1;
	}
	$.ajax({
		type:"post",
		dataType:"json",
		url:"/ajax/removetocar.jhtml",
		data:"pid="+pid+"&comboid="+comboId,
		success:function(data,textStatus){
			$("#goods_car_show").html("");
			var msg = eval(data).msg;
			alertMsg(msg,true);
		},
		error:function(){
			alertMsg("系统错误 移除商品失败");
		}
	});
};
/*清空浏览历史*/
var clearViewHistory = function(){
	$.ajax({
		type:"post",
		dataType:"json",
		url:"/ajax/removetohistory.jhtml",
		beforeSend:function(XMLHttpRequest){
			/*showLoading();*/
		},
		success:function(data,textStatus){
			$("#viewhistory").remove();
			alertMsg("清空浏览历史成功");
		},
		complete:function(XMLHttpRequest,textStatus){
			/*HideLoading();*/
		},
		error:function(){
			alertMsg("系统错误 清空浏览历史失败");
		}
	});
};
/*弹出提示层*/
var alertMsg = function(msg,reload){
	if($("#alertbox").html() != null) return ;
	var y;//取滚动条高度
	if (self.pageYOffset) y = self.pageYOffset;
	else if (document.documentElement && document.documentElement.scrollTop) y = document.documentElement.scrollTop;
	else if (document.body) y = document.body.scrollTop;
	
	var top = (screen.height + 100 - 250) / 2 - 150 + y;
	var left = screen.width / 2 - 279 /2;
	var box = "<div id=\"alertbox\" style=\"margin:0 auto;padding:0;width:262px;position:absolute; z-index:11000;top:"+top+"px;left:"+left+"px;\">";
	box += "<p style=\"margin:0;padding:0;\"><img src=\"/images/tcc_tit.gif\"/></p>";
	box += "<div style=\"width:260px;margin:0 auto;border:1px solid #C0C0C0;background:#F5F5F5;overflow:hidden;\">";
	box += "<div style=\"clear:both;padding:20px 20px 10px 20px;color:#565662;font-size:14px;letter-spacing:1px;text-align:center;line-height:24px;overflow:hidden;\">";
	box += "<p style=\"margin:0;padding:0;\">"+msg+"</p>";
	box += "<div><input type=\"button\" style=\"clear:both;margin-top:10px;padding:0;background:url(/images/tcc_btn.gif) no-repeat;border:0;width:61px;height:21px;cursor:pointer;\"/></div>";
	box += "</div>";
	box += "</div>";
	box += "</div>";
	$("body").append(box);
	$("#alertbox").animate({opacity:"1"},500,function(){
		$(this).find("input").click(function(){
			$("#alertbox").animate({opacity:"0"},1000,function(){
				$("#alertbox").remove();
				if(reload) window.location.reload();
			});
		});
	});
	window.setTimeout(function(){
		$("#alertbox").animate({opacity:"0"},1000,function(){
			$("#alertbox").remove();
			if(reload) window.location.reload();
		});
	},2000);
};
//添加收藏
var doAddFavour = function(pid,type){
	$.ajax({
		type:"post",
		dataType:"json",
		url:"/ajax/addfavour.jhtml",
		data:"pid="+pid+"&producttype="+type,
		success:function(data){
			var msg = eval(data).msg;
			alertMsg(msg);
			if(msg=="请先登录")
				window.location.href="http://www.ledaojia.com/login.jhtml?ref="+window.location.href;
		},
		error:function(){
			alertMsg("系统错误 添加收藏失败");
		}
	});
};
//登录/注册弹出层
var showLogin = function(reload){
	if($("#loginbox").html() != null) return ;
	var y;//取滚动条高度
	if (self.pageYOffset) y = self.pageYOffset;
	else if (document.documentElement && document.documentElement.scrollTop) y = document.documentElement.scrollTop;
	else if (document.body) y = document.body.scrollTop;
	
	var top = (screen.height + 100 - 350) / 2 - 150 + y;
	var left = screen.width / 2 - 494 /2;
	
	var box = '<div id="loginbox" class="login_tcc" style="top:'+top+'px;left:'+left+'px;">';
	box += '<p class="login_title"><a id="closebtn" href="javascript:void(0);" class="close"></a></p>';
	//登录
	box += '<div id="logincontent" class="login_con">';
	box += '<ul class="login_menu">';
	box += '<li class="menuon"><a href="javascript:void(0);">登 录</a></li>';
	box += '<li><a name="toreg" href="javascript:void(0);">注 册</a></li>';
	box += '</ul>';
	box += '<table width="100%" cellpadding="0" cellspacing="0" class="login_table">';
	box += '<tr>';
	box += '<td width="26%" class="login_name">用户名：</td>';
	box += '<td colspan="2"><input type="text" name="login_username" class="input1"/></td>';
	box += '</tr>';
	box += '<tr>';
	box += '<td class="login_name">密码：</td>';
	box += '<td colspan="2"><input type="password" name="login_password" class="float_l input1"/><a href="/toresetpwd1.jhtml" class="a6 float_l mar_l10">忘记密码</a></td>';
	box += '</tr>';
	box += '<tr>';
//	box += '<td>&nbsp;</td>';
//	box += '<td width="23%"><input type="checkbox" class="float_l mar_r5"/><strong class="float_l">记住用户名</strong></td>';
//	box += '<td width="51%"><input type="checkbox" class="float_l mar_r5"/><strong class="float_l">自动登录</strong></td>';
//	box += '</tr>';
	box += '<tr>';
	box += '<td>&nbsp;</td>';
	box += '<td><input type="button" name="dologin" class="logintcc_btn" value=""/></td>';
	box += '<td>新用户?<a href="javascript:void(0);" name="toreg" class="a6 mar_l5">立即注册</a></td>';
	box += '</tr>';
	box += '</table>';
	box += '</div><!--login_con end-->';
	//注册
	box += '<div id="regcontent" class="login_con" style="display:none">';
	box += '<ul class="login_menu">';
	box += '<li><a name="tologin" href="javascript:void(0);">登 录</a></li>';
	box += '<li class="menuon"><a href="javascript:void(0);">注 册</a></li>';
	box += '</ul>';
	box += '<form name="regform" action="/ajax/reg.jhtml" method="post">';
	box += '<table width="100%" cellpadding="0" cellspacing="0" class="login_table">';
	box += '<tr>';
	box += '<td width="36%" class="login_name">Email地址：</td>';
	box += '<td width="64%"><input type="text" class="input1 cl_gray9" value="Email地址将作为您登录乐到家的用户名" name="reg_email"><span></span></td>';
	box += '</tr>';
	box += '<tr>';
	box += '<td class="login_name">设定密码：</td>';
	box += '<td><input type="password" class="input1" name="reg_password"><span></span></td>';
	box += '</tr>';
	box += '<tr>';
	box += '<td class="login_name">再输入一次密码：</td>';
	box += '<td><input type="password" class="input1" name="reg_repassword"><span></span></td>';
	box += '</tr>';
	box += '<tr>';
	box += '<td>&nbsp;</td>';
	box += '<td><input type="checkbox" name="service" checked="checked" class="mar_r5 float_l">';
	box += '<p class="float_l">我已阅读并同意<a target="_blank" href="/contract.jhtml">《乐到家服务条款》</a></p></td>';
	box += '</tr>';
	box += '<tr>';
	box += '<td>&nbsp;</td>';
	box += '<td><input type="button" name="doregister" class="regtcc_btn" value=""/></td>';
	box += '</tr>';
	box += '</table>';
	box += '</form>';
	box += '</div><!--login_con end-->';
	
	box += '<p><img src="/images/login_btm.gif"/></p>';
	box += '</div><!--logintcc end-->';
	$("body").append(box);
	$("#closebtn").click(function(){$("#loginbox").remove();});
	$("#closebtn").hover(function(){$(this).attr("class","close_on");},function(){$(this).attr("class","close");});
	$("#loginbox a[name='toreg']").click(function(){$("#logincontent").hide();$("#regcontent").show();});
	$("#loginbox a[name='tologin']").click(function(){$("#regcontent").hide();$("#logincontent").show();});
	$("#loginbox").find(".input1").focus(function(){$(this).addClass("input_border")});
	$("#loginbox").find(".input1").blur(function(){$(this).removeClass("input_border")});
	$("#loginbox input[name='reg_email']").focus(function(){
		if($("#loginbox input[name='reg_email']").val()=="Email地址将作为您登录乐到家的用户名"){
			$("#loginbox input[name='reg_email']").val("");
			$("#loginbox input[name='reg_email']").removeClass("cl_gray9");
		}
	});
	$("#loginbox input[name='reg_email']").blur(function(){
		if($("#loginbox input[name='reg_email']").val()=="Email地址将作为您登录乐到家的用户名" || $("#loginbox input[name='reg_email']").val() == ""){
			$("#loginbox input[name='reg_email']").val("Email地址将作为您登录乐到家的用户名");
			$("#loginbox input[name='reg_email']").addClass("cl_gray9");
		}
	});
	
	$("#loginbox input[name='dologin']").click(function(){
		var username = $("#loginbox input[name='login_username']").val();
		var pwd = $("#loginbox input[name='login_password']").val();
		if((!isEmail(username)) && (!isMobile(username))){
			alertMsg("email地址或手机号不合法",false);
			$("#loginbox input[name='login_username']")[0].focus();
			return ;
		}
		if(pwd == "" || pwd.length < 5 || pwd.length > 17){
			alertMsg("密码长度应大于5且小于17个字符",false);
			$("#loginbox input[name='login_password']")[0].focus();
			return ;
		}
		$.ajax({
		type:"post",
		dataType:"json",
		url:"/ajax/login.jhtml",
		data:"username="+username+"&password="+pwd,
		success:function(data){
			//用户名及登录
			if(data.success){
				$("#loginbox").remove();
				if(reload)
					window.location.reload();
			}else
				alertMsg(data.msg);
		},
		error:function(){}
		});
	});
	
	$("#loginbox input[name='doregister']").click(function(){
		var username = $("#loginbox input[name='reg_email']").val();
		var pwd = $("#loginbox input[name='reg_password']").val();
		var repwd = $("#loginbox input[name='reg_repassword']").val();
		if(!isEmail(username)){
			alertMsg("email地址不合法",false);
			$("#loginbox input[name='reg_email']")[0].focus();
			return ;
		}
		if(pwd == "" || pwd.length < 5 || pwd.length > 17){
			alertMsg("密码长度应大于5且小于17个字符",false);
			$("#loginbox input[name='reg_password']")[0].focus();
			return ;
		}
		if(pwd != repwd){
			alertMsg("两次输入的密码不一致",false);
			$("#loginbox input[name='reg_repassword']")[0].focus();
			return ;
		}
		if($("#loginbox input[name='service']").attr("checked") != true){
			alertMsg("请阅读并选择同意服务条款",false);
			return ;
		}
		$.ajax({
		type:"post",
		dataType:"json",
		url:"/ajax/register.jhtml",
		data:"email="+username+"&password="+pwd,
		success:function(data){
			//用户名及登录
			if(data.success){
				alertMsg("注册成功");
				$("#loginbox").remove();
				if(reload)
					window.location.reload();
			}else
				alertMsg(data.msg);
		},
		error:function(){}
		});
	});
};

$(document).ready(function(){
	$("img[alt='量子统计']").css("display","none");
});
