$(function(){
	duihuan();

	//登录窗体的 X  号，关闭按钮
	$('#the_close').click(function(){
		$('#modal-login').slideUp();
		$('#zhezhao').hide();
	});
	//登录窗体的取消的时候
	$('#the_cancel').click(function(){
		$('#modal-login').slideUp();
		$('#zhezhao').hide();
	});
	
	//登录的验证//网站登录按钮
	$('#btn_submit').click(function(){
		var errorDiv=$('#error_div');
		var userName=$('#username');
		var password=$('#password');
		//开始验证用户名，客户端验证
		if(userName.val().length<4){
			errorDiv.html('用户名不能小于4位').css({'visibility':'visible'});
			userName.focus();
			return ;
		}
		errorDiv.css({'visibility':'hidden'});
		//开始验证密码，客户端验证
		if(password.val().length<6  || password.val().length>16){
//			errorDiv.html('密码应该为6到16个字符组成').css({'visibility':'hidden'});
			errorDiv.html('密码应该为6到16个字符组成').css({'visibility':'visible'});
			password.focus();
			return ;
		}
		errorDiv.css({'visibility':'hidden'});
		$.post('dologin_url.php',{'username':userName.val(),'password':password.val()},function(data){
			var json=eval("("+data+")");
			if(json.success=="true"){
				window.location.href="lipinlist.php";
			}else{
				if(json.error=='username'){
					errorDiv.html('用户名不能小于4位').css({'visibility':'visible'});
				}else if(json.error=='pwd'){
					errorDiv.html('密码应该为6到16个字符组成').css({'visibility':'visible'});
				}else if(json.error=='loginError'){
					errorDiv.html('用户名或密码不正确').css({'visibility':'visible'});
				}
				window.setTimeout(function(){
					errorDiv.css({'visibility':'hidden'});
				},3000);
			}
		});
		
	});
	
	
	
	// 处理 窗口滚动事件，让购物车选项卡，随屏幕动
	window.onscroll = function() {
		var scrollTop = $(window).scrollTop();
		if (scrollTop > 180) {
			$('#theCart').css( {
				'position' : 'absolute',
				'top' : (scrollTop + 25) + "px",
				'z-index':"100"
			});
			$('#mylipinlist').css({'border':'1px solid #cbcbcb'});
			
		} else {
			$('#theCart').css( {
				'position' : 'static',
				'top' : "1px",
				'z-index':"100"
			});
			$('#mylipinlist').css({'border':'0px'});
		}
		//$('#sendOut').mouseover();
	}
	
	
	//下一页
	$('#xiaye').click(function(){
		$('#theCart').css( {
			'position' : 'static',
			'top' : "1px",
			'z-index':"100"
		});
		
		
		var pageNo=parseInt($('#pageNo').val());
		var pageSize=parseInt($('#pageSize').val());
		var totalCount=parseInt($('#zongshu').val());
		//
		var maxPage=totalCount%pageSize==0?totalCount/pageSize:totalCount/pageSize+1;
		if(++pageNo>maxPage){
			generate("center",'没有下一页了');
		}else{
			$.post('doLipinPage.php',{'lipin':'lipin','pageNo':pageNo,'pageSize':pageSize,'totalCount':totalCount},function(data){
				var json=eval("("+data+")");
				if(json.success=="ok"){
					fillContentner(json.list);//填充数据
					//改变 pageNo,最下方
					$('#pageNo').val(pageNo);
					$('#pageSize').val(pageSize);
					//改变 显示出
					$('#the_page_no').html(pageNo);
					//$('#the_total_count').html(maxPage);
					
					//改变 pageSize
				}else{
					generate("center","网络错误请重试");
				}
			});
		}
	});
	//上一页
	$('#shangye').click(function(){
		var pageNo=parseInt($('#pageNo').val());
		var pageSize=parseInt($('#pageSize').val());
		var totalCount=parseInt($('#zongshu').val());
		//
		var maxPage=totalCount%pageSize==0?totalCount/pageSize:totalCount/pageSize+1;
		if(--pageNo<1){
			generate("center",'没有上一页了');
		}else{
			$.post('doLipinPage.php',{'lipin':'lipin','pageNo':pageNo,'pageSize':pageSize,'totalCount':totalCount},function(data){
				var json=eval("("+data+")");
				if(json.success=="ok"){
					fillContentner(json.list);//填充数据
					//改变 pageNo,最下方
					$('#pageNo').val(pageNo);
					$('#pageSize').val(pageSize);
					//改变 显示出
					$('#the_page_no').html(pageNo);
					//$('#the_total_count').html(maxPage);
					
					//改变 pageSize
				}else{
					generate("center","网络错误请重试");
				}
			});
		}
	});
	
	//首页
	$('#shouye').click(function(){
		var pageSize=parseInt($('#pageSize').val());
		var totalCount=parseInt($('#zongshu').val());
		
		$.post('doLipinPage.php',{'lipin':'lipin','pageNo':1,'pageSize':pageSize,'totalCount':totalCount},function(data){
			var json=eval("("+data+")");
			if(json.success=="ok"){
				fillContentner(json.list);//填充数据
				//改变 pageNo,最下方
				$('#pageNo').val(1);
				$('#pageSize').val(pageSize);
				//改变 显示出
				$('#the_page_no').html(1);
			}else{
				generate("center","网络错误请重试");
			}
		});
	});
	//尾页
	$('#weiye').click(function(){
		var pageSize=parseInt($('#pageSize').val());
		var totalCount=parseInt($('#zongshu').val());
		var maxPage=totalCount%pageSize==0?totalCount/pageSize:parseInt((totalCount/pageSize+1)+'');
		
		$.post('doLipinPage.php',{'lipin':'lipin','pageNo':maxPage,'pageSize':pageSize,'totalCount':totalCount},function(data){
			var json=eval("("+data+")");
			if(json.success=="ok"){
				fillContentner(json.list);//填充数据
				//改变 pageNo,最下方
				$('#pageNo').val(maxPage);
				$('#pageSize').val(pageSize);
				//改变 显示出
				$('#the_page_no').html(maxPage);
			}else{
				generate("center","网络错误请重试");
			}
		});
	});
	//转到
	
	$('#go').click(function(){
		$('#theCart').css( {
			'position' : 'static',
			'top' : "1px",
			'z-index':"100"
		});
		
		var pageSize=parseInt($('#pageSize').val());
		var totalCount=parseInt($('#zongshu').val());
		var maxPage=totalCount%pageSize==0?totalCount/pageSize:parseInt((totalCount/pageSize+1)+'');
		var gotoPage= parseInt($('#thePageNo').val());
		if(gotoPage>=1 && gotoPage<=maxPage){
			$.post('doLipinPage.php',{'lipin':'lipin','pageNo':gotoPage,'pageSize':pageSize,'totalCount':totalCount},function(data){
				var json=eval("("+data+")");
				if(json.success=="ok"){
					fillContentner(json.list);//填充数据
					//改变 pageNo,最下方
					$('#pageNo').val(gotoPage);
					$('#pageSize').val(pageSize);
					//改变 显示出
					$('#the_page_no').html(gotoPage);
				}else{
					generate("center","网络错误请重试");
				}
			});
		}else{
			generate("center","输入的数字不合法!");
		}
	});
});


