var cardAllArray = [];
var isFixed = false;
var isBatch = false;
var BatchArrayError = [];

var regEight = /^[0-9\s]{8}$/;
var regNine = /^[0-9\s]{9}$/;
var regTen = /^[0-9\s]{10}$/;
var regTwelve = /^[0-9\s]{12}$/;
var regThirteen = /^[0-9\s]{13}$/;
var regFifteen = /^[0-9]{15}$/;
var regSixteen = /^[0-9]{16}$/;
var regSeventeen = /^[0-9]{17}$/;
var regEighteen = /^[0-9]{18}$/;
var regNineteen = /^[0-9]{19}$/;
var regTwenty = /^[0-9\s]{20}$/;

$(function(){
	/**
     * @description: 回收页面，卡类项宽度计算
     */
    calcRecycleClassifyWidth();
    
    /**
     * @description: 移动改变背景图
     */
    $(".card-recovery-bg").hover(function() {
        var t= $(this).parents();
        if(!t.hasClass('active')){
            $(this).addClass("hover");
        }
    }, function() {
        $(this).removeClass("hover");
    });

    /**
     * @description: 鼠标移动选择卡种效果
     */
    $(document).on('mouseover', ".recovery-mode-list", function(){
        if(!$(this).hasClass('active')){
            $(this).css('border','2px solid #86a3c5');
        }
    });
    $(document).on('mouseout', ".recovery-mode-list", function(){
        /*if(!$(this).hasClass('active')){
            $(this).css('border','2px solid #bfcbd9');
        }*/
        $(this).css('border','2px solid #bfcbd9');
    });

    /**
     * @description: 鼠标移动选择面值效果
     */
    $(document).on('mouseover', ".recovery-par-list", function(){
        if(!$(this).hasClass('active')){
            $(this).css('border','2px solid #86a3c5');
        }
    });
    $(document).on('mouseout', ".recovery-par-list", function(){
        if(!$(this).hasClass('active')){
            $(this).css('border','2px solid #bfcbd9');
        }
    });


    /**
     * @description: 鼠标移动批量输入框效果
     */
    $("#batchCardlist:not('.active')").hover(function() {
        if(!$(this).hasClass('active')){
            $(this).css('border','2px solid #86a3c5');
        }
    }, function() {

        if(!$(this).hasClass('active')){
            $(this).css('border','2px solid #bfcbd9');
        }
    });

    /**
     * @description: 点击切换
     */
    $(".cardrecovery-show-list ul li:not(.site-nav-pipe)").click(function(event) {
        $(this).addClass('active').siblings().removeClass('active');
        var num = ($(this).index()+2)/2;
        $(".cardrecovery-show-box .cardrecovery-show-comm").eq(num-1).addClass('active').siblings().removeClass('active');
    });
    /**
     * @description: 移动div出现边框
     */
    $(".cardrecovery-show-comm .card-comm-list").hover(function() {
        $(this).addClass('switch-box-hover');
    }, function() {
        $(this).removeClass('switch-box-hover');
    });
    /**
	* @description: 线上回收交易流程点击显示内容
	*/
	$(".main.trade-flow-main .recycle-main li:not('.notice-list-spot')").click(function(event) {
		var oListNum = ($(this).index()+2)/2;
		$('.recycle-explain-list').eq(oListNum-1).addClass('active').siblings().removeClass('active');
	});

	/**
	* @description: 卡的类型切换
	*/
	$(".card-recovery-list").click(function(event) {
		$(this).addClass('active').siblings().removeClass('active');
		$(".recovery-card-major").eq($(this).index()).addClass('active').siblings().removeClass('active');
		$("#productClassifyId").val($(this).attr("id"));
		getRecycleOperatorsByProductClassifyId($(this).attr("id"));
	});
	
	/**
	* @description: 选择卡种
	*/
	$(".recovery-card-mode").on("click", ".data-type-operator", function(){
		var s_maintain = $(this).attr("maintenancestate"); // 维护状态[0：正常   1：正在维护]	如果为空，那就默认是正常的;只有为1的时候，才是正在维护中
        var opeMainResult = isOperatorMaintain(s_maintain);
        // alert(s_maintain + ';;;'+typeof s_maintain+ ';;;'+ opeMainResult);
        if (opeMainResult) {
            $(this).addClass('maintain').siblings().removeClass('maintain');
            setSubmitBtnBg(false);
        } else {
            $(this).removeClass('maintain').siblings().removeClass('maintain');
            setSubmitBtnBg(true);
        }

		$(this).addClass('active').siblings().removeClass('active');
		$("input[name='cardtype']").val($(this).attr("product-code"));
		$("#operatorId").val($(this).attr("id"));
		getCardRulesByOperatorId($("#operatorId").val());
		getRecyclePricesByOperatorId($(this).attr("id"));
        tidyBathCardsFn();
        //onlyCardPassFn( $.trim($("#type").val()) );

	});

	/**
	* @description: 选择面值
	*/
	$("#priceWrap").on("click", ".recovery-par-list", function(event) {
        if($(this).hasClass('price_maintain')){
            layer.msg('当前面值正在维护，无法提交', {icon : 2,shade : [ 0.4, '#000' ],time : 2500});
            // setSubmitBtnBg(false);
		}else{
            // setSubmitBtnBg(true);

            $(this).addClass('active').siblings().removeClass('active');
            $("input[name='cardprice']").val($(this).attr("val"));
            $("#price").val($(this).attr("val"));
            $("#priceTip").html($("#price").val());
            if($(this).attr("type") == "2")
            {
                getRateRangeInfo($("#operatorId").val(), $("#price").val());
            }

            getRecentConsumeDuration($("#operatorId").val(), $("#price").val());
		}

	});	
	
	/**
	* @description: 提交方式
	*/
	$(".recovery-card-mode.recovery-card-submit .recovery-mode-list").click(function(event) {
		$(this).addClass('active').siblings().removeClass('active');
		$(".submit-mode-cont").eq($(this).index()).addClass('active').siblings().removeClass('active');
		
		if($(this).index() == 0){
			$("#type").val("2");
            onlyCardPassFn(2);
		}else{
			$("#type").val("1");
            onlyCardPassFn(1);
		}

	});	

	/**
	* @description: 点击批量提交
	*/
	//$("#batchCardlist").val('0111001702060546320,100304016583597830,0222001702060546320,100304016583597830,0999001702060546320,100304016583597830,0888001702060546320,100304016583597830');
	//$("#batchCardlist").val('12345678912345678,123456789123456789');

	$("#cardBatchBtn").click(function (){
		//var neaten = $("#batchCardlist").val().split('\n');
		if($(this).hasClass('no-allowed')){
			return false;
		}else{
            tidyBathCardsFn();

            var checkPhoneCardPriceResult = checkPhoneCardPrice();
            if(checkPhoneCardPriceResult){
                var neaten = $("#batchCardlist").val();
                if(neaten === ''){
                    var isOnlyCardPassResult = isOnlyCardPass();
                    if(isOnlyCardPassResult){
                        layer.msg('请输入要提交的卡密', {icon: 2,shade: [0.4, '#000'],time : 2000});
                    }else{
                        layer.msg('请输入要提交的卡号、卡密', {icon: 2,shade: [0.4, '#000'],time : 2000});
                    }
                }else{
                	// 判断规则是否明确
                	var cardNumLenHidVal = $.trim($("#cardNumRule").val());
                    var cardPassLenHidVal = $.trim($("#cardPassRule").val());
                    
                    if(cardNumLenHidVal != '-1' && cardPassLenHidVal != '-1'){
                    	cardCommFn(neaten);
                    }else{
                    	// 规则不明确，根据用户输入的提交
                    	noRuleFn(neaten);
                    }
                }
            }
		}

	});
	
	$("input[name='cardtype']").val('MOBILE');
	$('#batchCardlist').click(function(event) {
		$(this).addClass('active');
        $(this).css('border','2px solid #27baff');
	});
	$('#batchCardlist').blur(function(event) {
		$(this).removeClass('active');
        $(this).css('border','2px solid #bfcbd9');
	});
	
	
	$("i.icon-agree-up").click(function(event) {
		if($(this).hasClass('icon-agree-off')){
			$(this).removeClass('icon-agree-off');
			
			if($("#type").val() == "1")
			{
				$("#isAgree1").val("0");
				$("#cardOneBtn").attr("style", "background:gray");
			}
			else if($("#type").val() == "2")
			{
				$("#isAgree2").val("0");
				$("#cardBatchBtn").attr("style", "background:gray");
			}
		}
		else
		{
			$(this).addClass('icon-agree-off');
			if($("#type").val() == "1")
			{
				$("#isAgree1").val("1");
				$("#cardOneBtn").removeAttr("style");
			}
			else if($("#type").val() == "2")
			{
				$("#isAgree2").val("1");
				$("#cardBatchBtn").removeAttr("style");
			}
		}
		
		//alert("isAgree1:" + $("#isAgree1").val());
		//alert("isAgree2:" + $("#isAgree2").val());
	});
	//$("#cardNum").val('12345678912345678');
	//$("#cardPass").val('123456789123456789');
	/**
	* @description: 单卡提交
	*/
	$("#cardOneBtn").click(function(event) {
        if($(this).hasClass('no-allowed')){
            return false;
        }else{
            var checkPhoneCardPriceResult = checkPhoneCardPrice();
            if(checkPhoneCardPriceResult){
                var oCardNumVal = $.trim($("#cardNum").val());
                var oCardPassVal = $.trim($("#cardPass").val());
                //var cardtype =$("input[name='cardtype']").val();

                var cardtype = "";
                $(".data-type-operator").each(function(){
                    if($(this).attr("id") == $("#operatorId").val())
                    {
                        cardtype = $(this).attr("product-code");
                        return false;
                    }
                });

                var oCard  = '00001';
                var isOnlyCardPassResult = isOnlyCardPass();
                if(isOnlyCardPassResult){
                    if(oCardPassVal === ''){
                        layer.msg('请输入卡密！', {icon: 2,shade: [0.4, '#000'],time : 2000});
                    }else{
                        cardType(oCardNumVal,oCardPassVal,oCard,cardtype);
                    }
                }else{
                    if(oCardNumVal === ''){
                        layer.msg('请输入卡号！', {icon: 2,shade: [0.4, '#000'],time : 2000});
                        return false;
                    }else if(oCardPassVal === ''){
                        layer.msg('请输入卡密！', {icon: 2,shade: [0.4, '#000'],time : 2000});
                        return false;
                    }else{
                        cardType(oCardNumVal,oCardPassVal,oCard,cardtype);
                    }
                }

                if(isFixed){
                    cardAallFn();
                }else{
                    cardBatchError(oCard)
                }
            }
		}

	});

    /**
     * @description: 单卡回收业务专题-卡类宽度计算
     */
    calcSingleRecyleClassifyWidth();

});

