/*
 * ebiz front
 *
 * frontend.js
 *
 * @author allen
 *
 */

var ProductContent = {
    /*this function is jump pageto view cart page*/
    submitAddToShoppingCart :function(){
		//如果hProductItemId==0则用户属性还未选完不能提交
		if( $("#hProductItemId").val() == 0 ){
			//alert("请继续选择产品属性");
			$("#continueSelect").show();
			window.setTimeout('$("#continueSelect").hide()', 3000);
			return;
		}
		//validate the item inventory
	    var result;
	    var quantity = 1;
	    var itemId = $("#hProductItemId").val();
	    result = ProductContent.generatePromptInfoHtml(itemId, quantity);
	    if(result.length > 0){
	        $("#checkcurrent").show();
	        $("#currentinfo").empty();
	        $("#currentinfo").html(result);
	        window.setTimeout('$("#checkcurrent").hide()', 3000);
	        return;
	    }else{
	    	$('#productForm').submit();
	    }
    },
    
    //validate the item qty
    generatePromptInfoHtml : function(itemId, quantity){
    	var result;
    	$.ajax({
            type: 'post',
            url: '/a/getItemInventoryInfoHtml',
            dataType: "html",
            data: {"itemId" : itemId, "quantity" : quantity},
            async: false,
            success: function(responseText){
                result = responseText;
            },
            error: function(){
                result = "";
            }
        });
    	return result;
    },

     //flash item and total count
    flashCount :function(data){
        itemCount = data.item;
        totalCount = data.total;
        $('#itemsCountLabel').html(itemCount);
        $('#itemsTotalLabel').html(totalCount);
    },

    //ajax Paginate for Opinion  
    ajaxOpinionPaginate : function(currentPage){
    	var OpinionHtml = ProductContent.generateOpinionHtml(currentPage);
    	var OpinionPaginationHtml = ProductContent.generateOpinionPaginationHtml(currentPage);
    	$("#pjContent").html(OpinionHtml);
    	$("#opinionPagination").html(OpinionPaginationHtml);
    	
    },
    
    generateOpinionHtml : function(currentPage){
    	var result;
    	var productId = $("#productId").val();
    	$.ajax({
    		type: 'post',
    		url: '/a/getOpinionHtml',
    		dataType: "html",
    		data: {"productId" : productId, "currentPage" : currentPage},
    		async: false,
    		success: function(responseText){
    			result = responseText;
    		},
    		error: function(){
    			result = "";
    		}
    	});
    	return result;
    },
    
    generateOpinionPaginationHtml : function(currentPage){
    	var result;
    	var productId = $("#productId").val();
    	$.ajax({
            type: 'post',
            url: '/a/getOpinionPaginationHtml',
            dataType: "html",
            data: {"productId" : productId, "currentPage" : currentPage},
            async: false,
            success: function(responseText){
                result = responseText;
            },
            error: function(){
                result = "";
            }
        });
    	return result;
    },

    //akimimi add/////////////////////////
    ajaxPaginate : function(currentPage){
//    	var divTitle = "ady_";
//    	var currentDivId;
//    	var result = new Array();
    	for(var i = 1; i < 7; i++){
    		ProductContent.currentShowDiv(i, currentPage);
    	}
    },

    //judje current show div
    currentShowDiv : function(id, currentPage){
    	if(!$("#ady_" + id).is(":hidden")){
    		var queryHtml = ProductContent.generateQueryHtml(id, currentPage);
    		$("#ady_" + id).html(queryHtml);
    	}
    },

    //generate the query html
    generateQueryHtml : function(id, currentPage){
    	var productId = $("#productId").val();
    	$.ajax({
            type: 'post',
            url: '/a/getQueryHtml',
            dataType: "html",
            data: {"currentDiv" : id , "productId" : productId, "currentPage" : currentPage},
            async: false,
            success: function(responseText){
                result = responseText;
            },
            error: function(){
                result = false;
            }
        });
    	if(result){
    		return result;
    	}
    	return "";
    },

    //judge the user if login and submit the query
    submitQuery : function(){
    	var uid = $("#userId").val();
    	var content = $("#queryContent").val();
    	if(ValidationUtil.isBlank(uid)){
    		alert("请先登录");
    		window.location='/u/login';
    		return;
    	}else if( $.trim(content).length <= 0 ){
    		alert("请填写内容");
    		return;
    	}else if( $.trim(content).length > 200 ){
			alert("填写内容请不要超过200个汉字");
			return;
    	}else{
    		var userId = $("#userId").val();
    		var productId = $("#productId").val();
    		var queryContent = $("#queryContent").val();
    		var queryType = $("#queryType").val();
    		$.ajax({
                type: 'post',
                url: '/a/submitQuery',
                //dataType: "html",
                data: {"userId" : userId , "productId" : productId, "queryContent" : queryContent , "queryType" : queryType },
                async: false,
                success: function(data){
                	if(data == "success"){
                		result = true;
                	}else{
                		result = false;
                	}
                },
                error: function(){
                    result = false;
                }
            });
    		if(result){
    			$("#queryContent").val("");
    			alert("提交成功");
    			//ajax generate review the all consult
    			ProductContent.queryAllHtml(productId);
    			var jsonNum = ProductContent.queryNumberHtml(productId);
    			if( jsonNum != "" ){
    				ProductContent.generateNumberHtmlCode(jsonNum);
    			}
    		}
    	}
    },
    
    //generate the consult info begin
    
    queryAllHtml : function(productId){
    	var result;
    	$.ajax({
            type: 'post',
            url: '/a/queryAllHtml',
            dataType: "html",
            data: {"pid" : productId},
            async: false,
            success: function(data){
            	result = data;
            },
            error: function(){
                result = "";
            }
        });
    	$("#consultAllInfo").html(result);
    },
    
    queryNumberHtml : function(productId){
    	var result;
    	$.ajax({
            type: 'post',
            url: '/a/queryNumberHtml',
            dataType: "json",
            data: {"pid" : productId},
            async: false,
            success: function(data){
            	result = data;
            },
            error: function(){
                result = "";
            }
        });
    	return result;
    },
    
    generateNumberHtmlCode : function(jsonNum){
    	$("#all_num_id").html(jsonNum.queryAllNum);
    	$("#goods_num_id").html(jsonNum.queryGoodsNum);
    	$("#distribute_num_id").html(jsonNum.queryDistributeNum);
    	$("#payment_num_id").html(jsonNum.queryPaymentNum);
    	$("#campuses_num_id").html(jsonNum.queryCampusesNum);
    	$("#maintain_num_id").html(jsonNum.queryMaintainNum);
    },
    
    //generate the consult info end
    
    showComment : function(){
    	$("#commentButton").hide();
    	$("#submitComment").show();
    },

    showBuyKnowledge : function(anchor){//give the anchor to show the part
    	$("#detail_par_1").hide();
    	$("#detail_par_3").show();
    	window.location="#"+anchor;
    },
    
    closePromptInfo : function(){
    	$("#checkcurrent").hide();
    },
    
    closeContinueSelectInfo : function(){
    	$("#continueSelect").hide();
    },
    
    //将产品添加到wishlist中
    submitAddToWishlist : function(){
    	//精确到item否则给出提示
    	if( $("#hProductItemId").val() == 0 ){
			$("#continueSelect").show();
			window.setTimeout('$("#continueSelect").hide()', 3000);
			return;
		}
    	var itemId = $("#hProductItemId").val();
    	$.ajax({
            type: 'post',
            url: '/a/addtowishlist',
            dataType: "html",
            data: {"itemId" : itemId},
            async: false,
            success: function(result){
            	if(result == "false"){
            		window.location='/u/login';
            		return;
            	}
            	$("#addWishlistDiv").show();
    	        window.setTimeout('$("#addWishlistDiv").hide()', 3000);
    	        return;
            },
            error: function(){
                return;
            }
        });
    },
    
    closePromptInfoDiv : function(id){
    	$("#"+id).hide();
    }
    

}

var shoppingcart = {

    deleteshoppingcart : function(scId){
        var prompt = $.trim($("#prompt").val());
        if(confirm(prompt)) {
            window.location='/o/deleteShoppingInfo?scId='+scId;
        }
        return false;
    },

    delcookieshoppingcart : function(pItemId){
        var prompt = $.trim($("#prompt").val());
        if(confirm(prompt)) {
            window.location='/o/deleteCookieShoppingInfo?pItemId='+pItemId;
        }
        return false;
    },

    checkout : function(){
        var result;
        var itemIdArray = Array();
        var quantityArray = Array();
        var scIdArray = Array();
        itemId = $("input[name='itemId[]']");
        quantity = $("input[name='quantity[]']");
        scId = $("input[name='scId[]']");
        $.each(itemId, function(i, obj){
            itemIdArray[itemIdArray.length] = obj.value;
        });
        $.each(quantity, function(i, obj){
            quantityArray[quantityArray.length] = obj.value;
        });
        $.each(scId, function(i, obj){
            scIdArray[scIdArray.length] = obj.value;
        });
        itemIds = itemIdArray.join(",");
        quantitys = quantityArray.join(",");
        scIds = scIdArray.join(",");
        result = shoppingcart.generateHtml(itemIds, quantitys, scIds);
        if(result.length > 0){
            $("#checkcurrent").show();
            $("#currentinfo").empty();
            $("#currentinfo").html(result);
            return;
        }else{
            shoppingcart.submitCheckOut();
        }
    },

    generateHtml : function(itemIds, quantitys, scIds){
        $.ajax({
            type: 'post',
            url: '/a/getItemQtyInfo',
            dataType: "html",
            data: {"itemIds" : itemIds , "quantitys" : quantitys , "scIds" : scIds},
            async: false,
            success: function(responseText){
                result = responseText;
            },
            error: function(){
                result = false;
            }
        });
        return result;
    },

    submitCheckOut : function(){
        $('#shoppingCartForm').attr("action", "/o/updateShoppingForCheckout");
        $('#shoppingCartForm').submit();
    }

}



/**********************************************************************************************************************/



var UtilFunction = {

    in_array : function(needle, haystack) {
        for(var i in haystack) {
            if(haystack[i] == needle) {
                return true;
            }
        }
        return false;
    },

    showDiv : function(id){
        $("#" + id).show();
    },

    hideDiv : function(id){
        $("#" + id).hide();
    },

    toggleDiv: function(id){
        $("#" + id).toggle();
    },

    unique : function(data){
        data = data || [];
        var a = {};
        for (var i=0; i<data.length; i++) {
            var v = data[i];
            if (typeof(a[v]) == 'undefined'){
                a[v] = 1;
            }
        };
        data.length=0;
        for (var i in a){
            data[data.length] = i;
        }
        return data;
    },

    formatFloat : function(num, pos){//the js rounding function
        if(parseFloat(num) == 0){
            return num.toFixed(pos);
        }else if(parseInt(num) == num){
            return num.toFixed(pos);
        }else{
            return (Math.round(num * Math.pow(10, pos)) / Math.pow(10, pos)).toFixed(pos);
        }
    },

    gotoUrl: function(url){
        window.location = url;
    },

	showDialog: function(config){
        var dialogId = config.dataDiv;
        var height = config.height;
        var width = config.width
        //init dialog
        $("#" + dialogId).dialog({
                        modal: true ,
                        height: height ,
                        autoOpen: true,
                        width: width,
                        resizable: false,
                        overlay: {
                           opacity: 0.6,
                           background: "#555555"
                        },
                        close: function(event, ui) {
                            $("#" + dialogId).dialog( 'destroy' );
                        }
        });
    },

    setOptionCancel : function(optionName){
    	$("input[type=radio][name='"+optionName+"']").each(function (){
    		this.checked = false;
    	});
    }


}

var ValidationUtil = {

		isBlank: function(v){
            return  ((v == null) || (v.length == 0));
        },

        isNumber:function(v){
            return this.isBlank(v) || !(/^\d+(\.\d+)?$/.test(v));
        },

        isDigits:function(v){
            return this.isBlank(v) || /[^\d]/.test(v);
        },

        isEmail:function(v){
            return  /^[a-z0-9_\-\.]+@[a-z0-9_\-\.]+\.[a-z]{2,4}$/.test(v);
        },

        isDate:function(v){
            return this.isBlank(v) || !/Invalid|NaN/.test(new Date(v));
        },

        checkRangeValue : function(v,paramMin,paramMax){
            return !(v >= paramMin && v <= paramMax) ;
        },

        showErrMsg:function(node,msg){
            $(node).innerHTML = msg;
        },

        clearErrMsg:function(node){
            $(node).innerHTML = '';
        },

        /*
        * new add to validate is letter and not blank
        */
        isLetter: function(v){
            return  this.isBlank(v) || !(/^[a-zA-Z]+$/.test(v));
        },

        isInteger: function(v){
            return  /^[1-9]+[0-9]*]*$/.test(v);
        },

        isUserName: function(v){
            return  /^[a-zA-Z\u4E00-\u9FA5]{1,1}[a-zA-Z0-9\u4E00-\u9FA5\_]{1,11}/.test(v);
        },
        validataPsw : function(v){
            return /(\d+[a-zA-Z]+)|([a-zA-Z]+\d+)/.test(v);
        },
        isMobilePhone : function(v){
            return  /^(\+*\d{2})*1\d{10}$/.test(V);
        }
        /**
         * @todo validateStringLength( strString, intLengthMax, [intLengthMin] )
         */
}