function exchangePresent(){
	var isLogin=$('#isLogin').val();
	
	if(isLogin=='0'){
		$('#zhezhao').show();
		$('#modal-login').slideDown();
		return ;
	}
	var jifen=parseInt($("#myjifen").val());
	$('.btn_duihuan').click(function(){
		var pid=parseInt($(this).attr('data-id'));
		var pname=$(this).attr('data-name');
		var pcount=parseInt($(this).attr('data-count')); //数量
		var pscore=parseInt($(this).attr('data-score'));//每个 所用积分
		if(jifen<pscore){
			generate("center",'您的积分不足');
			return ;
		}
		window.location.href="lipinsubmitlist.php?pid=" + pid + "&&pname=" + pname + "&&pscore=" + pscore;
	});	
}




/**
 * 该方法用于给 兑换 按钮 添加点击事件，点击的时候加入购物车
 */


function duihuan(){
	$('.btn_duihuan').unbind('click');
	//先得到容器，
	var myjifen=parseInt($('#myjifen').val());//我的积分
	var theRongQi=$('#lipinchecontener');
	$('.btn_duihuan').click(function(){
		//首先检查是不是登录了
		var isLogin=$('#isLogin').val();
		if(isLogin=='0'){
			$('#zhezhao').show();
			$('#modal-login').slideDown();
			return ;
		}
		
		
		//结束检查
		var id=parseInt($(this).attr('data-id'));
		var name=$(this).attr('data-name');
		var count=parseInt($(this).attr('data-count')); //数量
		var score=parseInt($(this).attr('data-score'));//每个 所用积分
//		var id=$(this).attr('data-id');
		
		//便利 所有的 容器下的元素，如果存在就更新，如果不存在就 添加
		$cunzai=false;
		$('.ys').each(function(index,item){
			var _this=$(item);
			var existId= parseInt(_this.attr('data-id'));
			if(id==existId){//存在
				var $theCountContener=$('#lipin_count_'+id);
				var theCount=parseInt($theCountContener.html());
				theCount++;
				var zong=getZongScore();
				if(zong+score>myjifen){
					generate("center",'您的积分不足');
					theCount--;
				}
				$theCountContener.html(theCount);
				$cunzai=true;
			}
		});
		if(!$cunzai){
			if(score>myjifen){
				generate("center",'您的积分不足');
				return ;
			}
			
			var zong=getZongScore();//获取总积分
			
			if(zong+score>myjifen){
				generate("center",'您的积分不足');
				return ;
			}
			
			var theStr='<div class="dingcanhengxian ys" style="height:18px;width:203px;margin-bottom:2px;" data-id="'+id+'">'+
							'<span class="dingcanbuhengxian" id="the_name_'+id+'">'+name+'</span> '+
							'<span class="co dingcanyoubuxian"><span id="the_score_'+id+'">'+score+'</span> X <span id="lipin_count_'+id+'">1</span> <i class="icon-minus-sign lipin_delete" rel="'+id+'" style="cursor:pointer;"></i></span>'+
						'</div>';
			theRongQi.append(theStr);
			lipinDelete();
		}
		afterClick();
	});
}