function calcRecycleClassifyWidth(){
	var parentBox = $(".recovery-card-type");
	if(parentBox.length > 0){
		var itemobj = parentBox.find(".card-recovery-list");
		var itemlen = itemobj.length;
		var spaceTotal = (itemlen-1)*50;
		var itemWidth = (1232-spaceTotal)/itemlen;
		itemobj.find('.card-recovery-bg').css('width', itemWidth+'px');
		itemobj.eq(itemlen-1).css('margin-right', '0');
	}
}

/**
 * @description: 单卡回收业务专题-卡类宽度计算
 */
function calcSingleRecyleClassifyWidth(){
	var parentBox = $("#singleCard-recyle-topic");
	if(parentBox.length > 0){
		var liobj = parentBox.find(".cardrecovery-show-list li").not('.site-nav-pipe');
		var lilen = liobj.length;
		var liWidth = (1320-(lilen-1))/lilen;
        liobj.css('width', liWidth+'px');
	}
}


/**
* @description: 批量提交去掉空格，跟逗号，生成卡号跟卡密
*/
 function cardCommFn(cardList){
 	var cardtype = "";
    $(".data-type-operator").each(function(){
        if($(this).attr("id") == $("#operatorId").val()){
            cardtype = $(this).attr("product-code");
            return false;
        }
    });

    var cardsData = $.trim(cardList.replace(/\n/g, ';').replace(/\s{3}/g, ',')); //卡号卡密  \s：匹配任何空白字符，包括空格、制表符、换页符等等   \n：匹配一个换行符
    var batchData = []; //存卡密数组
    batchData = cardsData.split(";");

    var isOnlyCardPassResult = isOnlyCardPass();
    if(isOnlyCardPassResult){
        batchData = batchData.map(function (item) {
            return [item];
        }, this);

        //遍历 校验卡密
        var bathHide = [];
        for (var j = 0; j < batchData.length; j++) {
            if (batchData[j] != "") {
                cardType("", batchData[j][0], j+1, cardtype);
                bathHide.push(batchData[j]);
            }
        }
    }else{
        batchData = batchData.map(function (item) {
            var item0 = item.split(",")[0];
            var item1 = item.split(",")[1];
            return [item0, item1];
        }, this);

        //遍历 校验卡号、卡密
		var bathHide = [];
        for (var j = 0; j < batchData.length; j++) {
            if (batchData[j][0] != "") {
                cardType(batchData[j][0], batchData[j][1], j+1, cardtype);
                bathHide.push(batchData[j][0]);
                bathHide.push(batchData[j][1]);
            }
        }
    }

    if(BatchArrayError == ""){
        isBatch = true;
        $("input[name='cards']").val(bathHide);
        cardAallFn('batch');
    }else{
        isBatch = false;
        $("input[name='cards']").val("");
        cardBatchError(BatchArrayError);
    }

 }