//for akimimi

var Register = {

	checkSchool : function()
    {
	  $("#school_label").removeClass();
	  var item = $("input[name='schoolRadio']:checked").val();
	  if(item == 1)
	  {
		  $("#select_school").slideDown("slow");
		  //$("#select_school").show();
		  $("#isSchool").val(1);
	  }
	  else
	  {
		  $("#select_school").slideUp("slow");
		  //$("#select_school").hide();
		  $("#isSchool").val(2);
	  }
    },

    regSubmit : function(){
        var validate = true;
        if(!Register.validateUserName()){
            validate = false;
        }
        if(!Register.validateEmail()){
            validate = false;
        }
        if(!Register.validatePassword()){
            validate = false;
        }
        if(!Register.validateRepassword()){
            validate = false;
        }
        if(!Register.validateCaptcha()){
            validate = false;
        }

		var isSchool = $('#school').attr('checked');
		if(isSchool){
			if(!Register.validateHighSchool()){
                validate = false;
            }
		}

		var agree = $('#agreement').attr('checked');
		if(!agree){
			var errorMsg = $('#errorNoAgreement').val();
			$('#errorAgreement').addClass("onError");
			$('#errorAgreement').html(errorMsg);

		} else {
			$('#errorAgreement').html('');
		}
        if(validate){
            $('#regForm').submit();
        }
        return validate;
    },

    validateUserName : function(){
        var result = false;
        var username = $.trim($('#username').val());
        var errorNameEmpty = $('#errorNameEmpty').val();
        var errorNameExist = $('#errorNameExist').val();
        var errorNameError = $('#errorNameError').val();
        var errorNameRight = $('#errorNameRight').val();
        if(ValidationUtil.isBlank(username)){
			$("#errorUserName").addClass("onError");
            $('#errorUserName').html(errorNameEmpty);
            return result;
        }else if(!ValidationUtil.isUserName(username)){
			$("#errorUserName").addClass("onError");
            $('#errorUserName').html(errorNameError);
            return result;
        }else if(ValidationUtil.checkRangeValue(username.length, 2, 12)){
			$("#errorUserName").addClass("onError");
            $('#errorUserName').html(errorNameError);
            return result;
        }
        $.ajax({
            type: 'post',
            url: '/a/validateUserName',
            data: {"username" : username},
            dataType: "json",
            async: false,  //false is synchronization , true is asynchronism
            success: function(data){
                if(data.result){    //true or false
				    $("#errorUserName").removeClass("onError");
                    $('#errorUserName').html(errorNameRight);
                    result = true;
                }else{
					$("#errorUserName").addClass("onError");
                    $('#errorUserName').html(errorNameExist);
                    result = false;
                }
            },
            error: function(){
                result = false;
            }
        });
        return result;   //return result, if equal true then submit
    },

    validateEmail : function(){
        var result = false;
        var errorEmailEmpty = $('#errorEmailEmpty').val();
        var errorEmailExist = $('#errorEmailExist').val();
        var errorEmailError = $('#errorEmailError').val();
        var errorEmailRight = $('#errorEmailRight').val();
        var email = $.trim($('#email').val());
        if(ValidationUtil.isBlank(email)){
			$("#errorEmail").addClass("onError");
            $('#errorEmail').html(errorEmailEmpty);
            return result;
        }else if(!ValidationUtil.isEmail(email)){
			$("#errorEmail").addClass("onError");
            $('#errorEmail').html(errorEmailError);
            return result;
        }
        $.ajax({
            type: 'post',
            url: '/a/validateEmail',
            data: {"email" : email},
            dataType: "json",
            async: false,  //false is synchronization , true is asynchronism
            success: function(data){
                if(data.result){    //true or false
				    $("#errorEmail").removeClass("onError");
                    $('#errorEmail').html(errorEmailRight);
                    result = true;
                }else{
					$("#errorEmail").addClass("onError");
                    $('#errorEmail').html(errorEmailExist);
                    result = false;
                }
            },
            error: function(){
                result = false;
            }
        });
        return result;   //return result, if equal true then submit
    },

    validatePassword : function(){
        var result = false;
        var errorPasswordEmpty = $('#errorPasswordEmpty').val();
        var errorPasswordError = $('#errorPasswordError').val();
        var errorPasswordRight = $('#errorPasswordRight').val();
        var password = $.trim($('#password').val());
        if(ValidationUtil.isBlank(password)){
			$("#errorPassword").addClass("onError");
            $('#errorPassword').html(errorPasswordEmpty);
            return result;
        }else if(ValidationUtil.checkRangeValue(password.length, 6, 18)){
			$("#errorPassword").addClass("onError");
            $('#errorPassword').html(errorPasswordError);
            return result;
        }else{
			$("#errorPassword").removeClass("onError");
            $('#errorPassword').html(errorPasswordRight);
            return true;
        }
    },

    validateRepassword : function(){
        var result = false;
        var errorRepasswordEmpty = $('#errorRepasswordEmpty').val();
        var errorRepasswordError = $('#errorRepasswordError').val();
        var errorRepasswordRight = $('#errorRepasswordRight').val();
        var repassword = $.trim($('#repassword').val());
        var password = $.trim($('#password').val());
        if(ValidationUtil.isBlank(repassword)){
			$("#errorRepassword").addClass("onError");
            $('#errorRepassword').html(errorRepasswordEmpty);
            return result;
        }else if(repassword != password){
			$("#errorRepassword").addClass("onError");
            $('#errorRepassword').html(errorRepasswordError);
            return result;
        }else{
			$("#errorRepassword").removeClass("onError");
            $('#errorRepassword').html(errorRepasswordRight);
            return true;
        }
    },

    validateCaptcha : function(){
        var result = false;
        var errorCaptchaEmpty = $('#errorCaptchaEmpty').val();
        var errorCaptchaError = $('#errorCaptchaError').val();
        var errorCaptchaRight = $('#errorCaptchaRight').val();
        var captcha = $.trim($('#captcha').val()).toLowerCase();
        var codedata = $.trim($('#codedata').val()).toLowerCase();
        if(ValidationUtil.isBlank(captcha)){
			$("#errorCaptcha").addClass("onError");
            $('#errorCaptcha').html(errorCaptchaEmpty);
            return result;
        }else if(captcha != codedata){
			$("#errorCaptcha").addClass("onError");
            $('#errorCaptcha').html(errorCaptchaError);
            return result;
        }else{
			$("#errorCaptcha").removeClass("onError");
            $('#errorCaptcha').html(errorCaptchaRight);
            return true;
        }
    },

	validateHighSchool : function(){
        var result = false;
        var errorHighSchoolEmpty = $('#errorHighSchoolEmpty').val();
        $('#errorSchool').html('');
        var school = $.trim($('#campusesName').val());
        if(ValidationUtil.isBlank(school)){
			$("#errorSchool").addClass("onError");
            $('#errorSchool').html(errorHighSchoolEmpty);
            return result;
        }else{
			$("#errorSchool").removeClass("onError");
            return true;
        }
    },

    changeCaptcha : function(){
        var result;
        $.ajax({
            type: 'post',
            url: '/a/changeCaptchaImg',
            async: false,  //false is synchronization , true is asynchronism
            success: function(data){
                result = data;
                $('#captchaImg').html(result);
            },
            error: function(){
                result = false;
            }
        });
    }
}

var Login = {

    loginSubmit : function(){
        var validate = true;
        var errorLoginError = $('#errorLoginError').val();
        $('#errorLabel').html("");
        if(!Login.validateEmail()){
            validate = false;
			return false;
        }
        if(!Login.validatePassword()){
            validate = false;
			return false;
        }
        if(!Login.validateCaptcha()){
            validate = false;
			return false;
        }
        if(validate){
            var result = Login.validateLogin();
            if(result){
//            	alert(document.getElementById("quickpage"));
            	if(document.getElementById("quickpage") != null){
            		window.location.href="/u/checkout";
            	}else{
            		window.location.href="/";
            	}
            }else{
                $('#errorLabel').html(errorLoginError);
            }
        }
       return false;
    },

    validateEmail : function(){
        var errorEmailEmpty = $('#errorEmailEmpty').val();
        var errorEmailError = $('#errorEmailError').val();
        var email = $.trim($('#email1').val());
        if(ValidationUtil.isBlank(email)){
            $('#errorLabel').html(errorEmailEmpty);
            return false;
        }else if(!ValidationUtil.isEmail(email)){
            $('#errorLabel').html(errorEmailError);
            return false;
        }else{
            $('#errorLabel').html("");
            return true;   //return result, if equal true then submit
        }
    },

    validatePassword : function(){
        var errorPasswordEmpty = $('#errorPasswordEmpty').val();
        var password = $.trim($('#password1').val());
        if(ValidationUtil.isBlank(password)){
            $('#errorLabel').html(errorPasswordEmpty);
            return false;
        }else{
            $('#errorLabel').html("");
            return true;
        }
    },


    validateCaptcha : function(){
        var errorCaptchaEmpty = $('#errorCaptchaEmpty').val();
        var errorCaptchaError = $('#errorCaptchaError').val();
        var captcha = $.trim($('#captcha1').val()).toLowerCase();
        var codedata = $.trim($('#codedata1').val()).toLowerCase();
        if(ValidationUtil.isBlank(captcha)){
            $('#errorLabel').html(errorCaptchaEmpty);
            return false;
        }else if(captcha != codedata){
            $('#errorLabel').html(errorCaptchaError);
            return false;
        }else{
            $('#errorLabel').html("");
            return true;
        }
    },

    changeCaptcha : function(){
        var result;
        $.ajax({
            type: 'post',
            url: '/a/changeCaptchaImg?n=1',
            async: false,  //false is synchronization , true is asynchronism
            success: function(data){
                result = data;
                $('#captchaImg1').html(result);
            },
            error: function(){
                result = false;
            }
        });
    },

    validateLogin : function(){
        var result;
        var email = $('#email1').val();
        var password = $('#password1').val();
        $.ajax({
            type: 'post',
            url: '/a/login',
            data: {"email" : email , "password" : password},
            async: false,  //false is synchronization , true is asynchronism
            success: function(data){
                if(data == "success"){
                    result = true;
                }else{
                    result = false;
                }
            },
            error: function(){
                result = false;
            }
        });
        return result;
    }
}

var FindPassword = {

    findPasswordSubmit : function(){
        var validate = true;
        if(!FindPassword.validateEmail()){
            validate = false;
        }
        if(validate){
            $('#findPasswordForm').submit();
        }
        return validate;
    },

    validateEmail : function(){
        var errorEmailEmpty = $('#errorEmailEmpty').val();
        var errorEmailError = $('#errorEmailError').val();
        var email = $.trim($('#email').val());
        if(ValidationUtil.isBlank(email)){
			$('#errorEmail').addClass('onError');
            $('#errorEmail').html(errorEmailEmpty);
            return false;
        }else if(!ValidationUtil.isEmail(email)){
			$('#errorEmail').addClass('onError');
            $('#errorEmail').html(errorEmailError);
            return false;
        }else{
			$('#errorEmail').removeClass('onError');
            $('#errorEmail').html("");
            return true;   //return result, if equal true then submit
        }
    }
}

