var searched=false;
var maxnum=15;
$(document).ready(function(){
    $(".pmt_rule_title").bind('click',ChooseStep);
    $(".page").livequery('click',function(e){
        var curObj = $(this);
	    var PageNo =curObj.attr("href");
	    var tmpLength =curObj.attr("href").lastIndexOf('\/');
	    if(tmpLength >0){//解决a ie6 兼容问题
		    PageNo =curObj.attr("href").substr((curObj.attr("href").lastIndexOf('\/')+1));
	    }else{
		    PageNo =curObj.attr("href");
	    }
	    var ProductName =$("#search_name").val();
	    var ProductIds=$("#check_product_ids").val();
	    var PromotionId =$("#promotion_id").val();
	    var subcat =$("#subcat").val();
	    var bid=$("#brand").val();
	    var productIds =$("#productids").val();
	    GetProductInfo(PageNo,ProductName,ProductIds ,PromotionId ,subcat,productIds,bid);
	    return false;
    });
    $("#search_product").bind('click',function(e){
	    var PageNo=$("#PageNo").val();
	    var ProductName =$("#search_name").val();
	    var ProductIds=$("#check_product_ids").val();
	    var PromotionId=$("#promotion_id").val();
	    var subcat=$("#subcat").val();
	    var bid=$("#brand").val();
	    var productIds =$("#productids").val();
	    GetProductInfo(PageNo,ProductName,ProductIds ,PromotionId ,subcat,productIds,bid);
	    return false;
    });
    $("input[@name='sort']").livequery('keyup',function(){
        $(this).val($(this).val().replace(/\D/g,""));
    });
    $('#btnStep1').click(function(){//第一步保存
        if(CheckStep1()){
            if(!searched){
                var PageNo=1;
				var ProductName ='';
				//var ProductIds ='';
				var ProductIds=$("#check_product_ids").val();
				var PromotionId =$("#promotion_id").val();
				var bid=$("#brand").val();
				var subcat=$("#subcat").val();
				GetProductInfo(PageNo,ProductName,ProductIds ,PromotionId, '','',bid);
            }
            $('.pmt_rule_content').hide();
            $('.pmt_rule_content').eq(1).show();
        }
    });
    $('#btnStep2').click(function(){//第二步保存
        if(CheckStep2()){
            $('.pmt_rule_content').hide();
            $('.pmt_rule_content').eq(2).show();
        }
    });
    $('#btnSave').click(function(){//第三步保存
        try{
		    $("input[@name='sort']").each(function(){
			    var re = /^[1-9]+[0-9]*]*$/;
			    if(!re.test($(this).val())){
				    alert('排序必填且为正整数');
				    throw '排序必填且为正整数';
			    }
		    });
		}
		catch(e){
            return false;
		}
    });
    $("#product_all").livequery('click',function(){
		var product_ids =$.trim($("#check_product_ids").val());
		if($(this).is(":checked")){
			if(product_ids)
				 pids =product_ids.split(',');
			else
				 pids =new Array();
			$("input[name='check_product']").each(function(){
				if(pids.length>6) return false;
				if(!$(this).is(':checked')){
					$(this).attr('checked' ,true);
					update_status($(this));
					CreateNewRow($(this).parent().parent());
				}
				pids.push($(this).val());
			});
		}else if(pids){
			$("input[name='check_product']").each(function(){
				$(this).attr('checked' ,false);
				update_status($(this));
				pids =del(pids ,$(this).val());
				DelRow($(this).parent().parent());
			});
		}
		if(pids.length>maxnum){
            alert('每个橱窗最多只能添加'+maxnum+'个商品');
			return false;
		}
		pids =uniq(pids);
		if(pids.length<=0){
			tmp_num ='0';
		}else{
			tmp_num =pids.length;
		}
		pid_str =pids_join(pids);
		$("#check_product_ids").val(pid_str);
		$("#select_product_num").html(tmp_num);
	});
	$("input[name='check_product']").livequery('click',function(){
		var product_id =$(this).val();
		var product_ids =$.trim($("#check_product_ids").val());
		var rowObj=$(this).parent().parent();
		if(product_ids){
			var pids =product_ids.split(',');
			if($(this).is(":checked")){
				pids.push(product_id);
				pids =uniq(pids);
				if(pids.length>maxnum){
                    alert('每个橱窗最多只能添加'+maxnum+'个商品');
			        return false;
		        }
				var str ='已添加<br><span class="cancel_product hand" id="cancel_product_'+product_id+'" value="'+product_id+'">取消</span>';
				$("#add_product_"+product_id).parent().html(str);
				//创建价格设置行
				CreateNewRow(rowObj);
			}else{
				pids =del(pids ,product_id);
				var str ='<span class="add_product hand" id="add_product_'+product_id+'" value="'+product_id+'" >加入厨窗</span>';
				$("#cancel_product_"+product_id).parent().html(str);
				DelRow(rowObj);
			}
			var pid_str =pids_join(pids);
			$("#check_product_ids").val(pid_str);
			if(pids.length<=0){
				tmp_num ='0';
			}else{
				tmp_num =pids.length;
			}
			$("#select_product_num").html(tmp_num);
		}else if($(this).is(":checked")){
			var str ='已添加<br><span" class="cancel_product hand" id="cancel_product_'+product_id+'" value="'+product_id+'">取消</span>';
			$("#add_product_"+product_id).parent().html(str);
			$("#check_product_ids").val(product_id);
			$("#select_product_num").html(1);
			CreateNewRow(rowObj);
		}
	});
	$(".cancel_product").livequery('click',function(){
		var product_id =$(this).attr('value');
		var rowObj=$(this).parent().parent();
		if($("#check_product_"+product_id).is(":checked")){
			$("#check_product_"+product_id).attr('checked' ,false);
			var pids =$("#check_product_ids").val().split(',');
			pids =del(pids,product_id);
			pids_str =pids_join(pids);
			$("#check_product_ids").val(pids_str);
			var str ='<span class="add_product hand"  id="add_product_'+product_id+'" value="'+product_id+'">加入厨窗</span>';
			$(this).parent().html(str);
			if(pids.length<=0){
				tmp_num ='0';
			}else{
				tmp_num =pids.length;
			}
			$("#select_product_num").html(tmp_num);
			DelRow(rowObj);
		}
	});
	$(".add_product").livequery('click',function(){
		var product_id =$(this).attr('value');
		var rowObj=$(this).parent().parent();
		$("#check_product_"+product_id).attr('checked' ,true);
		if($("#check_product_ids").val()){
			pids =$("#check_product_ids").val().split(',');
		}else{
			pids =new Array();
		}
		pids.push(product_id);
		pids =uniq(pids);
		pids_str =$.trim(pids_join(pids),',');
		$("#check_product_ids").val(pids_str);
		var str ='已添加<br><span class="cancel_product hand" id="cancel_product_'+product_id+'" value="'+product_id+'">取消</span>';
		$(this).parent().html(str);
		$("#select_product_num").html(pids.length);
		CreateNewRow(rowObj);
	});
	$(".step3_cancle_product").livequery('click',function(){
		var product_id =$(this).attr('value');
		var pids =$("#check_product_ids").val().split(',');
		pids =del(pids,product_id);
		pids_str =pids_join(pids);
		$("#check_product_ids").val(pids_str);
		$("#check_product_"+product_id).attr('checked' ,false);
		$(this).parent().parent().remove();
	});
});
function ChooseStep(){
    var stepid=$(this).attr('id');
    var flag=new Boolean();
    flag=true;
    if(stepid=='step2'){
        flag=CheckStep1();
        if(flag && !searched){
            var PageNo=1;
			var ProductName ='';
			//var ProductIds ='';
			var ProductIds=$("#check_product_ids").val();
			var PromotionId =$("#promotion_id").val();
			var bid=$("#brand").val();
            var subcat=$("#subcat").val();
			GetProductInfo(PageNo,ProductName,ProductIds ,PromotionId, '','',bid);
        }
    }else if(stepid=='step3'){
        flag=CheckStep1();
        if(flag){
            flag=CheckStep2();
            if(!flag){
                $('.pmt_rule_content').hide();
                $('.pmt_rule_content').eq(1).show();
            }
        }
    }
    if(flag){
        $('.pmt_rule_content').hide();
        $(this).next('.pmt_rule_content').show();
    }
}