/**
* @description: 判断现在的卡的类型
*/
function cardType(name,pass,cardnum,cardtype){
	//alert("name=" + name + ",pass=" + pass + ",cardnum=" + cardnum + ",cardtype=" + cardtype);
	/**
	* @description: 卡类型相对应的值 电信卡快销：TELECOM，电信卡慢销：TELECOM_SLOW , 移动卡快销：MOBILE，移动卡慢销：MOBILE_SLOW，电信卡快销：TELECOM ， 电信卡慢销：TELECOM_SLOW
		盛大：SD，Q币：QB，完美：WM，天宏：TH，网易：WY，征途：ZT，久游：JY，搜狐：SH，纵游： ZY，石油：HOIL，石油快销：HOIL_SLOW，骏网：JW，盛付通：SFT
	*/
	if(cardtype === 'MOBILE' || cardtype === 'MOBILE_SLOW'){
		//移动卡
		cardMove(name,pass,cardnum);
	}else if(cardtype === 'MOBILE_DISCOUNT'){
		var checkResult =  discountCheck();
		if(checkResult){		
			cardMove(name,pass,cardnum);
		}
	}else if(cardtype === 'ZJYDSK'){
    	if(name.length === 17){
    		isFixed = true;
    		if(pass.length === 18){
    	        isFixed = true;
    	        if(name.substr(5,2) === '11'){
    	        	isFixed = true;
    	        }else{
    	        	isFixed = false;
        	        BatchArrayError.push(cardnum);
    	        }
    	    }else{
    	        isFixed = false;
    	        BatchArrayError.push(cardnum);
    	    }
    	}else{
    		isFixed = false;
            BatchArrayError.push(cardnum);
    	}
    }else if(cardtype === 'UNICOM' || cardtype === 'UNICOM_SLOW'){
		//联通卡
		cardUnicom(name,pass,cardnum);
	}else if(cardtype === 'UNICOM_DISCOUNT'){
		var checkResult =  discountCheck();
		if(checkResult){
			cardUnicom(name,pass,cardnum);
		}
	}else if(cardtype === 'TELECOM' || cardtype === 'TELECOM_SLOW'){
		//电信卡
		cardTelecom(name,pass,cardnum);
	}else if(cardtype === 'TELECOM_DISCOUNT'){
		var checkResult =  discountCheck();
		if(checkResult){
			cardTelecom(name,pass,cardnum);
		}
	}else if(cardtype === 'SD'){
		//盛大一卡通
		cardSD(name,pass,cardnum);
	}else if(cardtype === 'QB'){
		//Q币一卡通
		cardQB(name,pass,cardnum);
	}else if(cardtype === 'WM'){
		//完美一卡通
		cardWM(name,pass,cardnum);
	}else if(cardtype === 'TH'){
		//天宏一卡通
		cardTH(name,pass,cardnum);
	}else if(cardtype === 'WY'){
		//网易一卡通
		cardWY(name,pass,cardnum);
	}else if(cardtype === 'ZT'){
		//征途一卡通
		cardZT(name,pass,cardnum);
	}else if(cardtype === 'JY'){
		//久游一卡通
		cardJY(name,pass,cardnum);
	}else if(cardtype === 'SH'){
		//搜狐一卡通
		cardSH(name,pass,cardnum);
	}else if(cardtype === 'ZY'){
		//纵游一卡通
		cardZY(name,pass,cardnum);
	}else if(cardtype === 'HOIL_SLOW'){
		//验证石油卡折扣
		var hoilCheck =  discountCheck();
		if(hoilCheck){
			//石油卡
			cardHoil(name,pass,cardnum);
		}
		
	}else if(cardtype === 'HOIL'){

		//石油卡快销
		cardHoil(name,pass,cardnum);
	}else if(cardtype === 'ZSY'){
        //中石油
        cardZSY(name,pass,cardnum);
    }else if(cardtype === 'JW'){
		//骏网一卡通
		cardJW(name,pass,cardnum);
	}else if(cardtype === 'SFT'){
		//盛付通一卡通
		cardSFT(name,pass,cardnum);
	}else if(cardtype === 'JW_ALL'){
		//骏网全业务卡
		cardJWAll(name,pass,cardnum);
	}else if(cardtype === 'ZYK'){
        //自游卡
        cardZYK(name,pass,cardnum);
    }else if(cardtype === 'JS'){
        //金山一卡通
        cardJS(name,pass,cardnum);
    }else if(cardtype === 'APPLE'){
        //苹果卡
        cardAPPLE(name,pass,cardnum);
    }else{
		// layer.msg('卡号、卡密不符合规则，请检查后重试', {icon: 2,shade: [0.4, '#000'],time : 2000});    	
    	var submitWay = $("#type").val();
        if(submitWay=="1"){//单卡提交
        	// 判断规则是否明确
        	var cardNumLenHidVal = $.trim($("#cardNumRule").val());
            var cardPassLenHidVal = $.trim($("#cardPassRule").val());
            
            if(cardNumLenHidVal != '-1' && cardPassLenHidVal != '-1'){
            	_singleCardFn(cardtype, name, pass, cardnum);
            }else{
            	// 规则不明确，根据用户输入的提交
            	checkMaxLength(name, pass, cardnum);
            	//isFixed = true;                   	
            }         
        }else if(submitWay=="2"){//批量提交
        	_cardCom(name,pass,cardnum);
        }
	}
}