var UpdatePassword = {

    updateSubmit : function(){
        var validate = true;
        if(!Register.validatePassword()){
            validate = false;
        }
        if(!Register.validateRepassword()){
            validate = false;
        }
        if(validate){
            $('#updatePasswordForm').submit();
        }
        return validate;
    },

    validatePassword : function(){
        var result = false;
        var errorPasswordEmpty = $('#errorPasswordEmpty').val();
        var errorPasswordError = $('#errorPasswordError').val();
        var errorPasswordRight = $('#errorPasswordRight').val();
        var password = $.trim($('#password').val());
        if(ValidationUtil.isBlank(password)){
			$('#errorPassword').addClass('onError');
            $('#errorPassword').html(errorPasswordEmpty);
            return result;
        }else if(ValidationUtil.checkRangeValue(password.length, 6, 18)){
			$('#errorPassword').addClass('onError');
            $('#errorPassword').html(errorPasswordError);
            return result;
        }else{
			$('#errorPassword').removeClass('onError');
            $('#errorPassword').html(errorPasswordRight);
            return true;
        }
    },

    validateRepassword : function(){
        var result = false;
        var errorRepasswordEmpty = $('#errorRepasswordEmpty').val();
        var errorRepasswordError = $('#errorRepasswordError').val();
        var errorRepasswordRight = $('#errorRepasswordRight').val();
        var repassword = $.trim($('#repassword').val());
        var password = $.trim($('#password').val());
        if(ValidationUtil.isBlank(repassword)){
			$('#errorRepassword').addClass('onError');
            $('#errorRepassword').html(errorRepasswordEmpty);
            return result;
        }else if(repassword != password){
			$('#errorRepassword').addClass('onError');
            $('#errorRepassword').html(errorRepasswordError);
            return result;
        }else{
			$('#errorRepassword').removeClass('onError');
            $('#errorRepassword').html(errorRepasswordRight);
            return true;
        }
    }
}
var ModifyPassword = {

       validateOldPassword : function(){
            var result = false;
            var errorOldPasswordEmpty = $('#errorOldPasswordEmpty').val();
            var errorOldPasswordError = $('#errorOldPasswordError').val();
            var errorPassworedRight = $('#errorPasswordRight').val();
            $('#errorOldPassword').html('');
            var oldPassword = $.trim($('#oldPassword').val());
            if(ValidationUtil.isBlank(oldPassword)){
                $('#errorOldPassword').html(errorOldPasswordEmpty);
                return result;

            }
            $.ajax({
                 type: 'post',
                 url: '/a/validateOldPassword',
                 data: {"oldPassword" : oldPassword},
                 async: false,  //false is synchronization , true is asynchronism
                 success: function(data){
                    if(data=='true'){
                    $('#errorOldPassword').html(errorPassworedRight);
                        result = true;
                    }else{
                        $('#errorOldPassword').html(errorOldPasswordError);
                        result = false;
                    }
                 },
                 error: function(){
                      $('#errorOldPassword').html(errorOldPasswordError);
                      result = false;
                    }
                });
            return result;

        },
        validateNewPassword : function(){
            var result = false;
            var errorNewPasswordEmpty = $('#errorNewPasswordEmpty').val();
            var passwordError = $('#errorPasswordError').val();
            var errorPassworedRight = $('#errorPasswordRight').val();
            $('#errorNewpassword').html('');
            var newPassword = $.trim($('#newPassword').val());
            if(ValidationUtil.isBlank(newPassword)){
                $('#errorNewpassword').html(errorNewPasswordEmpty);
                return result;
            } else if(ValidationUtil.checkRangeValue(newPassword.length, 6, 18)){
                $('#errorNewpassword').html(passwordError);
                return result;
            }else{
                $('#errorNewpassword').html(errorPassworedRight);
                return true;
            }

        },

        validateRepassword : function(){
            var result = false;
            var errorRepasswordEmpty = $('#errorRepasswordEmpty').val();
            var errorRepasswordError = $('#errorRepasswordError').val();
            var errorRepasswordRight = $('#errorRepasswordRight').val();
            var repassword = $.trim($('#repassword').val());
            var newPassword = $.trim($('#newPassword').val());
            if(ValidationUtil.isBlank(repassword)){
                $('#errorRepassword').html(errorRepasswordEmpty);
                return result;
            }else if(repassword != newPassword){
                $('#errorRepassword').html(errorRepasswordError);
                return result;
            }else{
                $('#errorRepassword').html(errorRepasswordRight);
                return true;
            }
        },

        modifySubmit : function(){
            var validate = true;
            if(!ModifyPassword.validateOldPassword()){
                validate = false;
            }
            if(!ModifyPassword.validateNewPassword()){
                validate = false;
            }
            if(!ModifyPassword.validateRepassword()){
                validate = false;
            }
       //     if(!Register.validateCaptcha()){
      //          validate = false;
      //      }
            if(validate){
                $('#modifyPasswordForm').submit();
            }
            return validate;
        }

}