function lipinDelete(){
	$('.lipin_delete').unbind('click');
	$('.lipin_delete').click(function(){
		var theId=$(this).attr('rel');
			var $theCount=$('#lipin_count_'+theId);// .html();
			var count=parseInt($theCount.html());
			if(count>1){
				count--;
				$theCount.html(count);
			}else{
				$theCount.parent().parent().remove();
			}
			afterClick();
	});
	
}


/**
 * 当兑换按钮点击之后
 */

function afterClick(){
	var json='{"lipins":[';
	var isNull=true;
	
	var zongScore=0;
	var zongCount=0;
	$('.ys').each(function(index,item){
		isNull=false;
		var _this=$(item);
		var existId= _this.attr('data-id');
		var name=$('#the_name_'+existId).html();
		var existScore= $('#the_score_'+existId).html();
		var existCount= $('#lipin_count_'+existId).html();
		zongCount+=parseInt(existCount);//统计 总件数
		zongScore+=parseInt(existCount)*parseInt(existScore);//统计中积分
		
		if(index==0){
			json+='{"id":'+existId+',"name":"'+name+'","score":'+existScore+',"count":'+existCount+"}";
			
		}else{
			json+=',{"id":'+existId+',"name":"'+name+'","score":'+existScore+',"count":'+existCount+"}";
		}
	});
	
	//显示到
	$('#_count_count_').html(zongCount);
	$('#_score_score_').html(zongScore);
	json+=']}';
	
	//改变去 结算
	 $('#resGiftCarNull').hide();
	 $('#resGiftCarAbleBtn').show();
	 $('#resGiftCar').show();
	
	 if(zongCount==0 || zongScore==0){
		 $('#resGiftCarNull').show();
		 $('#resGiftCarAbleBtn').hide();
		 $('#resGiftCar').hide();
	 }
	 
	 
	
	$.post('lipinsubmitlist.php',{'action':'lipin','json':json},function(){
		
	});
}



/*
 * 获取当前兑换的总积分
 */
function getZongScore(){
	var zong=0;
	$('.ys').each(function(index,item){
		var _this=$(item);
		var existId= parseInt(_this.attr('data-id'));
		var everyScore=parseInt($('#the_score_'+existId).html());//得到 当前 改项的 积分
		var everyCount=parseInt($('#lipin_count_'+existId).html());
		zong+=everyScore*everyCount;
	});
	return zong;
};



function fillContentner(list){
	var $div= $('#list_data');//容器
	var str='';
	//{'id':'11','name':'滑溜牙签','imgPath':'lipinimg/default.jpg','score':'20','lipinCount':'','':'好牙签用滑溜'}
	$.each(list,function(index,item){
		str+='<span class="res_gift_album inline_any tc mb15" style="margin-bottom:0px;margin-top:5px;">'+
		 	'<a href="javascript:void(0);" class="resGiftInfo" title="'+item.description+'"><img '+
			'src="'+item.imgPath+'"'+
			' class="bdc db p10 jsLazyImage" style="width:150px;height:140px;"></a>'+
		' <strong class="ell mt10 mb10 db pct98"><a'+
			' href="javascript:" class="resGiftInfo cdred f14 nodec"  style="color:green;">'+item.name+'</a></strong>'+

		' <span class="mt2 db">积分：<strong class="co fa">'+item.score+'</strong></span>'+

		' <span class="mt10 db abs_in">'+ 
//		'<a class="btn" href="lipinxiangqing.php?id='+item.id+'"><i'+
//				' class="icon-folder-open"></i> 详情</a>'+
		'<a class="btn btn-success btn_duihuan"'+
		' href="javascript:;" style="padding:0px;width:70px;height:20px;background:#2da200;"  data-count="'+item.lipinCount+'" data-score="'+item.score+'" data-name="'+item.name+'" data-id="'+item.id+'" onclick="exchangePresent()">立即兑换</a>'+
	'</span>'+
	'</span> ';
	});
	
	//家上下面的防止格式混乱
	str+='<span class="res_gift_album inline_any" style="height:1px;margin:0px;">&nbsp;</span>'+
	'<span	class="res_gift_album inline_any" style="height:1px;margin:0px;">&nbsp;</span> <span'+
		' class="res_gift_album inline_any" style="height:1px;margin:0px;">&nbsp;</span> <span'+
		' class="res_gift_album inline_any" style="height:1px;margin:0px;">&nbsp;</span> <span'+
		' class="res_gift_album inline_any" style="height:1px;margin:0px;">&nbsp;</span>';
	//添加容器之后啊
	$div.html(str);
	duihuan();
}