/**
* @description: 无明确规则的批量卡号卡密处理
*/
function noRuleFn(cardList){	  
	var productCode = $("#operatorsWrap .data-type-operator.active").attr("product-code");
	if(productCode === "JD_E"){ // 提交到后台不能带横杠
		var cardsData = $.trim(cardList.replace(/\n/g, ';').replace(/-/g, '')); //卡号卡密  \s：匹配任何空白字符，包括空格、制表符、换页符等等   \n：匹配一个换行符
    }else{
    	var cardsData = $.trim(cardList.replace(/\n/g, ';')); //卡号卡密  \s：匹配任何空白字符，包括空格、制表符、换页符等等   \n：匹配一个换行符
    }
	
    var batchData = []; //存卡密数组
    batchData = cardsData.split(";"); // 筛选出每一行
    var noNullBatch = [];  
    for (var i = 0; i < batchData.length; i++) {
        if (batchData[i] != "") {
        	noNullBatch.push(batchData[i]);
        }
    }
    // 计算输入了几张卡
    var _length = noNullBatch.length;
    $('.card-operation-txt .txt-red').html(_length);
    
    //var cardNumLenHidVal = $.trim($("#cardNumRule").val());
    var _count = 0;
    var isOnlyCardPassResult = isOnlyCardPass();
    if(isOnlyCardPassResult){
    	noNullBatch = noNullBatch.map(function (item) {
        	item = item.replace(/\s/g,",").replace(/[\，]/g,',');   	        	
        	var item1 = '';
        	if(item.indexOf(",") != -1 ){
        		if(item.split(",")[0].length > 0){
        			_count++;
        		}else{
        			item1 = item.split(",")[1];
        		}
        	}else{        		
                item1 = item;
        	}
            return [item1];
        }, this);
    	
    	var bathHide = [];
        for (var j = 0; j < noNullBatch.length; j++) {    	
        	if (noNullBatch[j] != "") { 
        		checkMaxLength("", noNullBatch[j][0], j+1);
                bathHide.push(noNullBatch[j]);
            }        	
        }
    }else{
    	noNullBatch = noNullBatch.map(function (item) {
        	item = item.replace(/\s/g,",").replace(/[\，]/g,',');   	
        	var item0 = '';
        	var item1 = '';
        	if(item.indexOf(",") != -1 ){
        		item0 = item.split(",")[0];
                item1 = item.split(",")[1];
        	}else{
        		item0 = '';
                item1 = item;
        	}
            return [item0, item1];
        }, this);
    	
    	var bathHide = [];
        for (var j = 0; j < noNullBatch.length; j++) {
        	checkMaxLength(noNullBatch[j][0], noNullBatch[j][1], j+1); 	
        	bathHide.push(noNullBatch[j][0]);
            bathHide.push(noNullBatch[j][1]);
        }
    }

    if(_count>0){
    	layer.msg('该卡不需要填写卡号，请检查后再提交', {icon: 2,shade: [0.4, '#000'],time : 2000});
    }else{
    	//isFixed = true;
    	if(BatchArrayError == ""){
            isBatch = true;
            $("input[name='cards']").val(bathHide);
            cardAallFn('batch');
        }else{
            isBatch = false;
            $("input[name='cards']").val("");
            cardBatchError(BatchArrayError);
        }
    }	
}

/**
* @description: 验证卡号、卡密的最大长度
* 卡号、卡密长度分别不能大于30
*/
function checkMaxLength(name, pass, conduct){
	var productCode = $("#operatorsWrap .data-type-operator.active").attr("product-code");
	if(productCode === "JD_E"){ // 提交到后台不能带横杠
		name = name.replace(/-/g, '');
		pass = pass.replace(/-/g, '');
    }
	
	var maxLen = 30;
	var cardNumLenHidVal = $.trim($("#cardNumRule").val());
    var cardPassLenHidVal = $.trim($("#cardPassRule").val());
	if(parseInt(name.length) > maxLen){
		isFixed = false;
        BatchArrayError.push(conduct);
	}else{
		if(cardNumLenHidVal != '-1'){ // 0或具体数字
			if(parseInt(name.length) === parseInt(cardNumLenHidVal)){
                // 卡号验证通过，验证卡密
                if(parseInt(pass.length) > maxLen){
                	isFixed = false;
                    BatchArrayError.push(conduct);
                }else{
                    if(cardPassLenHidVal != '-1'){
                        if(parseInt(pass.length) === parseInt(cardPassLenHidVal)){
                            // 卡密验证通过
                        	isFixed = true;
                        }else{
                        	isFixed = false;
                            BatchArrayError.push(conduct);
                        }
                    }else{
                    	isFixed = true;
                    }
                }
            }else{
            	isFixed = false;
                BatchArrayError.push(conduct);
            }
		}else{
			if(parseInt(name.length) === 0){
				isFixed = false;
                BatchArrayError.push(conduct);
			}else{
				// 验证卡密
	            if(parseInt(pass.length) > maxLen){
	            	isFixed = false;
	                BatchArrayError.push(conduct);
	            }else{
	                if(cardPassLenHidVal != '-1'){
	                    if(parseInt(pass.length) === parseInt(cardPassLenHidVal)){
	                        // 卡密验证通过
	                    	isFixed = true;
	                    }else{
	                    	isFixed = false;
	                        BatchArrayError.push(conduct);
	                    }
	                }else{
	                	isFixed = true;
	                }
	            }
			}
		}
	
	}
}

/**
* @description: 验证折扣  cardDiscount
*/
function discountCheck(){
	var cardDiscount = $("#cardDiscount");
	var cardDiscountVal = $.trim(cardDiscount.val());

	if(cardDiscountVal === ''){
		layer.msg('请输入供货折扣！！', {icon: 2,shade: [0.4, '#000'],time : 2000});
		return false;
	}else{
		var discountFrom = $.trim($("#discountHidFromId").val());
		var discountEnd = $.trim($("#discountHidEndId").val());
		if(parseFloat(cardDiscountVal) >= discountFrom && parseFloat(cardDiscountVal) <= discountEnd){
			return true;
		}else{
			layer.msg('供货折扣输入不正确！', {icon: 2,shade: [0.4, '#000'],time : 2000});
			return false;
		}
		
	}
}