var CheckOut = {

    usedPromotion : Array(), //promotion id

    usedPromotionCode : Array(), //promotion code

    stackable : 1, //1 is can use next promotion , 0 is can not use next promotion

    /*
     * shipping info part
     * cheque rule
     * hid is tax price hidden id , pid is show price span id, rule=n is without invoice ,rule=y is use invoice
     * taxFee is at last to form post value hidden id
     */
    radioListener : function (obj){//obj:当前对象,如果当前radio是选中的则返回false否则返回true
		if(obj.value>0)
			var otherRadio = obj.parentNode.parentNode.previousSibling.childNodes[0].childNodes[0];
		else
			var otherRadio = obj.parentNode.parentNode.nextSibling.childNodes[0].childNodes[0];
		if( $(obj).attr('alreadycheck') )
			return false;
		$(obj).attr('alreadycheck','1');
		$(otherRadio).attr('alreadycheck','');
		return true;
	},
	
	chequeRule : function(hid, pid, rule, taxFee, obj){
	    if( !CheckOut.radioListener(obj) )
	    	return false;//当前按钮已经被选中不允许再点击
		
		var taxPrice = Number( $("#" + hid).val() );
		var estimatedTax = Number( $("#estimatedTax").val() );
		var taxPriceTempt = 0;
		if(rule == "y"){
			taxPriceTempt = estimatedTax + taxPrice;
			//taxPriceTempt = taxPriceTempt.toFixed(2);
//			if( taxPriceTempt != parseInt(taxPriceTempt) ){
//				taxPriceTempt = UtilFunction.formatFloat( taxPriceTempt );
//			}
			$("#" + pid).html(UtilFunction.formatFloat(taxPrice, 2));
			$("#" + taxFee).val(taxPrice);
			$("#estimatedTaxLabel").html(UtilFunction.formatFloat(taxPriceTempt, 2));
			$("#reestimatedTaxLabel").html(UtilFunction.formatFloat(taxPriceTempt, 2));
			$("#estimatedTax").val(taxPriceTempt);
		}else{
			taxPriceTempt = estimatedTax - taxPrice;
			$("#" + pid).html("0.00");
			$("#" + taxFee).val(0);
			$("#estimatedTaxLabel").html(UtilFunction.formatFloat(taxPriceTempt, 2));
			$("#reestimatedTaxLabel").html(UtilFunction.formatFloat(taxPriceTempt, 2));
			$("#estimatedTax").val(taxPriceTempt);
		}
		var tag = false;//false id all without invoice , true is use invoice then textbox show info
        var itemIdArray = Array();
        var itemId = $("input[name='itemId[]']");
        $.each(itemId, function(i, obj){
            itemIdArray[itemIdArray.length] = obj.value;
        });
        for(var i = 0; i < itemIdArray.length; i++){
        	var id = itemIdArray[i];
        	var value = $("input[name='invoiceCheck_"+id+"']:checked").val();
        	if(value == 1){//at least have one use invoice
        		tag = true;
        	}
        }
        if(tag){//true is use invoice
        	$("#invoiceTitle").val("");
        	$("#invoiceTitle").attr("readOnly", false);
        }else{
        	$("#invoiceTitle").val("不需要发票");
        	$("#invoiceTitle").attr("readOnly", true);
        }
        CheckOut.countAllTotalPrice();
	},

	validateChequeRule : function(){//use in the checkout page onload
		var tag = false;//false is all without invoice , true is use invoice then textbox show info
        var itemIdArray = Array();
        var itemId = $("input[name='itemId[]']");
        $.each(itemId, function(i, obj){
            itemIdArray[itemIdArray.length] = obj.value;
        });
        for(var i = 0; i < itemIdArray.length; i++){
        	var id = itemIdArray[i];
        	var value = $("input[name='invoiceCheck_"+id+"']:checked").val();
        	if(value == 1){//at least have one use invoice
        		tag = true;
        	}
        }
        if(tag){//true is use invoice
        	$("#invoiceTitle").val("");
        	$("#invoiceTitle").attr("readOnly", false);
        }else{
        	$("#invoiceTitle").val("不需要发票");
        	$("#invoiceTitle").attr("readOnly", true);
        }
	},

    /*
     * checkout address part
     */
    showAddAddressInfo : function(){//add address button then show the address info div
        $("#addAddress").show();
    },

    addNewAddress : function(){//the button of add address info
        var addUserName = $.trim($("#addUserName").val());
        var province = $("#province").val();
        var city = $("#city").val();
        var county = $("#county").val();
        var addOtherAddress = $.trim($("#addOtherAddress").val());
        var addPhone = $.trim($("#addPhone").val());
        var addMobileTelephone = $.trim($("#addMobileTelephone").val());
        var addEmail = $.trim($("#addEmail").val());
        var addressNum = CheckOut.validateAddressNum();
        var submit = true;
        var errorUserNameEmpty = $("#errorUserNameEmpty").val();
        var errorAreaEmpty = $("#errorAreaEmpty").val();
        var errorOtherAreaEmpty = $("#errorOtherAreaEmpty").val();
        var errorMobilePhoneEmpty = $("#errorMobilePhoneEmpty").val();
        var errorMobilePhone = $("#errorMobilePhone").val();
        var errorEmailEmpty = $("#errorEmailEmpty").val();
        var errorEmail = $("#errorEmail").val();
        $("#errorUserName").html("");
        $("#errorOtherAddress").html("");
        $("#errorMobilePhoneInfo").html("");
        $("#errorEmailInfo").html("");
        if(ValidationUtil.isBlank(addUserName)){
            $("#errorUserName").html(errorUserNameEmpty);
            submit = false;
        }
        if(!AreaDict.validateAreaDict()){
            submit = false;
        }
        if(ValidationUtil.isBlank(addOtherAddress)){
            $("#errorOtherAddress").html(errorOtherAreaEmpty);
            submit = false;
        }
        if(ValidationUtil.isBlank(addMobileTelephone)){
            $("#errorMobilePhoneInfo").html(errorMobilePhoneEmpty);
            submit = false;
        }else if(!ValidationUtil.isInteger(addMobileTelephone) || addMobileTelephone.length != 11){
        	$("#errorMobilePhoneInfo").html(errorMobilePhone);
        	submit = false;
        }
        if(ValidationUtil.isBlank(addEmail)){
            $("#errorEmailInfo").html(errorEmailEmpty);
            submit = false;
        }else if(!ValidationUtil.isEmail(addEmail)){
        	$("#errorEmailInfo").html(errorEmail);
            submit = false;
        }
        if(submit){
            if(Number(addressNum) < 5){
                $("#addNewAddressBtn").show();
                $.ajax({
                     type: 'post',
                     url: '/a/addNewAddress',
                     data: {"addUserName":addUserName,"province":province,"city":city,"county":county,"addOtherAddress":addOtherAddress,"addPhone":addPhone,"addMobileTelephone":addMobileTelephone,"addEmail":addEmail},
                     //dataType: "json",
                     async: false,  //false is synchronization , true is asynchronism
                     success: function(data){
                         $("#addAddress").hide();
                         //give current option name to clear all the option ( set the option is cancel )
                         UtilFunction.setOptionCancel("address");
                         $("#addressInfo").append(data);
                         $("#existAddress").val("1");
                         CheckOut.useTheAddressInfo("address");
                         if(Number(addressNum) == 4){
                        	 $("#addAddress").hide();
                        	 $("#addNewAddressBtn").hide();
                         }
                     },
                     error: function(){
                          result = false;
                     }
                });
            }else{
                $("#addAddress").hide();
                $("#addNewAddressBtn").hide();
            }
        }
    },

    validateAddressNum : function(){//if the user address number generate five then return false
        var result;
        $.ajax({
             type: 'post',
             url: '/a/countAddressNum',
             //data: {},
             //dataType: "json",
             async: false,  //false is synchronization , true is asynchronism
             success: function(data){
                 result = data;
             },
             error: function(){
                 result = false;
             }
        });
        return result;
    },

    useTheAddressInfo : function(){//the button of use current checked//if select xinjiang or xizang then SF shipping do not select
        var addressId = $("input[name='address']:checked").val();
        var addressInfo = $("#address_" + addressId).html();
        $("#currentUseAddress").html(addressInfo);
        $("#addressInfo").hide();
        $("#currentUseAddress").show();
        $("#useAddressBtn").hide();
        $("#addAddressBtn").hide();
        $("#addressModify").show();
        $("#addressComplete").hide();
        $("#addAddress").hide();
        CheckOut.validateProvinceForSFShipType();//ajax function to judge the province if can ship
        CheckOut.countShipFee();//count the ship price
    },

    validateProvinceForSFShipType : function(){//if province is xinjiang or xizang then show error info
    	var addressId = $("input[name='address']:checked").val();
    	var deliveryRadio = $("input[name='deliveryRadio']:checked").val();
    	//ajax judge current province if is xinjiang or xizang then SF shipping not to select
        $.ajax({
            type: 'post',
            url: '/a/judgeExceptionProvince',
            data: {"addressId" : addressId},
            //dataType: "json",
            async: false,  //false is synchronization , true is asynchronism
            success: function(data){
                result = data;
            },
            error: function(){
                result = false;
            }
       });
       if(result == "xjxz" || result == false){
    	   if(deliveryRadio == 5){//current select is SF shipping type
    		   $("#errorSFInfo").show();
    		   $("#exceptionProvince").val(0);//0 is can not to submit
    	   }else{
    		   $("#errorSFInfo").hide();
    		   $("#exceptionProvince").val(1);//1 is can to submit
    	   }
       }else{
    	   $("#errorSFInfo").hide();
    	   $("#exceptionProvince").val(1);//1 is can to submit
       }
    },

    countShipFee : function(){//get the province to count the ship fee
    	//get the all items weight and qty
    	var itemIdArray = Array();
    	var quantityArray = Array();
    	var weightArray = Array();
    	var shipRuleArray = Array();
        var totalArray = Array();
        var itemId = $("input[name='itemId[]']");
        var quantity = $("input[name='quantity[]']");
        var weight = $("input[name='weight[]']");
        var total = $("input[name='total[]']");
        var shipRule = $("input[name='shipRule[]']");//count the weight for item, if the item shipRule=3, then weight nou to count
        $.each(itemId, function(i, obj){
            itemIdArray[itemIdArray.length] = obj.value;
        });
        $.each(quantity, function(i, obj){
        	quantityArray[quantityArray.length] = obj.value;
        });
        $.each(weight, function(i, obj){
        	weightArray[weightArray.length] = obj.value;
        });
        $.each(total, function(i, obj){
        	totalArray[totalArray.length] = obj.value;
        });
        $.each(shipRule, function(i, obj){
        	shipRuleArray[shipRuleArray.length] = obj.value;
        });
        var itemIds = itemIdArray.join(",");
        var quantitys = quantityArray.join(",");
        var weights = weightArray.join(",");
        var totals = totalArray.join(",");
        var shipRules = shipRuleArray.join(",");
        var shipRule = $("#hiddenShipRule").val();//count shipping fee , 1==fixed , 2==weight
        var addressId = $("input[name='address']:checked").val();//current select address id
        var shipType = $("input[name='deliveryRadio']:checked").val();//current select delivery company
    	//alert(shipRule+" == "+addressId+" == "+shipType);
        //ajax judge current province if is xinjiang or xizang then SF shipping not to select
        $.ajax({
            type: 'post',
            url: '/a/countShipFee',
            data: {"itemIds":itemIds, "quantitys":quantitys, "weights":weights, "shipRule":shipRule, "addressId":addressId, "shipType":shipType, "shipRules":shipRules, "totals":totals},
            dataType: "json",
            async: false,  //false is synchronization , true is asynchronism
            success: function(data){
                result = data;
                $("#shipPriceNormal").html(UtilFunction.formatFloat(Number(result.normal), 2));
                $("#shipPriceSF").html(UtilFunction.formatFloat(Number(result.SF), 2));
                $("#shipPriceEMS").html(UtilFunction.formatFloat(Number(result.EMS), 2));
                $("#hiddenShipPriceNormal").val(result.normal);
                $("#hiddenShipPriceSF").val(result.SF);
                $("#hiddenShipPriceEMS").val(result.EMS);
                
                //if init is normal delivery mode
                var item = $("input[name='deliveryRadio']:checked").val();
                if( item == 1 ){//normal delivery
                	$("#shippingChargesLabel").html( UtilFunction.formatFloat(Number(result.normal), 2) );
                    $("#shippingCharges").val(result.normal);
                    $("#reshippingChargesLabel").html( UtilFunction.formatFloat(Number(result.normal), 2) );
                    CheckOut.countAllTotalPrice();
                }
                
            },
            error: function(){
                result = false;
            }
       });
    },

    addressModify : function(){//click the modify link
        $("#addressModify").hide();
        $("#addressComplete").show();
        $("#addressInfo").show();
        $("#currentUseAddress").hide();
        $("#useAddressBtn").show();
        var addressNum = CheckOut.validateAddressNum();
        if(Number(addressNum) >= 5){
        	$("#addAddressBtn").hide();
        }else{
        	$("#addAddressBtn").show();
        }
    },

    addressComplete : function(){//click the complete link
        CheckOut.useTheAddressInfo();
        $("#addressModify").show();
        $("#addressComplete").hide();
        $("#addressInfo").hide();
        $("#currentUseAddress").show();
        $("#useAddressBtn").hide();
        $("#addAddressBtn").hide();
        $("#addAddress").hide();
    },

    cancelAdd : function(){//the cancel button
        $("#addAddress").hide();
    },

    /**
     * shipping way part
     */
    shippingModify : function(){//the shipping modify link
        $("#collegesDeliver").show();
        $("#normalDeliver").show();
        $("#sfDeliver").show();
        $("#EMSDeliver").show();
        $("#shippingModify").hide();
        $("#shippingComplete").show();
    },

    shippingComplete : function(){//the shipping complete link
        $("#normalDeliver").hide();
        $("#sfDeliver").hide();
        $("#EMSDeliver").hide();
        $("#shippingModify").show();
        $("#shippingComplete").hide();
        CheckOut.saveDelivery();
    },

    saveDelivery : function(){//click the radio of delivery way
        $("#errorSFInfo").hide();
        CheckOut.validateProvinceForSFShipType();//validate province if can shipping
    	var item = $("input[name='deliveryRadio']:checked").val();
    	var shipPriceNormal = Number($("#hiddenShipPriceNormal").val());
    	var shipPriceSF = Number($("#hiddenShipPriceSF").val());
    	var shipPriceEMS = Number($("#hiddenShipPriceEMS").val());
    	if(item == 3){//colleges deliver
            $("#collegesDeliver").show();
            $("#normalDeliver").hide();
            $("#sfDeliver").hide();
            $("#EMSDeliver").hide();
            $("#selectColleges").show();
            $("#selectTime").show();
            $("#collegesPayment").show();
            $("#alipayPayment").hide();
            $("#bankPayment").hide();
            $("#paymentModify").hide();
            $("#paymentComplete").show();
            $("input[name='radioPay'][value='1']").attr("checked",true);
            $("#shippingCharges").val("0.00");
            $("#shippingChargesLabel").html("0.00");
            $("#reshippingChargesLabel").html("0.00");
        }else if(item == 1){//normal deliver
            $("#collegesDeliver").hide();
            $("#normalDeliver").show();
            $("#sfDeliver").hide();
            $("#EMSDeliver").hide();
            $("#selectColleges").hide();
            $("#selectTime").hide();
            $("#collegesPayment").hide();
            $("#alipayPayment").show();
            $("#bankPayment").show();
            $("#paymentModify").hide();
            $("#paymentComplete").show();
            $("input[name='radioPay'][value='3']").attr("checked",true);
            $("#shippingCharges").val(shipPriceNormal);
            $("#shippingChargesLabel").html(UtilFunction.formatFloat(shipPriceNormal, 2));
            $("#reshippingChargesLabel").html(UtilFunction.formatFloat(shipPriceNormal, 2));
        }else if(item == 5){//sf deliver
            $("#collegesDeliver").hide();
            $("#normalDeliver").hide();
            $("#sfDeliver").show();
            $("#EMSDeliver").hide();
            $("#selectColleges").hide();
            $("#selectTime").hide();
            $("#collegesPayment").hide();
            $("#alipayPayment").show();
            $("#bankPayment").show();
            $("#paymentModify").hide();
            $("#paymentComplete").show();
            $("input[name='radioPay'][value='3']").attr("checked",true);
            $("#shippingCharges").val(shipPriceSF);
            $("#shippingChargesLabel").html(UtilFunction.formatFloat(shipPriceSF, 2));
            $("#reshippingChargesLabel").html(UtilFunction.formatFloat(shipPriceSF, 2));

        }else if(item == 2){//EMS deliver
            $("#collegesDeliver").hide();
            $("#normalDeliver").hide();
            $("#sfDeliver").hide();
            $("#EMSDeliver").show();
            $("#selectColleges").hide();
            $("#selectTime").hide();
            $("#collegesPayment").hide();
            $("#alipayPayment").show();
            $("#bankPayment").show();
            $("#paymentModify").hide();
            $("#paymentComplete").show();
            $("input[name='radioPay'][value='3']").attr("checked",true);
            $("#shippingCharges").val(shipPriceEMS);
            $("#shippingChargesLabel").html(UtilFunction.formatFloat(shipPriceEMS, 2));
            $("#reshippingChargesLabel").html(UtilFunction.formatFloat(shipPriceEMS, 2));
        }
        $("#shippingModify").show();
        $("#shippingComplete").hide();
        CheckOut.countAllTotalPrice();
    },

    /**
     * select campuses
     */
    showAllCampuses : function(){//show province and school info
    	$("#allSchool").show();
    },

    closeBtn : function(){//hide province and school info
        $("#allSchool").hide();
    },

    showArea : function(id){//get the province generate the school info
    	var result;
    	$.ajax({
		     type: 'post',
		     url: '/a/generateCampuses',
		     data: {"areaDictId" : id},
		     //dataType: "json",
		     async: false,  //false is synchronization , true is asynchronism
		     success: function(data){
		    	 //result = data;
		    	 $("#allCampuses").html(data);
		     },
		     error: function(){
		    	 result = false;
		     }
	    });
    },
    
    showArea1 : function(id,noInOrder){//get the province generate the school info
    	var result;
    	$.ajax({
		     type: 'post',
		     url: '/a/generateCampuses',
		     data: {"areaDictId" : id,"noInOrder":noInOrder},
		     //dataType: "json",
		     async: false,  //false is synchronization , true is asynchronism
		     success: function(data){
		    	 //result = data;
		    	 $("#allCampuses").html(data);
		     },
		     error: function(){
		    	 result = false;
		     }
	    });
    },

    viewArea : function(areaName, id){//set the value to textbox and hidden box , show campuses ambassador if it exist else do not show
    	$("#campusesName").val(areaName);
    	$("#allSchool").hide();
    	$("#campusesId").val(id);
    	$.ajax({
		     type: 'post',
		     url: '/a/generateAmbassador',
		     data: {"campusesId" : id},
		     //dataType: "json",
		     async: false,  //false is synchronization , true is asynchronism
		     success: function(data){
		    	 //result = data;
		    	 $("#selectDeputy").html(data);
		     },
		     error: function(){
		    	 result = false;
		     }
	    });
    },

    /**
     * payment way part
     */
    paymentModify : function(){//the modify link
        $("#paymentModify").hide();
        $("#paymentComplete").show();
        var item = $("input[name='deliveryRadio']:checked").val();
        if(item == 3){//this is colleges payment
            $("#collegesPayment").show();
            $("#alipayPayment").hide();
            $("#bankPayment").hide();
        }else{
            $("#collegesPayment").hide();
            $("#alipayPayment").show();
            $("#bankPayment").show();
        }
    },

    paymentComplete : function(){//the complete link
        $("#paymentModify").show();
        $("#paymentComplete").hide();
        CheckOut.savePay();
    },

    showCollegesPayment : function(){//only show colleges payment
        $("#collegesPayment").show();
        $("#alipayPayment").hide();
        $("#bankPayment").hide();
    },

    showAlipayPayment : function(){//only show alipay payment
        $("#collegesPayment").hide();
        $("#alipayPayment").show();
        $("#bankPayment").hide();
    },

    showBankPayment : function(){//only show bank payment
        $("#collegesPayment").hide();
        $("#alipayPayment").hide();
        $("#bankPayment").show();
    },

	savePay : function(){//click the radio the show current select
        var item = $("input[name='radioPay']:checked").val();
        if(item == 1){//colleges payment free shipping
            CheckOut.showCollegesPayment();
        }else if(item == 3){//alipay payment
            CheckOut.showAlipayPayment();
        }else if(item == 11){//bank payment
            CheckOut.showBankPayment();
        }
        $("#paymentModify").show();
        $("#paymentComplete").hide();
    },

    /**
     * use coupon part begin
     * param:
     * 1.param="input" 说明此code是用户输入的
     * 2.param=code代码 即param!="input" 说明此code是自动打折的code 循环调用打折
     */
    
    /*
     * 自动打折
     * codes = "XXX,XXX,XXX" split by ','
     */
    autoPromotion : function(codes){
    	if(codes != ""){
    		var codeArray = new Array();
        	codeArray=codes.split(",");
        	for(var i = 0; i < codeArray.length; i++){
        		var code = codeArray[i];
        		CheckOut.useCoupon(code);
        	}
    	}
    },
    
	useCoupon : function(param){ //validate the coupon is not empty
    	 if(param == "input"){
			 $("#applyCouponBtn").attr("disabled", true);//init the button is can click
			 couponCode = $("#coupon").val();
			 if($.trim(couponCode) == ""){
				 var emptyInfo = $("#errorEmptyCoupon").val();
				 $("#errorInfoCouponTitle").html("");
				 $("#errorInfoCouponCode").html("");
				 $("#errorInfoCouponStatus").html("");
				 $("#errorInfoCouponTitle").html(emptyInfo);
			 }else{
			     $("#useCouponBtn").attr("disabled", true);//when the discount info already generate then the button can be clicked
				 CheckOut.applyCoupon(couponCode, "input");//应用code
				 $("#useCouponBtn").attr("disabled", false);
				 $("#coupon").val("");//clear the textBox
			 }
			 $("#applyCouponBtn").attr("disabled", false);
    	 }else{//当前为自动打折的code
    		 CheckOut.applyCoupon(param, "auto");//应用code
    	 }
    	 
		 CheckOut.generatePriceInfo();
		 //算完promotion后再计算是否符合满多少钱免运费的promotion
		 CheckOut.countShipFee();  
	},

	/*
	 * type=input：用户输入 
	 * type=auto：系统自动打折 
	 */
	applyCoupon : function(couponCode, type){//before use the coupon to get the coupon param , and call the method to generate the html code of discount and dealPrice info
          var itemIdArray = Array();
          var quantityArray = Array();
          var salePriceArray = Array();
          var totalPriceArray = Array();
          var itemId = $("input[name='itemId[]']");
          var quantity = $("input[name='quantity[]']");
          var salePrice = $("input[name='salePrice[]']");
          var totalPrice = $("input[name='total[]']");
          $.each(itemId, function(i, obj){
              itemIdArray[itemIdArray.length] = obj.value;
          });
          $.each(quantity, function(i, obj){
              quantityArray[quantityArray.length] = obj.value;
          });
          $.each(salePrice, function(i, obj){
              salePriceArray[salePriceArray.length] = obj.value;
          });
          $.each(totalPrice, function(i, obj){
              totalPriceArray[totalPriceArray.length] = obj.value;
          });
          var itemIds = itemIdArray.join(",");
          var quantitys = quantityArray.join(",");
          var salePrices = salePriceArray.join(",");
          var totalPrices = totalPriceArray.join(",");
          var merchandiseTotal = $("#merchandiseTotal").val();
          var discount = $("#discount").val();
          var couponTotal = merchandiseTotal - discount;
          var usedPromotionValue = CheckOut.usedPromotion.length > 0 ? false : true;//if user first use coupon then return true
          var stackableValue = CheckOut.stackable == 1 ? true : false;//if this coupon can re-use then return true//init is true
          //validate the code if already is used
          if(!CheckOut.isValidateCouponCode(couponCode)){//this coupon already be used
              if(type == "input"){//用户输入的code
	        	  //$("#errorCouponCodeAlreadyUse").show();
	              var couponTitle = $("#errorCouponTitle").val();
	              var couponCode = $("#coupon").val();
	              var statusInfo = $("#errorCouponAlreadyUse").val();
	              $("#errorInfoCouponTitle").html("");
	              $("#errorInfoCouponCode").html("");
	              $("#errorInfoCouponStatus").html("");
	              $("#errorInfoCouponTitle").html(couponTitle);
	              $("#errorInfoCouponCode").html(couponCode);
	              $("#errorInfoCouponStatus").html(statusInfo);
              }
              return ;
          }
          //get the coupon info
          var couponInfo = CheckOut.countCoupon(couponTotal, couponCode, itemIds, quantitys, salePrices, usedPromotionValue, stackableValue, totalPrices);
          //coupon info
          var couponTitle = $("#errorCouponTitle").val();
          var couponCode = $("#coupon").val();
          var statusInfo;
          $("#errorInfoCouponTitle").html("");
          $("#errorInfoCouponCode").html("");
          $("#errorInfoCouponStatus").html("");
          
          if(couponInfo == false){//this coupon code can not used or the ajax request lose
        	  if(type == "input"){//用户输入的code
	              $("#useCouponBtn").attr("disabled", false);
	              //$("#errorInfoCouponCode").show();
	              statusInfo = $("#errorCouponFailed").val();
	              $("#errorInfoCouponTitle").html(couponTitle);
	              $("#errorInfoCouponCode").html(couponCode);
	              $("#errorInfoCouponStatus").html(statusInfo);
        	  }
          }else{
              statusInfo = $("#errorCouponSuccess").val();
              if(type == "input"){//用户输入的code
	              $("#errorInfoCouponTitle").html(couponTitle);
	              $("#errorInfoCouponCode").html(couponCode);
	              $("#errorInfoCouponStatus").html(statusInfo);
              }
              //generate the html code of coupon info
              isValidate = CheckOut.generateCouponInfo(couponInfo, type);
              if(isValidate){//when the price < 0 , then return false
                  //$("#errorInfoCouponCode").hide();
              }else{//todo//when price < 0
                  //$("#errorInfoCouponCode").show();
              }
              //count the price after use coupon
              //CheckOut.countTax();
          }
      },

	countCoupon : function(couponTotal, couponCode, itemIds, quantitys, salePrices, usedPromotion, stackable, totalPrices){ //use the ajax function to count the discount info
	   //ajax function to use the coupon code
	   $.ajax({
	       type: 'post',
		   url: '/a/getCouponInfo',
		   data: {"couponTotal":couponTotal, "couponCode":couponCode, "itemIds":itemIds, "quantitys":quantitys, "salePrices":salePrices, "usedPromotion":usedPromotion, "stackable":stackable, "totalPrices":totalPrices},
		   dataType: "json",
		   async: false,  //false is synchronization , true is asynchronism
		   success: function(data){
		       result = data;
		   },
		   error: function(){//if error return false and set the button can be clicked
	               result = false;
	           }
	   });
	   return result;
	},

	generateCouponInfo : function(couponInfo, type){ //get the promotion price info to generate the html code
           if(!CheckOut.isValidateCouponCode(couponInfo.couponCode)){//this coupon already be used
        	   if(type == "input"){//用户输入的code
	        	   //$("#errorCouponCodeAlreadyUse").show();
	               var couponTitle = $("#errorCouponTitle").val();
	               var couponCode = $("#coupon").val();
	               var statusInfo = $("#errorCouponAlreadyUse").val();
	               $("#errorInfoCouponTitle").html("");
	               $("#errorInfoCouponCode").html("");
	               $("#errorInfoCouponStatus").html("");
	               $("#errorInfoCouponTitle").html(couponTitle);
	               $("#errorInfoCouponCode").html(couponCode);
	               $("#errorInfoCouponStatus").html(statusInfo);
        	   }
               return false;
           }
           $.each(couponInfo, function(i, obj){
               if(i == "itemsDiscount"){
                   $.each(obj, function(itemId, itemDiscount){
                       //set the total price
                       oldItemTotalPrice = Number($("#hiddenTotalPrice_" + itemId).val());
                       newItemTotalPrice = oldItemTotalPrice - Number(itemDiscount.discountTotal);
                       if(newItemTotalPrice <= 0){//if the price < 0 then return false
                           return false;//this coupon is not be used
                       }
                       oldDealPrice = Number($("#hiddenDealPrice_" + itemId).val());
                       qty = Number($("#hiddenquantity_" + itemId).val());//get the item quantity
                       newDealPrice = oldDealPrice - Number(itemDiscount.discountTotal) / qty;
                       $("#hiddenDealPrice_" + itemId).val(newDealPrice);
                       $("#totalPrice_" + itemId).html(UtilFunction.formatFloat(newItemTotalPrice, 2));
                       $("#retotalPrice_" + itemId).html(UtilFunction.formatFloat(newItemTotalPrice, 2));
                       $("#hiddenTotalPrice_" + itemId).val(newItemTotalPrice);
                       //set the discount price
                       oldDiscount = Number($("#hiddenDiscountPrice_" + itemId).val());
                       newDiscount = oldDiscount + Number(itemDiscount.discountTotal);
                       if(newDiscount == 0){//if is free shipping,Discount equal 0,then do not show the discount info
                           $("#discountInfo_" + itemId).hide();//if the item discount is 0 then hide the discount info
                       }else{
                           $("#discountInfo_" + itemId).show();//if the item have discount then show the discount div to show the info
                       }

                       $("#hiddenDiscountPrice_" + itemId).val(newDiscount);//set the hidden value for submit of the form
                       $("#discountPrice_" + itemId).html(UtilFunction.formatFloat(newDiscount, 2));//show the discount price info
                       $("#rediscountPrice_" + itemId).html(UtilFunction.formatFloat(newDiscount, 2));//show the discount price info
                       //set the if this item can free shipping
                       oldisFreeShipping = Number($("#hiddenIsFreeShipping_" + itemId).val());
                       newisFreeShipping = oldisFreeShipping + Number(itemDiscount.isFreeShipping);
                       $("#hiddenIsFreeShipping_" + itemId).val(newisFreeShipping);
                   });
               }
           });
           oldDiscountAllTotal = Number($("#discount").val());
           newDiscountAllTotal = Number(couponInfo.discountAllTotal) + oldDiscountAllTotal;
           oldDiscountAllTotal = $("#discountLabel").html(UtilFunction.formatFloat(newDiscountAllTotal, 2));
           oldDiscountAllTotal = $("#rediscountLabel").html(UtilFunction.formatFloat(newDiscountAllTotal, 2));
           oldDiscountAllTotal = $("#discount").val(newDiscountAllTotal);
           CheckOut.stackable = couponInfo.stackable;
           //if user already use this coupon code then the coupon can not to re-use
           CheckOut.generateCouponCode(couponInfo.promotionId, couponInfo.title, couponInfo.couponCode, type);
           return true;
       },

       generateCouponCode : function(promotionId, couponTitle, couponCode, type){
           info = "";
           //var couponTitle = $("#errorCouponTitle").val();
           //var statusInfo = $("#errorCouponAlreadyUse").val();
           //if(CheckOut.usedPromotion.length == 0){//first use coupon , length is 0
               //CheckOut.usedPromotion[CheckOut.usedPromotion.length] = promotionId;//save the coupon id in array
               //CheckOut.usedPromotionCode[CheckOut.usedPromotionCode.length] = couponCode;//save the coupon code in array
               //info += '<div>'+ couponTitle + ' ' + couponCode + ' ' + statusInfo + '</div>';
           //}else{//judge the coupon if already be used
               //isValidateCode = true;
               //$.each(CheckOut.usedPromotionCode, function(i, obj){
                   //if(obj == couponCode){
                       //isValidateCode = false;
                   //}
                   //info += '<div>' + couponTitle + ' ' +  + obj + ' ' + statusInfo + '</div>';
               //});
               if(CheckOut.isValidateCouponCode(couponCode)){//this coupon can be used
                   CheckOut.usedPromotion[CheckOut.usedPromotion.length] = promotionId;
                   CheckOut.usedPromotionCode[CheckOut.usedPromotionCode.length] = couponCode;
                   //显示用户promotion信息
                   $("#showCouponCode").show();
                   $("#reshowCouponCode").show();
                   info += ' <div style="margin-left:100px;margin-top:5px;">' + couponTitle +  ' - ' + couponCode + ' </div> ';
               }
           //}

		       $("#showCouponCode").append(info);
	           $("#reshowCouponCode").append(info);

           
       },

       isValidateCouponCode : function(couponCode){//judge the coupon if already be used
           isValidateCode = true;
           if(CheckOut.usedPromotionCode.length == 0){
               return isValidateCode;
           }else{
               $.each(CheckOut.usedPromotionCode, function(i, obj){
                   if(obj == couponCode){
                       isValidateCode = false;
                   }
               });
           }
           return isValidateCode;
       },

//       countTax : function(){
//           var itemIdArray = Array();
//           var totalArray = Array();
//           var cityName = $.trim($("#shipCity").val());
//           var itemId = $("input[name='itemId[]']");
//           var total = $("input[name='total[]']");
//           var stateName = $("#shipStateSelect").val();
//           $.each(itemId, function(i, obj){
//               itemIdArray[itemIdArray.length] = obj.value;
//           });
//           $.each(total, function(i, obj){
//               totalArray[totalArray.length] = obj.value;
//           });
//           itemIds = itemIdArray.join(",");
//           totals = totalArray.join(",");
//           $.ajax({
//               type: 'post',
//               url: '/a/countTax',
//               data: {"itemIds" : itemIds , "cityName" : cityName , "totals" : totals , "stateName" : stateName},
//               //dataType: "json",
//               async: false,
//               success: function(data){
//                   data = Number(data);
//                   $("#estimatedTaxLabel").html(UtilFunction.formatFloat(data, 2));
//                   $("#estimatedTax").val(data);
//                   shippingFee = $("#shippingCharges").val();
//                   var merchandiseTotal = $("#merchandiseTotal").val();
//                   //estimatedTax = $("#estimatedTax").val();
//                   var estimatedTax = data;
//                   var discount = $("#discount").val();
//                   total = Number(merchandiseTotal) + Number(shippingFee) + Number(estimatedTax) - Number(discount);
//                   $("#allTotalLabel").html(UtilFunction.formatFloat(total, 2));
//                   $("#allTotal").val(UtilFunction.formatFloat(total, 2));
//               },
//               error: function(){
//                   result = false;
//               }
//           });
//       },

       generatePriceInfo : function(){
           //var shippingFee = 1.11;
//           var value = $("input[name='checkShip']:checked").val();
//           var shipFeeResult = CheckOut.countShippingFee(value);
//           var shipFee = shipFeeResult.shippingFee;
//           var shippingFee = UtilFunction.formatFloat(shipFee.shippingPrice, 2);
//           $("#rShippingPrice").html(UtilFunction.formatFloat(shipFee.shippingPrice, 2));//!!!!!!
//           $("#shippingFee").html(shippingFee);//!!!!!!!!!!!!???
           //$("#shippingChargesLabel").html(shippingFee);
           //$("#shippingCharges").val(shippingFee);
           //if discountLabel do not have value,then init discountPrice equal $0
           //如果折扣出现负数显示为0
    	   var discountPrice = Number($("#discount").val());
           if(discountPrice < 0){
        	   $("#discountLabel").html("0.00");
               $("#rediscountLabel").html("0.00");
               $("#discount").val("0.00");
           }
           //shippingFee = $("#shippingCharges").val();
//           var merchandiseTotal = $("#merchandiseTotal").val();
//           var estimatedTax = $("#estimatedTax").val();
//           var discount = $("#discount").val();
//           var total = Number(merchandiseTotal) + Number(shippingFee) + Number(estimatedTax) - Number(discount);
//           $("#allTotalLabel").html(UtilFunction.formatFloat(total, 2));
//           $("#allTotal").val(UtilFunction.formatFloat(total, 2));
           CheckOut.countAllTotalPrice();
       },

       /**
        * include Merchandise Total  , Shipping Charges , Estimated Tax , Discount
        */
       countAllTotalPrice : function(){
    	   var merchandiseTotal = Number($("#merchandiseTotal").val());
    	   var shippingCharges = Number($("#shippingCharges").val());
    	   var discount = Number($("#discount").val());
    	   var estimatedTax = Number($("#estimatedTax").val());
    	   var allTotal = merchandiseTotal + shippingCharges + estimatedTax - discount;
    	   $("#allTotalLabel").html(UtilFunction.formatFloat(allTotal, 2));
    	   $("#reallTotalLabel").html(UtilFunction.formatFloat(allTotal, 2));
    	   $("#allTotal").val(allTotal);
       },
       
       //promotion part end//
       

       /**
        * review order part
        */
       reviewOrder : function(){ //set the value in order review div
    	   var submit = true;
    	   var existAddress = $("#existAddress").val();
    	   var address = $("input[name='address']:checked").val();
    	   var deliveryRadio = $("input[name='deliveryRadio']:checked").val();
    	   var campusesName = $("#campusesName").val();
    	   var invoiceTitle = $("#invoiceTitle").val();
    	   var allTotal = $("#allTotal").val();
    	   if(Number(allTotal) <= 0){
    		   alert("价格有误不能提交订单，请您确认");
    		   submit = false;
    		   return false;
    	   }
    	   if(existAddress == 0){
    		   var errorAddressEmpty = $("#errorAddressEmpty").val();
    		   alert(errorAddressEmpty);//prompt info
    		   submit = false;
    		   return false;
    	   }
    	   if(deliveryRadio == 3 && ValidationUtil.isBlank(campusesName)){
    		   var errorCampuses = $("#errorCampusesEmpty").val();
    		   alert(errorCampuses);//prompt info
    		   submit = false;
    		   return false;
    	   }
    	   if(ValidationUtil.isBlank(invoiceTitle)){
    		   var errorInvoiceEmpty = $("#errorInvoiceEmpty").val();
    		   alert(errorInvoiceEmpty);//prompt info
    		   submit = false;
    		   return false;
    	   }
    	   if($("#exceptionProvince").val() == 0){
    		   var errorShipRule = $("#errorShipRule").val();
    		   alert(errorShipRule);
    		   submit = false;
    		   return false;
    	   }
    	   if(!submit){
    		   return;
    	   }
    	   CheckOut.generateReviewTaxInfo();
    	   CheckOut.generateReviewAddressInfo();
    	   CheckOut.generateReviewShippingInfo();
    	   CheckOut.generateReviewPaymentInfo();
    	   CheckOut.generateReviewInvoiceInfo();
    	   CheckOut.generateSpecialInfo();
    	   $("#orderInfo").hide();
    	   $("#orderReview").show();
	},
	
	generateReviewTaxInfo : function(){
	    var itemIdArray = Array();
	    var itemId = $("input[name='itemId[]']");
	    $.each(itemId, function(i, obj){
	        itemIdArray[itemIdArray.length] = obj.value;
	    });
	    for(var i = 0; i < itemIdArray.length; i++){
	    	var id = itemIdArray[i];
	    	var value = $("input[name='invoiceCheck_"+id+"']:checked").val();
	    	var taxRule = $("#taxRule_" + id).val();
	    	var hiddenTaxPrice = Number($("#hiddenTaxPrice_" + id).val());
	    	if(taxRule == "optional"){
		    	if(value == 1){//use invoice
		    		$("#reinvoiceInfo_" + id).html("需要");
		    		$("#retaxPrice_" + id).html(UtilFunction.formatFloat(hiddenTaxPrice, 2));
		    		$("#reprotection_" + id).html("不需发票");
		    	}else{
		    		$("#reinvoiceInfo_" + id).html("不需要");
		    		$("#retaxPrice_" + id).html("0.00");
		    		$("#reprotection_" + id).html("不需发票");
		    	}
	    	}else if(taxRule == "compel"){
	    		$("#reinvoiceInfo_" + id).html("需要");
	    		$("#retaxPrice_" + id).html(UtilFunction.formatFloat(hiddenTaxPrice, 2));
	    		$("#reprotection_" + id).html("需发票");
	    	}else{
	    		$("#reinvoiceInfo_" + id).html("不需要");
	    		$("#retaxPrice_" + id).html("0.00");
	    		$("#reprotection_" + id).html("不需发票");
	    	}
	    }
	},

	generateReviewAddressInfo : function(){
		var addressId = $("input[name='address']:checked").val();
		var province = $("#province_" + addressId).html();
		var cityName = $("#cityName_" + addressId).html();
		var districtName = $("#districtName_" + addressId).html();
		var otherAddress = $("#otherAddress_" + addressId).html();
		var userName = $("#userName_" + addressId).html();
		var userName = $("#userName_" + addressId).html();
		var mobileTelephone = $("#mobileTelephone_" + addressId).html();
		var phone = $("#phone_" + addressId).val();
		var email = $("#email_" + addressId).val();
		var html = province + "  " + cityName + "  " + districtName + "  " + otherAddress;
		html += " ( 收货人： " + userName + ",  " + mobileTelephone + ", " + phone + " ) ";
		$("#readdress").html(html);
	},

	generateReviewShippingInfo : function(){
		var deliveryType = $("input[name='deliveryRadio']:checked").val();
		$("#redelivery").html("");
		$("#recampuses").html("");
		$("#recampusesAgent").html("");
		$("#redeliveryTime").html("");
		if(deliveryType == 3){//campuses type
			var teamNameId = $("input[name='userId']:checked").val();//teamNameId is user table id
			var deliveryDate = $("input[name='deliveryDate']:checked").val();//teamNameId is user table id
			var teamName = $("#teamName_" + teamNameId).val();
			var recampuses = $("#campusesName").val();
			$("#redelivery").html("高校货到付款");
			$("#recampuses").html(recampuses);
			$("#recampusesAgent").html(teamName);
			if(deliveryDate == 1){
				$("#redeliveryTime").html("上午");
			}else if(deliveryDate == 2){
				$("#redeliveryTime").html("下午");
			}else if(deliveryDate == 3){
				$("#redeliveryTime").html("晚上");
			}else if(deliveryDate == 4){
				$("#redeliveryTime").html("不限");
			}
			$("#recampusesInfo").show();
		}else if(deliveryType == 1){//normal
			$("#recampusesInfo").hide();
			$("#redelivery").html("普通快递");
		}else if(deliveryType == 5){//SF
			$("#recampusesInfo").hide();
			$("#redelivery").html("顺风快递");
		}else if(deliveryType == 2){//EMS
			$("#recampusesInfo").hide();
			$("#redelivery").html("EMS");
		}

	},

	generateReviewPaymentInfo : function(){
		var paymentType;
		var radioPay = $("input[name='radioPay']:checked").val();
		if(radioPay == 1){//campuses type
			paymentType = "高校货到付款";
		}else if(radioPay == 3){
			paymentType = "支付宝在线支付";
		}else if(radioPay == 11){
			paymentType = "银行付款（工行）";
		}
		$("#repayment").html(paymentType);
	},

	generateReviewInvoiceInfo : function(){
		var invoiceInfo = $("#invoiceTitle").val();
		$("#reinvoiceInfo").html(invoiceInfo);
	},

	generateSpecialInfo : function(){
		var specialInfo = $.trim($("#textarea").val());
		if(ValidationUtil.isBlank(specialInfo)){
			$("#reInstruction").html("无特殊要求");
		}else{
			$("#reInstruction").html(specialInfo);
		}
	},

	/*
	* all validate to submit
	*/
	vChequeRule : function(){//use in the checkout page onload
	    var tag = false;//false id all without invoice , true is use invoice then textbox show info
	    var itemIdArray = Array();
	    var itemId = $("input[name='itemId[]']");
	    $.each(itemId, function(i, obj){
	        itemIdArray[itemIdArray.length] = obj.value;
	    });
	    for(var i = 0; i < itemIdArray.length; i++){
			var id = itemIdArray[i];
			var value = $("input[name='invoiceCheck_"+id+"']:checked").val();
			if(value == 1){//at least have one use invoice
				tag = true;
			}
	    }
        if(tag){//use invoice , validete the invoice textbox
           	if(CheckOut.vInvoiceTextbox()){
           		return true;
           	}else{
           		return false;
           	}
        }else{
        	return false;
        }
	},

	vInvoiceTextbox : function(){
		var invoiceTitle = $.trim($("#invoiceTitle").val());
		if(ValidationUtil.isBlank(invoiceTitle)){
			return false;
		}else{
			return true;
		}
	},

	placeOrder : function(){
		var result;
        var itemIdArray = Array();
        var quantityArray = Array();
        var salePriceArray = Array();
        $("#placeOrderButton").attr("disabled", true);//set the button is disable
        var itemId = $("input[name='itemId[]']");
        var quantity = $("input[name='quantity[]']");
        var salePrice = $("input[name='salePrice[]']");
        $.each(itemId, function(i, obj){
            itemIdArray[itemIdArray.length] = obj.value;
        });
        $.each(quantity, function(i, obj){
        	quantityArray[quantityArray.length] = obj.value;
        });
        $.each(salePrice, function(i, obj){
        	salePriceArray[salePriceArray.length] = obj.value;
        });
        var itemIds = itemIdArray.join(",");
        var quantitys = quantityArray.join(",");
        var salePrices = salePriceArray.join(",");
        result = CheckOut.generateCheckOutHtml(itemIds, quantitys);

	    //ajax验证每件产品的价钱是否与product_items表相同
//        var pricePrompt = CheckOut.validateItemSalePrice(itemIds, salePrices); 
//	    if( pricePrompt != "" ){
//	    	$("#pricePrompt").show();
//            $("#pricePromptInfo").empty();
//            $("#pricePromptInfo").html(pricePrompt);
//		    return;
//	    }
 	   
        if(result.length != 0){//if the item is sell out
            $("#checkcurrent").show();
            $("#currentinfo").empty();
            $("#currentinfo").html(result);
            return;
        }else{
            usedPromotionIds = CheckOut.usedPromotion.join(',');
            usedPromotionCodes = CheckOut.usedPromotionCode.join(',');
            $("#hiddenUsedPromotion").val(CheckOut.usedPromotion);
            $("#hiddenUsedPromotionCode").val(CheckOut.usedPromotionCode);
            $("#placeOrderButton").attr("disabled", true);
            $('#checkOutForm').attr("action", "/o/placeOrder");
            $("#checkOutForm").submit();//submit
        }
	},

	//验证每件产品的价钱
	validateItemSalePrice : function(itemIds, salePrices){
		var result = "";
        $.ajax({
            type: 'post',
            url: '/a/getitemsalepriceforcheckout',
            dataType: "html",
            data: {"itemIds" : itemIds , "salePrices" : salePrices},
            async: false,
            success: function(responseText){
                result = responseText;
            },
            error: function(){
                result = "";
            }
        });
        return result;
	},
	
	/*
	 * if stock out then prompt user
	 */
    generateCheckOutHtml : function(itemIds, quantitys){
		var result = "";
        $.ajax({
            type: 'post',
            url: '/a/getItemQtyInfoForCheckOut',
            dataType: "html",
            data: {"itemIds" : itemIds , "quantitys" : quantitys},
            async: false,
            success: function(responseText){
                result = responseText;
            },
            error: function(){
                result = "";
            }
        });
        return result;
    }


}