function GetProductInfo(a){
	PageNo =arguments[0];
	ProductName =arguments[1];
	CheckkedPids =$.trim(arguments[2]);
	if(CheckkedPids=='undefined') CheckkedPids ='';
	PromotionId =arguments[3];
	SubCat =arguments[4];
	var bid=arguments[6];
	if(typeof subcat=='undefined') subcat ='';
	var SearchPids =arguments[5];
	var PromotionType =$("#promotion_type").val();
	//var ruleBeginTime=$("#txtTimeBegin").val()+" "+$("#startHour").val()+ ":00:00";
	//var ruleEndTime=$("#txtTimeEnd").val()+" "+$("#endHour").val()+ ":00:00";
	URL ='get_product_for_pmtrule.ashx',
	Param ={pageno:PageNo,keyword:ProductName ,checkedpids:CheckkedPids,promotion_id:PromotionId,promotion_type:PromotionType,searchpids:SearchPids ,cid:SubCat,bid:bid,pbt:'',pet:''},
	$.post(URL ,Param ,function(data){
		$("#productlist").html(data);
	})
	searched=true;
	return true;
}


function getParamsInfo(PmtType){
	tmp =new Array();
	switch(PmtType){
		case '6':
			var id_str ='';
			for(var i=1;i<=3;i++){
				tmp[i] ='';
				$("input[name='product_param"+i+"[]']").each(function(){
					if(i==1){
						ids =$(this).attr('id').split('_');
						id_str +=ids[2]+'_';
					}
					tmp[i] +=$(this).val().replace('_' ,'')+'_';
				});
			}
			tmp[0] =id_str;
			tmp[4] ='';
			$("input[name='sort_card[]']").each(function(){
				tmp[4] +=$(this).val().replace('_' ,'')+'_';
			});
			break;
		case '5':
			var id_str ='';
			tmp[1] ='';
			$("input[name='product_param1[]']").each(function(){
				ids =$(this).attr('id').split('_');
				id_str +=ids[2]+'_';
				tmp[1] +=$(this).val().replace('_' ,'')+'_';
			});
			tmp[0] =id_str;
			tmp[2] ='';
			$("input[name='sort_card[]']").each(function(){
				tmp[2] +=$(this).val().replace('_' ,'')+'_';
			});
			break;
		case '51':
			var id_str ='';
			tmp[1] ='';
			$("input[name='product_param1[]']").each(function(){
				ids =$(this).attr('id').split('_');
				id_str +=ids[2]+'_';
				tmp[1] +=$(this).val().replace('_' ,'')+'_';
			});
			tmp[0] =id_str;
			break;
		case '3':
			var id_str ='';
			tmp[1] ='';
			$("select[name='product_param1[]']").each(function(){
				ids =$(this).attr('id').split('_');
				id_str +=ids[2]+'_';
				tmp[1] +=$(this).val().replace('_' ,'')+'_';
			});
			tmp[0] =id_str;
			tmp[2] ='';
			$("input[name='sort_card[]']").each(function(){
				tmp[2] +=$(this).val().replace('_' ,'')+'_';
			});
			break;
		case '1':
			var id_str ='';
			var dataInfo =new Array(1,2);
			var v =1;
			$.each(dataInfo ,function(key ,i){
				tmp[v] ='';
				$("input[name='product_param"+i+"[]']").each(function(){
					if(i==1){
						ids =$(this).attr('id').split('_');
						id_str +=ids[2]+'_';
					}
					tmp[v] +=$(this).val().replace('_' ,'')+'_';
				});
				v++;
				tmp[v] ='';
				$("input[name='product_param_discount"+i+"[]']").each(function(){
					tmp[v] +=$(this).val().replace('_' ,'')+'_';
				});
				v++;
			});
			tmp[0] =id_str;
			tmp[5] ='';
			$("input[name='sort_card[]']").each(function(){
				tmp[5] +=$(this).val().replace('_' ,'')+'_';
			});
			break;
		case '101':
			var id_str ='';
			tmp[1] ='';
			$("input[name='product_param1[]']").each(function(){
				ids =$(this).attr('id').split('_');
				id_str +=ids[2]+'_';
				tmp[1] +=$(this).val().replace('_' ,'')+'_';
			});
			tmp[0] =id_str;
			tmp[2] ='';
			$("input[name='sort_card[]']").each(function(){
				tmp[2] +=$(this).val().replace('_' ,'')+'_';
			});
			break;
		case '102':
			var id_str ='';
			for(var i=1;i<=2;i++){
				tmp[i] ='';
				$("input[name='product_param"+i+"[]']").each(function(){
					if(i==1){
						ids =$(this).attr('id').split('_');
						id_str +=ids[2]+'_';
					}
					tmp[i] +=$(this).val().replace('_' ,'')+'_';
				});
			}
			tmp[0] =id_str;
			tmp[3] ='';
			$("input[name='sort_card[]']").each(function(){
				tmp[3] +=$(this).val().replace('_' ,'')+'_';
			});
			break;
	}
	return tmp;
}
function CreateNewRow(obj){
    var pid=obj.attr("id").split('_')[1];
    if($('#newrow_'+pid).length==0){
        var img=obj.children(".pimg").html();
        var pname=obj.children(".pname").html();
        var pprice=obj.children(".pprice").html();
        var rowObj='<tr id="newrow_'+pid+'"><td>'+img+'</td><td>'+pname+'</td><td><input type="text" size="5" name="sort" value=""><input type="hidden" value="'+pid+'" name="pids"></td><td><span value="'+pid+'" class="step3_cancle_product hand">取消</span></td>';
        $('#step3_body').append(rowObj);
    }
}
function DelRow(obj){
    var pid=obj.attr("id").split('_')[1];
    if($('#newrow_'+pid).length>0){
        $("#newrow_"+pid).remove();
    }
}