function _singleCardFn(cardtype, name, pass, conduct){
	var cardNumLenHidVal = $.trim($("#cardNumRule").val());
    var cardPassLenHidVal = $.trim($("#cardPassRule").val()); 
    if(cardtype === 'JD_E'){ // 京东E卡卡密需要用横杠隔开
    	if(name.length === parseInt(cardNumLenHidVal)){
    		isFixed = true;
    		if(pass.length === 19){
    	        isFixed = true;
    	    }else{
    	        isFixed = false;
    	        BatchArrayError.push(conduct);
    	    }
    	}else{
    		isFixed = false;
            BatchArrayError.push(conduct);
    	}
    }else{
    	if(name.length === parseInt(cardNumLenHidVal)){
    		isFixed = true;
    		if(pass.length === parseInt(cardPassLenHidVal)){
    	        isFixed = true;
    	    }else{
    	        isFixed = false;
    	        BatchArrayError.push(conduct);
    	    }
    	}else{
    		isFixed = false;
            BatchArrayError.push(conduct);
    	}
    } 
}

/**
* @description: 验证移动卡
*/
function cardMove(name,pass,conduct){
	
	if(regSeventeen.test(name)){
		isFixed = true;

		//验证卡密
		if(regEighteen.test(pass)){
			isFixed = true;
		}else{
			isFixed = false;
			BatchArrayError.push(conduct);
		}
	}else{
		isFixed = false;
		BatchArrayError.push(conduct);
	}
	
}

/**
* @description: 验证联通卡
*/
function cardUnicom(name,pass,conduct){
	
	if(regFifteen.test(name)){
		isFixed = true;
		//验证卡密
		if(regNineteen.test(pass)){
			isFixed = true;
		}else{
			isFixed = false;
			BatchArrayError.push(conduct);
		}
	}else{
		isFixed = false;
		BatchArrayError.push(conduct);
	}
	
}
/**
* @description: 验证电信卡
*/
function cardTelecom(name,pass,conduct){
	
	if(regNineteen.test(name)){
		isFixed = true;
		//验证卡密
		if(regEighteen.test(pass)){
			isFixed = true;
		}else{
			isFixed = false;
			BatchArrayError.push(conduct);
		}
	}else{
		isFixed = false;
		BatchArrayError.push(conduct);
	}
	
}

/**
* @description: 验证盛大一卡通
*/
function cardSD(name,pass,conduct){
	
	if(regSixteen.test(name)){
		isFixed = true;
		//验证卡密
		if(regEight.test(pass)){
			isFixed = true;
		}else{
			isFixed = false;
			BatchArrayError.push(conduct);
		}
	}else{
		isFixed = false;
		BatchArrayError.push(conduct);
	}
	
}

/**
* @description: 验证q币一卡通
*/
function cardQB(name,pass,conduct){
	
	if(regNine.test(name)){
		isFixed = true;
		//验证卡密
		if(regTwelve.test(pass)){
			isFixed = true;
		}else{
			isFixed = false;
			BatchArrayError.push(conduct);
		}
	}else{
		isFixed = false;
		BatchArrayError.push(conduct);
	}
	
}

/**
* @description: 验证完美一卡通
*/
function cardWM(name,pass,conduct){
	
	if(regTen.test(name)){
		isFixed = true;
		//验证卡密
		if(regFifteen.test(pass)){
			isFixed = true;
		}else{
			isFixed = false;
			BatchArrayError.push(conduct);
		}
	}else{
		isFixed = false;
		BatchArrayError.push(conduct);
	}
	
}

/**
* @description: 验证天宏一卡通
*/
function cardTH(name,pass,conduct){
    var regExp = /[a-z]|[A-Z]$/;
    var thNew = /^[a-zA-Z][a-zA-Z]\d{8}$/;
    var thOld =/^[a-zA-Z][a-zA-Z]\d{10}$/;
    if(thNew.test(name)){
        isFixed = true;
        if(regTen.test(pass)){
            isFixed = true;
        }else{
            isFixed = false;
            BatchArrayError.push(conduct);
        }
    }else if(thOld.test(name)){
        isFixed = true;
        if(regFifteen.test(pass)){
            isFixed = true;
        }else{
            isFixed = false;
            BatchArrayError.push(conduct);
        }

    }else{
        isFixed = false;
        BatchArrayError.push(conduct);
    }
    /*if(!regExp.test(name)){
        if(regTen.test(name)){
            isFixed = true;
            //验证卡密
            if(regTen.test(pass)){
                isFixed = true;
            }else{
                isFixed = false;
                BatchArrayError.push(conduct);
            }
        }else{
            isFixed = false;
            BatchArrayError.push(conduct);
        }
	}else{
        if(thNew.test(name)){
            isFixed = true;
            if(regTen.test(pass)){
                isFixed = true;
            }else{
                isFixed = false;
                BatchArrayError.push(conduct);
            }
        }else if(thOld.test(name)){
            isFixed = true;
            if(regFifteen.test(pass)){
                isFixed = true;
            }else{
                isFixed = false;
                BatchArrayError.push(conduct);
            }

        }else{
            isFixed = false;
            BatchArrayError.push(conduct);
        }
	}*/


	
}
/**
* @description: 验证网易一卡通
*/
function cardWY(name,pass,conduct){
	
	if(regThirteen.test(name)){
		isFixed = true;
		//验证卡密
		if(regNine.test(pass)){
			isFixed = true;
		}else{
			isFixed = false;
			BatchArrayError.push(conduct);
		}
	}else{
		isFixed = false;
		BatchArrayError.push(conduct);
	}
	
}
/**
* @description: 验证征途一卡通
*/
function cardZT(name,pass,conduct){
	
	if(regSixteen.test(name)){
		isFixed = true;
		//验证卡密
		if(regEight.test(pass)){
			isFixed = true;
		}else{
			isFixed = false;
			BatchArrayError.push(conduct);
		}
	}else{
		isFixed = false;
		BatchArrayError.push(conduct);
	}
	
}
/**
* @description: 验证久游一卡通
*/
function cardJY(name,pass,conduct){
	
	if(regThirteen.test(name)){
		isFixed = true;
		//验证卡密
		if(regTen.test(pass)){
			isFixed = true;
		}else{
			isFixed = false;
			BatchArrayError.push(conduct);
		}
	}else{
		isFixed = false;
		BatchArrayError.push(conduct);
	}
	
}
/**
* @description: 验证搜狐一卡通
*/
function cardSH(name,pass,conduct){
	
	if(regTwenty.test(name)){
		isFixed = true;
		//验证卡密
		if(regTwelve.test(pass)){
			isFixed = true;
		}else{
			isFixed = false;
			BatchArrayError.push(conduct);
		}
	}else{
		isFixed = false;
		BatchArrayError.push(conduct);
	}
	
}
/**
* @description: 验证纵游一卡通
*/
function cardZY(name,pass,conduct){
	
	if(regFifteen.test(name)){
		isFixed = true;
		//验证卡密
		if(regFifteen.test(pass)){
			isFixed = true;
		}else{
			isFixed = false;
			BatchArrayError.push(conduct);
		}
	}else{
		isFixed = false;
		BatchArrayError.push(conduct);
	}
	
}
/**
* @description: 验证石油一卡通
*/
function cardHoil(name,pass,conduct){
	
	if(regSixteen.test(name)){
		isFixed = true;
		//验证卡密
		if(regTwenty.test(pass)){
			isFixed = true;
		}else{
			isFixed = false;
			BatchArrayError.push(conduct);
		}
	}else{
		isFixed = false;
		BatchArrayError.push(conduct);
	}
	
}
/**
 * @description: 验证中石油
 */