//*******************************************************************************
//For area
var AreaDict = {
        changeArea : function(level){
            var parentId;
            if(level==2){
                parentId = $('#province').val();
            }else if(level==3){
                parentId = $('#city').val();
            }
          //  alert(parentId);
            var defaultOption = $('#defaultOption').val();

            $.ajax({
                 type: 'post',
                 dataType: "json",
                 url: '/u/getareadict',
                 data: {"parentId" : parentId, "level":level},
                 async: false,  //false is synchronization , true is asynchronism
                 success: function(data){

                     if(data.length){
                            var i = 0;
                            var defaultOpt = '<option value="">'+defaultOption+'</option>';
                            var html = defaultOpt;

                            var dict;
                            for(i;i<data.length;i++){

                                dict = '<option value="'+data[i].id+'">'+data[i].title+'</option>';
                                html += dict;
                            }

                            if(level==2){
                                $('#city').html(html);
                                $('#county').html(defaultOpt);
                                $('#city').show();
                                $('#county').hide();

                            } else if(level==3) {
                                $('#county').html(html);
                                $('#county').show();
                            }
                        } else {
                            if(level==2){
                                $('#city').html(defaultOpt);
                                $('#county').html(defaultOpt);
                                $('#city').hide();
                                $('#county').hide();

                            } else if(level==3) {
                                $('#county').html(defaultOpt);
                                $('#county').hide();
                            }
                        }
                 },
                 error: function(){

                      result = false;
                    }
                });
        },
        validateAreaDict : function(){
            var result = false;
            var province = $('#province').val();
            var city = $('#city').val();
            var county = $('#county').val();
            if(!province || !city || !county){
                var errorArea = $('#errorAreaEmpty').val();
                $('#errorAreaDict').html(errorArea);

            } else {
                $('#errorAreaDict').html('');
                result = true;
            }
            return result;
        }
}