function CheckStep1()
{
    var floorName =$.trim($("#txtFloorName").val());
	var str ='';
	if(!floorName || StrLength(floorName)>100){
		str +='楼层名称必填且小于50个汉字（100个字符）\n';
    }
    var re = /^[1-9]+[0-9]*]*$/;
    if(!re.test($.trim($("#txtSort").val()))){
        str +='排序必填且为正整数\n'
    }
	if(str){
		alert(str);
		return false;
	}
	return true;
}

function CheckStep2()
{
    var PdtIDs =$.trim($("#check_product_ids").val());
	if(PdtIDs =='undefined' || PdtIDs == ''){
        alert("请选择厨窗商品");
        return false;
    }    
    return true;
	var PromotionId =$("#promotion_id").val();
	var PromotionType =$.trim($("#promotion_type").val());
	var PmtApi =new Array();
	PmtApi[6] ='api/get_product_info_select_for_promo_vip_member_v2.php';
	PmtApi[5] ='api/get_product_info_select_for_limit_buy_v2.php';
	PmtApi[51] ='api/get_product_info_select_for_n_buy_v2.php';
	PmtApi[3] ='api/get_product_info_select_for_promo_gift_v2.php';
	PmtApi[1] ='api/get_product_info_select_for_multi_quantity_v2.php';
	PmtApi[101] ='api/get_product_info_select_for_direct_discount_v2.php';
	PmtApi[102] ='api/get_product_info_select_for_limit_time_v2.php';
	URL =PmtApi[PromotionType];
	if(!URL) return false;
	var param =getParamsInfo(PromotionType);
	if(PdtIDs){
		var pids =PdtIDs.split(',');
		pids =pids_join(pids);
		Param ={ pmtid:PromotionId,pids:pids ,param0:param[0],param1:param[1],param2:param[2],param3:param[3] ,param4:param[4],param5:param[5]},
		$.post(URL ,Param ,function(data){
			$("#step_3").html(data);
		});
	}else{
		if(PromotionId==0){
			return false;
		}else{
			var steps_2 =$.trim($("#steps_2").html());
			var noSelectProduct =$.trim($("#no_select_product").val());
			if(steps_2 && !$.trim($("#check_product_ids").val())){
				if(noSelectProduct==1){
					return true;
				}else{
					return false;
				}
			}
			pids ='';
			Param ={promotion_id:PromotionId,productids:pids ,param0:param[0],param1:param[1],param2:param[2],param3:param[3] ,param4:param[4],param5:param[5]},
			$.post(URL ,Param ,function(did){
				$("#steps_3").html(did);
			});
		}
	}
	return true;
}