function cardZSY(name,pass,conduct){

    if(regSeventeen.test(name)){
        isFixed = true;
        //验证卡密
        if(regNineteen.test(pass)){
            isFixed = true;
        }else{
            isFixed = false;
            BatchArrayError.push(conduct);
        }
    }else{
        isFixed = false;
        BatchArrayError.push(conduct);
    }

}
/**
* @description: 验证骏网一卡通
*/
function cardJW(name,pass,conduct){
	
	if(regSixteen.test(name)){
		isFixed = true;
		//验证卡密
		if(regSixteen.test(pass)){
			isFixed = true;
		}else{
			isFixed = false;
			BatchArrayError.push(conduct);
		}
	}else{
		isFixed = false;
		BatchArrayError.push(conduct);
	}
	
}
/**
* @description: 验证盛付通一卡通
*/
function cardSFT(name,pass,conduct){
	
	if(regSixteen.test(name)){
		isFixed = true;
		//验证卡密
		if(regEight.test(pass)){
			isFixed = true;
		}else{
			isFixed = false;
			BatchArrayError.push(conduct);
		}
	}else{
		isFixed = false;
		BatchArrayError.push(conduct);
	}
	
}

/**
 * @description: 验证骏网全业务卡
 * param name:卡号-无卡号
 * param pass:卡密-19位纯数字
 * param conduct:提交方式代号（0001表示单卡提交）
 */
function cardJWAll(name,pass,conduct){
    //验证卡密
    if(regNineteen.test(pass)){
        isFixed = true;
    }else{
        isFixed = false;
        BatchArrayError.push(conduct);
    }
}

/**
 * @description: 验证自游卡
 * param name:卡号-19
 * param pass:卡密-6
 * param conduct:提交方式代号（0001表示单卡提交）
 */
function cardZYK(name,pass,conduct) {
    if(regNineteen.test(name)){
        isFixed = true;
        //验证卡密
        // var regFive = /^[0-9]{5}$/;
        var regSix = /^[0-9]{6}$/;
        if(regSix.test(pass)){
            isFixed = true;
        }else{
            isFixed = false;
            BatchArrayError.push(conduct);
        }
    }else{
        isFixed = false;
        BatchArrayError.push(conduct);
    }
}

/**
 * @description: 验证金山一卡通
 * param name:卡号-13位数字
 * param pass:卡密-9位字母
 * param conduct:提交方式代号（0001表示单卡提交）
 */
function cardJS(name,pass,conduct) {
    var regThirteen = /^[A-Za-z0-9]{13}$/;
    if(regThirteen.test(name)){
        isFixed = true;
        //验证卡密
		var regNine = /^[A-Za-z0-9]{9}$/;
        if(regNine.test(pass)){
            isFixed = true;
        }else{
            isFixed = false;
            BatchArrayError.push(conduct);
        }
    }else{
        isFixed = false;
        BatchArrayError.push(conduct);
    }
}

/**
 * @description: 验证京东E卡
 * param name:卡号-无
 * param pass:卡密-16位+3位-
 * param conduct:提交方式代号（0001表示单卡提交）
 */
function cardJDE(name,pass,conduct) {
    if(pass.length === 19){
        isFixed = true;
    }else{
        isFixed = false;
        BatchArrayError.push(conduct);
    }
}

/**
 * @description: 验证苹果卡
 * param name:卡号-16位
 * param pass:卡密-16位
 * param conduct:提交方式代号（0001表示单卡提交）
 */
function cardAPPLE(name,pass,conduct) {
	if(name.length === 16){
		isFixed = true;
		if(pass.length === 16){
	        isFixed = true;
	    }else{
	        isFixed = false;
	        BatchArrayError.push(conduct);
	    }
	}else{
		isFixed = false;
        BatchArrayError.push(conduct);
	}
}

function _cardCom(name,pass,conduct){
	var cardNumLenHidVal = $.trim($("#cardNumRule").val());
    var cardPassLenHidVal = $.trim($("#cardPassRule").val()); 
    if(name.length === parseInt(cardNumLenHidVal)){
		isFixed = true;
		if(pass.length === parseInt(cardPassLenHidVal)){
	        isFixed = true;
	    }else{
	        isFixed = false;
	        BatchArrayError.push(conduct);
	    }
	}else{
		isFixed = false;
        BatchArrayError.push(conduct);
	}
}