//************************************************************************************************
var Delivery = {
        validateReceiverName : function(){
            var result = false;
            var errorReceiverNameEmpty = $('#errorReceiverNameEmpty').val();
            $('#errorReceiverName').html('');
            var receiveName = $.trim($('#receiverName').val());
            if(ValidationUtil.isBlank(receiveName)){
                $('#errorReceiverName').html(errorReceiverNameEmpty);
                return result;
           } else {
               $('#errorReceiverName').html('');
               return true;
           }
        },

        validateDetailAddress : function(){
            var result = false;
            var errorDetailAddressEmpty = $('#errorDetailAddressEmpty').val();
            $('#errorDetailAddress').html('');
            var detailAddress = $.trim($('#detailAddress').val());
            if(ValidationUtil.isBlank(detailAddress)){
                $('#errorDetailAddress').html(errorDetailAddressEmpty);
                return result;
           } else {
                $('#errorDetailAddress').html('');
                return true;
           }
        },

        validateMobile : function(){
            var result = false;
            var errorMobileEmpty = $('#errorMobileEmpty').val();
            var errorMobileError = $('#errorMobileError').val();
            $('#errorMobile').html('');
            var mobile = $.trim($('#mobile').val());
            if(ValidationUtil.isBlank(mobile)){
                $('#errorMobile').html(errorMobileEmpty);
                return result;
            } else if(!ValidationUtil.isInteger(mobile) || mobile.length!=11){
                $('#errorMobile').html(errorMobileError);
                return result;
            } else {
                $('#errorMobile').html('');
                return true;
            }
        },

        validateEmail : function(){
            var errorEmailEmpty = $('#errorEmailBoxEmpty').val();
            var errorEmailError = $('#errorEmailBoxError').val();
            var email = $.trim($('#email').val());
            if(ValidationUtil.isBlank(email)){
                $('#errorEmail').html(errorEmailEmpty);
                return false;
            }else if(!ValidationUtil.isEmail(email)){
                $('#errorEmail').html(errorEmailError);
                return false;
            }else{
                $('#errorEmail').html("");
                return true;   //return result, if equal true then submit
            }
        },

        deliverySubmit : function(){
            var validate = true;
            if(!Delivery.validateReceiverName()){
                validate = false;
            }
            if(!AreaDict.validateAreaDict()){
                validate = false;
            }

            if(!Delivery.validateDetailAddress()){
                validate = false;
            }
            if(!Delivery.validateMobile()){
                validate = false;
            }
            if(!Delivery.validateEmail()){
                validate = false;
            }
            if(validate){
                $('#deliveryForm').submit();
            }
            return validate;
       },

	   addDeliveryAddr : function(){
		   $('#deliveryInfoList').show();
	   },

	   cancelDeliveryAddr : function(){
		   $('#deliveryId').val(0);
		   $('#receiverName').val('');
		   $('#province').val(1);
		   $('#city').val(22);
		   $('#county').val(3);
		   $('#detailAddress').val('');
		   $('#phone').val('');
		   $('#mobile').val('');
		   $('#email').val('');
		   $('#deliveryInfoList').hide();
	   },

	   editDelivery : function(id){
		   $.ajax({
		     type: 'post',
		     url: '/userinfo/editdelivery',
		     data: {"id" : id},
		     dataType: "json",
		     async: false,  //false is synchronization , true is asynchronism
		     success: function(data){
				 var defaultOption = $('#defaultOption').val();
				 var defaultOpt = '<option value="">'+defaultOption+'</option>';
				 if(data[1].length){
					 var i = 0;
                     var html = defaultOpt;
                     var city;
                     for(i;i<data[1].length;i++){
                         city = '<option value="'+data[1][i].id+'">'+data[1][i].title+'</option>';
                         html += city;
                    }
					$('#city').html(html);
				 }

				 if(data[2].length){
					 var i = 0;
                     var html = defaultOpt;
                     var county;
                     for(i;i<data[2].length;i++){
                         county = '<option value="'+data[2][i].id+'">'+data[2][i].title+'</option>';
                         html += county;
                    }
					$('#county').html(html);
				 }

				 if(data[0]){
				     $('#deliveryId').val(data[0].id);
					 $('#receiverName').val(data[0].name);
					 $('#province').val(data[0].address_1);
					 $('#city').val(data[0].address_2);
					 $('#county').val(data[0].address_3);
					 $('#detailAddress').val(data[0].detail_address);
					 $('#phone').val(data[0].phone_number_1);
					 $('#mobile').val(data[0].phone_number_2);
					 $('#email').val(data[0].email);
					 $('#deliveryInfoList').show();

				 }
		     }
	    });
	   },

	   delDelivery : function(id){
		   var confirmInfo = $('#confirmInfo').val();
		   if(confirm(confirmInfo)){
		       $.ajax({
		           type: 'post',
		           url: '/userinfo/deldelivery',
		           data: {"id" : id},
		           dataType: "json",
		           async: false,  //false is synchronization , true is asynchronism
		           success: function(data){
				       window.location = '/userinfo/delivery';
				   }
		      });
	       }
	   }
}