function update_status(obj){
	var product_id =obj.val();
	var product_ids =$.trim($("#check_product_ids").val());
	if(product_ids){
		var pids =product_ids.split(',');
		if(obj.is(":checked")){
			pids.push(product_id);
			pids =uniq(pids);
			if(pids.length>maxnum){
                alert('每个橱窗最多只能添加'+maxnum+'个商品');
			    return false;
		    }
			var str ='已添加<br><span class="cancel_product hand" id="cancel_product_'+product_id+'" value="'+product_id+'">取消</span>';
			$("#add_product_"+product_id).parent().html(str);
		}else{
			pids =del(pids ,product_id);
			var str ='<span class="add_product hand" id="add_product_'+product_id+'" value="'+product_id+'">加入厨窗</span>';
			$("#cancel_product_"+product_id).parent().html(str);
		}
		var pid_str =pids_join(pids);
		if(pids.length<=0){
			tmp_num ='0';
		}else{
			tmp_num =pids.length;
		}
		$("#check_product_ids").val(pid_str);
		$("#select_product_num").html(tmp_num);
		document.getElementById('select_product_num').innerHTML =tmp_num;
	}else if(obj.is(":checked")){
		var str ='已添加<br><span class="cancel_product hand" id="cancel_product_'+product_id+'" value="'+product_id+'">取消</span>';
		$("#add_product_"+product_id).parent().html(str);
		$("#check_product_ids").val(product_id);
		$("#select_product_num").html("1");
	}
	return true;
}

function pids_join(pids){
	var str ='';
	if(pids &&  pids.length>0){
		var tmp =new Array();
		for(var i=0;i<pids.length;i++){
			var id =$.trim(pids[i]);
			if( id && id!=',') tmp[i] =id;
		}
		if(tmp) str =tmp.join(',');
	}
	return str;
}

function del(pids,product_id){
	var tmp =new Array();
	var j =0;
	for(var i=0;i<pids.length;i++){
		if(pids[i] ==product_id){
			continue;
		}else{
			tmp[j] =pids[i];
			j++;
		}
	}
	return tmp;
}

function uniq(array) {  
    var map={};  
    var re=[];  
    for(var i=0,l=array.length;i<l;i++) {
	if(array[i]=='undefined') continue;
        if(typeof map[array[i]] == "undefined"){  
            map[array[i]]=1;  
            re.push(array[i]);  
        }  
    }  
    return re;  
}
function StrLength(str){
  var  len=0;
  for(var i=0;i<str.length;i++){
    if(str.charCodeAt(i)>255){
      len +=2;
    }else{
      len +=1;
    }
  }
  return len;
}