/**
* @description: 批量提交显示报错
*/
function cardBatchError(arrHtml){
	var isOnlyCardPassResult = isOnlyCardPass();
	var noruleResult = isNoRuleFn();
	var cardNumLenHidVal = $.trim($("#cardNumRule").val());
	var productCode = $("#operatorsWrap .data-type-operator.active").attr("product-code");   
	if(arrHtml === '00001'){
		//单卡的验证方式
		$(".mode-inner-error").show();
		
		if(isOnlyCardPassResult){
			if(noruleResult){
				$(".mode-inner-error").find('.txt-red').html('卡密不正确，卡密最多30个字符');
	        }else{
	        	$(".mode-inner-error").find('.txt-red').html('卡密不正确');
	        }
		}else{
			if(noruleResult){
				$(".mode-inner-error").find('.txt-red').html('卡号或卡密不正确，卡号或卡密最多30个字符');
	        }else{
	        	$(".mode-inner-error").find('.txt-red').html('卡号或卡密不正确');
	        	if(productCode==='ZJYDSK'){
					$(".mode-inner-error").find('.txt-red').html('卡号为17位，卡密为18位；卡号第六七位必须是"11"');
				}
	        }
		}
		BatchArrayError.splice(0,BatchArrayError.length);
		timingNone('2000');
	}else{
		//批量的验证方式
		$(".batch-textarea-erro").show();
		$(".batch-textarea-erro").find('p.txt-red').text('');
        
		if(cardNumLenHidVal != '0'){
			if(noruleResult){
	        	$(".batch-textarea-erro").find('p.txt-red').append('[规则]卡号或卡密最多30个字符，卡号不能为空。<br />');
	        }
			if(productCode==='ZJYDSK'){
				$(".batch-textarea-erro").find('p.txt-red').append('[规则]卡号第六七位必须是"11"。<br />');
			}
		}else{
			if(noruleResult){
	        	$(".batch-textarea-erro").find('p.txt-red').append('[规则]卡号或卡密最多30个字符。<br />');
	        }
		}
		
        if(isOnlyCardPassResult){
        	for (var i =0; i< arrHtml.length; i++) {
                $(".batch-textarea-erro").find('p.txt-red').append('行'+arrHtml[i]+'：卡密不正确;<br />');
            }
		}else{	
			for (var i =0; i< arrHtml.length; i++) {
                $(".batch-textarea-erro").find('p.txt-red').append('行'+arrHtml[i]+'：卡号或卡密不正确;<br />');
            }
        }
		BatchArrayError.splice(0,BatchArrayError.length); 
		timingNone('3000');
	}
	
}
/**
* @description: 定时隐藏报错信息
*/
function timingNone(time){
   setTimeout(function(){
   		$(".mode-inner-error").hide();
		$(".batch-textarea-erro").hide();
   },time);
	
}




/**
* @description: 同意协议
*/
function cardProtocol(id){
	var oCardId = $(id);
	var oCardIcon = oCardId.find('.max-icon.icon-agree-up');
	if(oCardIcon.hasClass('icon-agree-off')){
		return true;
	}else{
		return false;
	}
}


/**
* @description: 批量提交: 卡号跟卡密
*/

function cardAallFn(mode){
	if(mode === 'batch'){
		var oAgree = cardProtocol('#batch');
	}else{
	 	var oAgree = cardProtocol('#single');
	}
	
	if(oAgree){
		if(mode === 'batch'){
			if(isBatch){
				if(isFixed){
					cardBatchAjax();
				}
			}
		}else{
			if(isFixed){
				cardSingleAjax();
			}
		}
		
	}else{
		layer.msg('请理解并同意《服务协议》！', {icon: 2,shade: [0.4, '#000'],time : 2000});
	}

}


/**
* @description: 批量提交ajax
*/
function cardBatchAjax(){
	submitCard();
}

/**
* @description: 单卡提交ajax
*/
function cardSingleAjax(){
	submitCard();
}

/**
* @description: 提交卡号、卡密
*/
function submitCard(){
	var limitAmountResult = checkTodayLimitIsEnough();
	if(limitAmountResult){
        var submitType = $.trim($("#type").val());
        if(submitType == "2"){
            clearRepeatCards();
        }else{
            var sCardType = $.trim($("#productClassifyId").val());//卡类
            if(sCardType=="1") {//话费卡提交确认
                var productName = $("#operatorsWrap .data-type-operator.active .product-name").text();
            	var con = '<p>'+productName+'话费卡张数：<span class="txt-red">1张</span></p>' +
                    '<p>注意：切记面值不符，<span class="txt-red" style="font-size: 20px;">余额不退！</span></p>';
                submitPhoneCardsPrompt(con);
            }else{
                submitCardFun();
			}
        }

	}
}

function submitPhoneCardsPrompt(con) {
    var productName = $("#operatorsWrap .data-type-operator.active .product-name").text();
	var price = $("#price").val();
	var sureSubmitCon = '<div class="card-submit-tipcon">尊敬的用户：' +
		'<p>您将要提交卡密为：<span class="txt-red">'+productName+'</span></p>' +
		'<p>面值：<span class="txt-red">'+price+'元</span></p>'+con+
		'</div>';
	layer.open({
		type: 1,
		title: '提交确认',
		content: sureSubmitCon,
		skin: 'lxf-layer-con',
		btn: ['确认提交', '取消']
		,yes: function(indexo, layero){
			//按钮【确认提交】的回调
			submitCardFun();
			layer.close(indexo);
		}
		,btn2: function(index, layero){
			//按钮【取消】的回调
		}
		,cancel: function(){
			//右上角关闭回调
		}
	});
}