var UpdateAddress = {
		validateTeamName : function(){
            var result = false;
            var errorTeamNameEmpty = $('#errorTeamNameEmpty').val();
            $('#errorTeamName').html('');
            var teamName = $.trim($('#teamName').val());
            if(ValidationUtil.isBlank(teamName)){
                $('#errorTeamName').html(errorTeamNameEmpty);
                return result;
            } else {
                $('#errorTeamName').html('');
                return true;
            }
        },

        validateFullName : function(){
            var result = false;
            var errorFullNameEmpty = $('#errorFullNameEmpty').val();
            $('#errorFullName').html('');
            var fullName = $.trim($('#fullName').val());
            if(ValidationUtil.isBlank(fullName)){
                $('#errorFullName').html(errorFullNameEmpty);
                return result;
            } else {
                $('#errorFullName').html('');
                return true;
           }
        },

        validateProvince : function(){
            var result = false;
            var errorProvinceEmpty = $('#errorProvinceEmpty').val();
            $('#errorProvince').html('');
            var province = $.trim($('#province').val());
            if(ValidationUtil.isBlank(province)){
                $('#errorProvince').html(errorProvinceEmpty);
                return result;
            } else {
                $('#errorProvince').html('');
                return true;
           }
        },

        validateCity : function(){
            var result = false;
            var errorCityEmpty = $('#errorCityEmpty').val();
            $('#errorCity').html('');
            var city = $.trim($('#city').val());
            if(ValidationUtil.isBlank(city)){
                $('#errorCity').html(errorCityEmpty);
                return result;
            } else {
                $('#errorCity').html('');
                return true;
           }
        },

        validateAddress : function(){
            var result = false;
            var errorAddrEmpty = $('#errorAddressEmpty').val();
            $('#errorReceiveAddr').html('');
            var addr = $.trim($('#receiveAddr').val());
            if(ValidationUtil.isBlank(addr)){
                $('#errorReceiveAddr').html(errorAddrEmpty);
                return result;
            } else {
                $('#errorReceiveAddr').html('');
                return true;
           }
        },

        validateZipCode : function(){
            var result = false;
            var errorZipEmpty = $('#errorZipCodeEmpty').val();
            $('#errorZipCode').html('');
            var addr = $.trim($('#receiveAddr').val());
            if(ValidationUtil.isBlank(addr)){
                $('#errorZipCode').html(errorZipEmpty);
                return result;
            } else {
                $('#errorZipCode').html('');
                return true;
           }
        },

        updateSubmit : function(){
            var validate = true;
            if(!UpdateAddress.validateTeamName()){
                validate = false;
            }
            if(!UpdateAddress.validateFullName()){
                validate = false;
            }
            if(!UpdateAddress.validateProvince()){
                validate = false;
            }

            if(!UpdateAddress.validateCity()){
                validate = false;
            }

            if(!UpdateAddress.validateAddress()){
                validate = false;
            }

            if(!Delivery.validateMobile()){
                validate = false;
            }
            if(!UpdateAddress.validateZipCode()){
                validate = false;
            }

            var updateConfirm = $('#updateConfirm').val();
            if(validate ){
				if(confirm(updateConfirm)){
                    $('#updateAddressForm').submit();
			    }
            }
            return validate;
        }
}

var Supplement = {
    validateAccount : function(){
		var value = $.trim($("#account").val());
		$("#errorMsgAccount").html("");
		if(ValidationUtil.isBlank(value)){
			$("#errorMsgAccount").html($("#errorAccountEmpty").val());
			return false;
		}
		return true;
	},

	validatePrice : function(){
		var value = $.trim($("#price").val());
		$("#errorMsgPrice").html("");
		if(ValidationUtil.isBlank(value) || ValidationUtil.isNumber(value)){
			$("#errorMsgPrice").html($("#errorPriceEmpty").val());
			return false;
		}
		return true;
	},

	validateTranAccount: function(){
		var value = $.trim($("#tranaccount").val());
		$("#errorMsgTranAccount").html("");
		if(ValidationUtil.isBlank(value)){
			$("#errorMsgTranAccount").html($("#errorTranAccountEmpty").val());
			return false;
		}
		return true;
	},

	validateTranName: function(){
		var value = $.trim($("#tranname").val());
		$("#errorMsgTranName").html("");
		if(ValidationUtil.isBlank(value)){
			$("#errorMsgTranName").html($("#errorTranNameEmpty").val());
			return false;
		}
		return true;
	},

	validateTranTime: function(){
		var value = $.trim($("#trantime").val());
		$("#errorMsgTranTime").html("");
		if(ValidationUtil.isBlank(value)){
			$("#errorMsgTranTime").html($("#errorTranTimeEmpty").val());
			return false;
		}
		return true;
	},

	validateAkaccount: function(){
		var value = $.trim($("#akaccount").val());
		$("#errorMsgAkaccount").html("");
		if(ValidationUtil.isBlank(value)){
			$("#errorMsgAkaccount").html($("#errorAkaccountEmpty").val());
			return false;
		}
		return true;
	},

	savePayment : function(){
		var result = true;
		if($("#onlinepay").attr('checked')==true){
		    if(!Supplement.validateAccount()){
		    	result = false;
		    }
		}
		if($("#offlinepay").attr('checked')==true){
		    if(!Supplement.validateTranAccount()){
		    	result = false;
		    }
		    if(!Supplement.validateTranName()){
		    	result = false;
		    }
		    if(!Supplement.validateTranTime()){
		    	result = false;
		    }
		    if(!Supplement.validateAkaccount()){
		    	result = false;
		    }
		}
		if(!Supplement.validatePrice()){
			result = false;
		}
		if(result == false){
			return;
		}
		if($("#onlinepay").attr('checked')==true){
			Supplement.openPaymentDialog();
	        $('#supplementForm').attr("target","_blank");
		}
		$("#supplementForm").submit();
	},

	openPaymentDialog: function(){
	    var int_width = window.screen.availWidth;
	    var int_height = window.screen.availHeight;
	    $( 'body' ).css('overflow-x','hidden');
	    $('#paymentDialog').css('width',int_width + 'px');
	    $('#paymentDialog').css('height',window.document.body.clientHeight + 'px');
	    $('#paymentDialogContent').css('margin-top', (int_height > 120 ? (int_height-120)*0.3 : 0) + 'px');
	    $('#paymentDialogContent').css('margin-left', (int_width > 320 ? (int_width-320)*0.5 : 0) + 'px');
	    $('#paymentDialog').css('display','block');
    }
}

var Withdraw = {

   validateAccount : function(){
		var value = $.trim($("#account").val());
		$("#errorMsgAccount").html("");
		if(ValidationUtil.isBlank(value)){
			$("#errorMsgAccount").html($("#errorAccountEmpty").val());
			return false;
		}
		return true;
   },

   validatePrice : function(){
		var value = $.trim($("#price").val());
		$("#errorMsgPrice").html("");
		if(ValidationUtil.isBlank(value) || ValidationUtil.isNumber(value)){
			$("#errorMsgPrice").html($("#errorPriceEmpty").val());
			return false;
		}
		return true;
	},

	validateTranName: function(){
		var value = $.trim($("#tranname").val());
		$("#errorMsgTranName").html("");
		if(ValidationUtil.isBlank(value)){
			$("#errorMsgTranName").html($("#errorTranNameEmpty").val());
			return false;
		}
		return true;
	},

	validateBankname: function(){
		var value = $.trim($("#bankname").val());
		$("#errorMsgBankName").html("");
		if(ValidationUtil.isBlank(value)){
			$("#errorMsgBankName").html($("#errorBankNameEmpty").val());
			return false;
		}
		return true;
	},

	saveWithdraw: function(){
		var result = true;
		if($("#onlinepay").attr('checked')==true){
		    if(!Withdraw.validateAccount()){
		    	result = false;
		    }
		}
		if($("#offlinepay").attr('checked')==true){
		    if(!Withdraw.validateTranName()){
		    	result = false;
		    }
		    if(!Withdraw.validateBankname()){
		    	result = false;
		    }
		}
		if(!Withdraw.validateAccount()){
			result = false;
		}
		if(!Withdraw.validatePrice()){
			result = false;
		}
		if(result == false){
			return;
		}
		$("#withdrawForm").submit();
	}


}