function submitCardFun(){
    var index = null;
    var discount = $.trim($("#cardDiscount").val());
    var discountNum = discount.replace(/[\％%]/g,'').replace(/\s/g,"");
    $("#cardDiscount").val(discountNum);

    var productCode = $("#operatorsWrap .data-type-operator.active").attr("product-code");
    if(productCode === 'JD_E'){
    	$("#cardPassHid").val($("#cardPass").val().replace(/\W/g, ''));   	
    }else{
    	$("#cardPassHid").val($("#cardPass").val());
    }
    
	$.ajax({
		url:$("#cardForm").attr("action"),
		data:$("#cardForm").serialize(),
		dataType: "json",
		async: true,
		type: "POST",
		xhrFields: {
			withCredentials: true
		},
		crossDomain: true,
		beforeSend: function() {
			index = layer.msg('销卡处理中，请稍候...', {icon: 16, shade : [0.4, '#000'],time : 100000});
		},
		success: function(data) {
			if(data.code == "000000"){
				layer.close(index);
				layer.alert(data.message, {
					title:'提交成功',
					icon : 1,
					skin: 'layui-layer-lan', //样式类名
					closeBtn: 0
				}, function(){
					window.location.reload();
				});

				//设置cookie
				var cardType = $.trim($("#productClassifyId").val()); //卡类
				var cardOperator = $.trim($("#operatorId").val()); //卡种
				var cardFaceVal = $.trim($("#price").val()); //面值
				var userSelectedCard = new Card(cardType, cardOperator, cardFaceVal);
				addUserSelectedOptionsCookies(userSelectedCard);
			} else {
				// 还没有登录
				if(data.code == "403"){
					document.location.href = $("meta[name='domain']").attr("content") + "/passport/login/index.html";
				}else if(data.code == "503"){	// 还没有实名认证
					layer.alert('<span style="color:#ff3344;">' + data.message + '</span>', {
						title: "提示",
						icon: 2,
						skin: 'layer-ext-moon',
						btn: '实名认证',
						yes: function(index, layero){
							document.location.href = $("meta[name='domain']").attr("content") + "/member/index.do";
						},
						cancel: function(index, layero){//右上角关闭按钮回调
							//window.location.reload();
						}
					});
				} else if (data.code == "000015") {					
					var minLevel = '初级认证';				
					if(parseInt(data.message)===2){
						minLevel = '中级认证';						
					}else if(parseInt(data.message)===3){
						minLevel = '高级认证';						
					}
					layer.alert('<span style="color:#ff3344;">很抱歉！该产品需要完成'+minLevel+'才能提交，请去完成'+minLevel+'</span>', {
					      title: "提示",
					      icon: 2,
					      skin: 'layer-ext-moon',
					      btn: '实名认证',
					      yes: function(index, layero){
					    	  document.location.href = $("meta[name='domain']").attr("content") + "/member/index.do";					    	  
					      },
					      cancel: function(index, layero){//右上角关闭按钮回调
					            //window.location.reload();
					      }
					});
				} else {
                    //alert("表单信息："+$("#cardForm").serialize());
					layer.msg(data.message, {icon : 2,shade : [ 0.4, '#000' ],time : 1500});
				}
			}
		},
		complete: function() {
			layer.close(index);
		},
		error: function(e) {}
	});
}

function round(a,b){for(var c=1;0<b;c*=10,b--);for(;0>b;c/=10,b++);return Math.round(a*c)/c}

/**
 * 只需卡密相关功能切换
 * * @param submitWay:提交方式
 */
function onlyCardPassFn(submitWay){
    var operatorId = $.trim($("#operatorId").val());
    var cardNumLenHidVal = $.trim($("#cardNumRule").val());
    if(submitWay=="1"){//单卡提交
        if(operatorId=="21" || parseInt(cardNumLenHidVal) === 0) {//骏网全业务卡
            $("#single .submit-mode-tit").eq(0).hide();
            $("#single .submit-mode-input").eq(0).hide();
        }else{
            $("#single .submit-mode-tit").eq(0).show();
            $("#single .submit-mode-input").eq(0).show();
        }
    }else if(submitWay=="2"){//批量提交
        if(operatorId=="21" || parseInt(cardNumLenHidVal) === 0) {//骏网全业务卡
            $("#batch .batch-info").hide();
            $("#batch .batch-info.nocode").show();
        }else{
            $("#batch .batch-info").show();
            $("#batch .batch-info.nocode").hide();
        }
    }
}

/**
 * 批量提交去掉重复的卡号
 */
function clearRepeatCards(){
    var cards = $.trim($("#cards").val());
    var cardsArr = cards.split(',');
    var len = cardsArr.length;
    var isOnlyCardPassResult = isOnlyCardPass();
    var cardOperator = $.trim($("#operatorId").val()); //卡种
    if(isOnlyCardPassResult){//去掉重复的卡密
        var new_arr=[];
        for(var i=0; i<len; i++){
            var items = cardsArr[i];
            if($.inArray(items,new_arr)==-1) {
                new_arr.push(items);
            }
        }
        console.log("只有卡密的批量提交，去重后的新数组："+new_arr);
        var new_arrLen = new_arr.length;
		$("#cards").val(new_arr);
		if(cardOperator == '24'){
            $("#cards").val($("#cards").val().replace(/\-/g, ''));
		}
    }else{//去掉重复的卡号+卡密
        var newArry = [];
        for(var i=0; i<len; i++){
            if(i%2==0){
                var item = cardsArr[i]+'&'+cardsArr[i+1];	//卡号&卡密
                newArry.push(item);
            }
        }
        var newArryLen = newArry.length;
        var new_arr=[];
        for(var j=0;j<newArryLen;j++) {
            var items = newArry[j];
            if($.inArray(items,new_arr)==-1) {
                new_arr.push(items);
            }
        }

        var new_arrLen = new_arr.length;
        var m_arr = [];
        for(var p=0;p<new_arrLen;p++){
            var p_arr = new_arr[p].split('&');
            m_arr.push(p_arr[0], p_arr[1]);

        }
		console.log("去重后的新数组："+m_arr);
        $("#cards").val(m_arr);
    }

    var sCardType = $.trim($("#productClassifyId").val());//卡类
    var cardNum = $('.card-operation-txt .txt-red').html();
    if(sCardType=="1") {//话费卡提交确认
        var con = '<p>您提交了'+cardNum+'张卡密，去掉重复的卡密'+ (parseInt(cardNum)-parseInt(new_arrLen)) +'张，实际准备提交<span class="txt-red">'+new_arrLen+'张</span></p>' +
            '<p>注意：切记面值不符，<span class="txt-red" style="font-size: 20px;">余额不退！</span></p>';
        submitPhoneCardsPrompt(con);
    }else{
        var con = '<p>您提交了'+cardNum+'张卡密，去掉重复的卡密'+ (parseInt(cardNum)-parseInt(new_arrLen)) +'张，实际准备提交<span class="txt-red">'+new_arrLen+'张</span></p>';
        submitPhoneCardsPrompt(con);
	}
}