var voteService = {
    submitMyComments : function(){
		var voteComments = $("#voteComments").val();
		var productId = $("#starBoxForm > input[name='product_id']").val();
		
		if(  $("#userid").val() == "0" ){
			alert("请先登录");
			window.location='/u/login';
			return;
		}
		//没有购买不能发表评论
		if( !voteService.isCanOpinion( productId, $("#userid").val()) ){
			alert("只有购买该商品的用户，才能发表评论");
			return;
		}
		if(  $.trim(voteComments) == "" ){
			alert("请填写内容");
			return;
		}
		if(  $.trim(voteComments).length > 200 ){
			alert("填写内容请不要超过200个汉字");
			return;
		}
        var param = {
            starpoint : $("#starBoxForm > input[name='starpoint']").val(),
            product_id : $("#starBoxForm > input[name='product_id']").val(),
//            content : $("#starBoxForm > textarea[name='content']").val()
            content : voteComments
        }
        if( !( param.starpoint || param.content ) )
            return false;
        $.ajax({
            type: 'post',
            url: $("#starBoxForm").attr('action'),
            dataType: "html",
            data: param,
            async: false,
            success: function(responseText){
        		$("#voteComments").val("");
        		alert("提交成功");
//                $("#starBoxForm").replaceWith(responseText);//replay the form info to success info
//        		voteService.reloadProductPageComments(param.product_id);//实时显示刚提交的信息
                voteService.generatePointHtml();
            },
            error: function(){
                return false;
            }
        });
    },
    reloadProductPageComments : function(int_productid){
        $.ajax({
            type: 'post',
            url: '/a/getProductPageComments',
            dataType: "html",
            data: {'product_id':int_productid},
            async: false,
            success: function(responseText){
                $("#commentsViewBlock").replaceWith(responseText);
            },
            error: function(){
                return false;
            }
        });
    },
    
    /*
     * change the point
     */
    generatePointHtml : function(){
    	var result;
    	var productId = $("#productId").val();
    	$.ajax({
    		type: 'post',
    		url: '/a/getOpinionPointHtml',
    		dataType: "html",
    		data: {"productId" : productId},
    		async: false,
    		success: function(responseText){
    			result = responseText;
    		},
    		error: function(){
    			result = "";
    		}
    	});
    	$("#avgPoint").html(result);
    },
    
    /*
     * 用户是否能够发表评论
     */
    isCanOpinion : function(productId, userId){
    	var result = "";
    	$.ajax({
            type: 'post',
            url: '/a/iscanopinion',
            dataType: "html",
            data: {"productId" : productId, "userId" : userId},
            async: false,
            success: function(responseText){
                result = responseText;
            },
            error: function(){
                result = "";
            }
        });
    	if(result == ""){
    		return false;
    	}else{
    		return true;
    	}
    	
    }
    
}

var ProductAllOpinion = {
	
	ajaxPaginate : function(currentPage){
		ProductAllOpinion.currentShowDiv(currentPage);
	},
	
	//judje current show div
	currentShowDiv : function(currentPage){
//		if(!$("#ady_" + id).is(":hidden")){
			var commentHtml = ProductAllOpinion.generateCommentHtml(currentPage);
			$("#paginate").html(commentHtml);
//		}
	},
	
	//generate the comment html
	generateCommentHtml : function(currentPage){
		var result;
		var productId = $("#productId").val();
		$.ajax({
	        type: 'post',
	        url: '/a/getCommentHtml',
	        dataType: "html",
	        data: {"productId" : productId, "currentPage" : currentPage},
	        async: false,
	        success: function(responseText){
	            result = responseText;
	        },
	        error: function(){
	            result = false;
	        }
	    });
		if(result){
			return result;
		}
		return "";
	}
		
}
/**
 * 兑换中心页面JS
 */
var ExchangeContent = {
	    
    show:function(id1, id2){
		$("#"+id1).show();
		$("#"+id2).hide();
		var CssStyle1 = $("#exchangeId1").attr("class");
		var CssStyle2 = $("#exchangeId2").attr("class");
		if(CssStyle1 == "title_1"){
			$("#exchangeId1").attr("class", "title_2")
		}else{
			$("#exchangeId1").attr("class", "title_1")
		}
		if(CssStyle2 == "title_1"){
			$("#exchangeId2").attr("class", "title_2")
		}else{
			$("#exchangeId2").attr("class", "title_1")
		}
    },
	/*
	init:function(){
		var value = $("input[name='exchange']:checked").val();
		if(value == 1){
			ExchangeContent.show('exchangxGift', 'exchangxCoupon');
		}else{
			ExchangeContent.show('exchangxCoupon', 'exchangxGift');
		}
	},
	*/
	/**
	 * 兑换产品
	 */
	exchangeGift : function(){
		var exchangeGoodsInfo = $("input[name='exchangeGoods']:checked").val();
		var exchangeGoodsArray = exchangeGoodsInfo.split("-");
		var giftId = exchangeGoodsArray[0];
		var minAcPoints = exchangeGoodsArray[1];
		var exhaustPoints = exchangeGoodsArray[2];
		//验证兑换信息
		if(!ExchangeContent.validateExchange()){
			return;
		}
		var canExchange = ExchangeContent.canExchangeGift(giftId, minAcPoints, exhaustPoints);
		if(canExchange == "success"){
			$('#exchangeForm').attr("action", "/o/updatebuyerpoint");
	        $('#exchangeForm').submit();
		}else if(canExchange == "point"){
			alert("兑换积分不足无法兑换");
		}else{
			alert("请先激活您的账号");
		}
	},

	/**
	 * ajax 判断用户级别与积分是否可以兑换该产品
	 */
	canExchangeGift : function(giftId, minAcPoints, exhaustPoints){
		var result;
		$.ajax({
	        type: 'post',
	        url: '/a/canExchangeGift',
	        dataType: "html",
	        data: {"giftId" : giftId, "minAcPoints" : minAcPoints, "exhaustPoints" : exhaustPoints},
	        async: false,
	        success: function(data){
	            result = data;
	        },
	        error: function(){
	            result = 'false';
	        }
	    });
		return result;
	},
	
	/**
	 * 判断兑换信息填写是否正确
	 */
	validateExchange : function(){
		var name = $.trim( $('#addUserName').val() );
		var province = $('#province').val();
		var city = $('#city').val();
		var county = $('#county').val();
		var addOtherAddress = $.trim( $('#addOtherAddress').val() );
		var addPhone = $.trim( $('#addPhone').val() );
		var addMobileTelephone = $.trim( $('#addMobileTelephone').val() );
		var addEmail = $.trim( $('#addEmail').val() );
		
		if(name == ""){
			alert("请将信息填写完整");
			return false;
		}
		if(province == ""){
			alert("请将信息填写完整");
			return false;
		}
		if(city == ""){
			alert("请将信息填写完整");
			return false;
		}
		if(county == ""){
			alert("请将信息填写完整");
			return false;
		}
		if(addOtherAddress == ""){
			alert("请将信息填写完整");
			return false;
		}
		if(addPhone == ""){
			alert("请将信息填写完整");
			return false;
		}else if(!ValidationUtil.isInteger(addPhone)){
			alert("请填写正确的信息");
        	return false;
        }
		if(addMobileTelephone == ""){
			alert("请将信息填写完整");
			return false;
		}else if(!ValidationUtil.isInteger(addMobileTelephone) || addMobileTelephone.length != 11){
			alert("请填写正确的信息");
        	return false;
        }
		if(addEmail == ""){
			alert("请将信息填写完整");
			return false;
		}else if(!ValidationUtil.isEmail(addEmail)){
			alert("请将信息填写完整");
            return false;
        }
		return true;
		

        if(ValidationUtil.isBlank(addMobileTelephone)){
            $("#errorMobilePhoneInfo").html(errorMobilePhoneEmpty);
            submit = false;
        }else if(!ValidationUtil.isInteger(addMobileTelephone) || addMobileTelephone.length != 11){
        	$("#errorMobilePhoneInfo").html(errorMobilePhone);
        	submit = false;
        }
        if(ValidationUtil.isBlank(addEmail)){
            $("#errorEmailInfo").html(errorEmailEmpty);
            submit = false;
        }else if(!ValidationUtil.isEmail(addEmail)){
        	$("#errorEmailInfo").html(errorEmail);
            submit = false;
        }
		
	},
	
	//兑换礼品分页方法
	ajaxPaginate : function(currentPage){
		var result;
		$.ajax({
	        type: 'post',
	        url: '/a/getExchangeHtml',
	        dataType: "html",
	        data: {"currentPage" : currentPage},
	        async: false,
	        success: function(responseText){
	            result = responseText;
	        },
	        error: function(){
	            result = "";
	        }
	    });
		$("#paginate").html(result);
	},
	
	
	exchangePromotion : function(){
		var exchangePromotionInfo = $("input[name='exchangeCoupon']:checked").val();
		var exchangePromotionArray = exchangePromotionInfo.split("-");
		var promotionId = exchangePromotionArray[0];
		var minAcPoints = exchangePromotionArray[1];
		var exhaustPoints = exchangePromotionArray[2];
		var canExchange = ExchangeContent.canExchangePromotion(minAcPoints, exhaustPoints);
		if(canExchange == "success"){
			$('#exchangeForm').attr("action", "/o/exchangePromotion");
	        $('#exchangeForm').submit();
		}else{
			alert("兑换积分不足无法兑换");
		}
	},
	
	/**
	 * ajax 判断用户级别与积分是否可以兑换抵用券
	 */
	canExchangePromotion : function(minAcPoints, exhaustPoints){
		var result;
		$.ajax({
	        type: 'post',
	        url: '/a/canExchangePromotion',
	        dataType: "html",
	        data: {"minAcPoints" : minAcPoints, "exhaustPoints" : exhaustPoints},
	        async: false,
	        success: function(data){
	            result = data;
	        },
	        error: function(){
	            result = 'false';
	        }
	    });
		return result;
	},
	
	/**
	 * ajax Gift Paginate
	 */
	ajaxGiftPaginate : function(currentPage){
		var result;
		$.ajax({
	        type: 'post',
	        url: '/a/getExchangeListHtml',
	        dataType: "html",
	        data: {"currentPage" : currentPage},
	        async: false,
	        success: function(responseText){
	            result = responseText;
	        },
	        error: function(){
	            result = "";
	        }
	    });
		$("#paginate").html(result);
	}
}

var WishlistContent = {

	ajaxWishlistPaginate : function(currentPage){
		var result;
		$.ajax({
	        type: 'post',
	        url: '/a/getWishlistHtml',
	        dataType: "html",
	        data: {"currentPage" : currentPage},
	        async: false,
	        success: function(responseText){
	            result = responseText;
	        },
	        error: function(){
	            result = "";
	        }
	    });
		$("#paginate").html(result);
	},
	
	delWishlistItem : function(cwid){
		$.ajax({
	        type: 'post',
	        url: '/a/deliteminfo',
	        dataType: "html",
	        data: {"cwid" : cwid},
	        async: false,
	        success: function(responseText){
	            result = responseText;
	        },
	        error: function(){
	            result = "";
	        }
	    });
		$("#paginate").html(result);
	},
		
	addcommon : function(cwid){
			$("#addcomment_"+cwid).hide();
			$("#submitComment_"+cwid).show();
			$("#showComment_"+cwid).hide();
	},
		
	subcommon : function(cwid){
		var result = "";
		var comment = $("#comment_"+cwid).val();
		$.ajax({
	        type: 'post',
	        url: '/a/updatecomment',
	        dataType: "html",
	        data: {"cwid" : cwid, "comment" : comment},
	        async: false,
	        success: function(responseText){
	            result = responseText;
	        },
	        error: function(){
	            result = "";
	        }
	    });
		$("#wishlistCommentInfo_"+cwid).html(result);
		
			$("#addcomment_"+cwid).hide();
			$("#submitComment_"+cwid).hide();
			$("#showComment_"+cwid).show();
	},
	
	editcommon : function(cwid){
		$("#addcomment_"+cwid).hide();
		$("#submitComment_"+cwid).show();
		$("#showComment_"+cwid).hide();
	},
	
	addToCart : function(cwid){
		var productItemId = $("#hProductItemId_"+cwid).val();
		var salePrice = $("#hSalePrice_"+cwid).val();
		var productId = $("#hProductId_"+cwid).val();
		$.ajax({
	        type: 'post',
	        url: '/a/addwishlistitemtocart',
	        dataType: "html",
	        data: {"productItemId" : productItemId, "salePrice" : salePrice, "productId" : productId},
	        async: false,
	        success: function(){
	        	window.location='/u/cart';
	        },
	        error: function(){
	            
	        }
	    });
		
	}
	    
}

var Active = {
	activeAccount : function(){
		$.ajax({
	        type: 'post',
	        url: '/u/resendactiveemail',
	        dataType: "json",
	        async: false,
	        success: function(responseText){
	           if(responseText=="true"){
				   alert("邮件发送成功，请进入邮箱激活您的账号！");
			   } 
	        },
	        error: function(){
	             alert("邮件发送失败，请重试！");
	        }
	    });
	}
}