$(document).ready(function(){
	$('#showyiwen').live('mouseover',function(){$('#yiwen').show();});
	$('#showyiwen').live('mouseout',function(){$('#yiwen').hide();});
	function numbers(obj){obj.value=obj.value.replace(/[^\d]/g,'');}	
    
	$("#point_ipt").live('keyup', function(){
		//积分
		numbers(this);
        $('#hidden-point').val(this.value);
		//caculate_point();	
		jisuan_total();
	});	
		
	function caculate_point(){
		var el = $('#point_ipt'), point_money = 0, msg, point;
		if (typeof(min_use_point) == 'number') {
			point = el.val();
            
			if (point == ''){
				$('#point_tips').html('');
				return point_money;		
			}		
			
			point = parseInt(point);
			isNaN(point) && (point = 0);
			el.val(point);
			
			var use_point_max = parseInt($('#use_point_max').text());
			
			if (point > use_point_max) {
                point = use_point_max;
				$('#point_ipt, #hidden-point').val(use_point_max);
			}
            
			point_money = (parseFloat(point) * point_rate).toFixed(2);
            msg = ' - '+ point_money + ' USD';
            
            $('#point_tips').html(msg);
		}
        
        return point_money;
	}
			
	jisuan_total();
	
	
	
	$(".shipping_method").live('click', function(){
		shipping_id = $(this).val();
		yunfei      = $("#sm"+shipping_id).html();
		//$("#shipping_sub_total").html(yunfei);
		//$("#free_shipping_sub_total").html(freeyunfei);
		
		switch (shipping_id){
			case "1":
			   $("#Need_Traking_number_button1").show('slow');
               //var _v = $('#freesm1').html($(".Need_Traking_number").val());
               $('.Need_Traking_number').attr('checked') && $('#freesm1').html($(".Need_Traking_number").val());
			   //$('#freesm1').html($(".Need_Traking_number").val());
			   //$(".Need_Traking_number").attr("checked",true);
			break;
			
			case "2":
			   $("#Need_Traking_number_button1").hide('slow');
			   //$(".Need_Traking_number").attr("checked",false);
			   //$('#freesm1').html('0.00');
			break;
			
			case "3":
			   $("#Need_Traking_number_button1").hide('slow');
			   //$(".Need_Traking_number").attr("checked",false);
			   //$('#freesm1').html('0.00');
			break;
			
			default:
			
			break;
		}
        freeyunfei  = $("#freesm"+shipping_id).html();
        $("#shipping_sub_total").html(yunfei);
		$("#free_shipping_sub_total").html(freeyunfei);
		jisuan_total();	
	 });
     
	$('.Need_Traking_number').live('click', function(){
		shipid = $(this).attr('shipid');
		thisprice = parseFloat($('#Need_Traking_number_fee'+shipid).html());
		freesmprice = parseFloat($('#freesm'+shipid).html());
        var el = $("#free_shipping_sub_total"), free_sub_total = el.html();
		if($(this).attr("checked")){
			freesmprice = freesmprice + thisprice
			$('#freesm'+shipid).html(freesmprice.toFixed(2));
			$('#freesm'+shipid).attr("orgp",freesmprice.toFixed(2));
		}else{
			freesmprice = freesmprice - thisprice;
            freesmprice = Math.max(freesmprice, 0);
			$('#freesm'+shipid).html(freesmprice.toFixed(2));
			$('#freesm'+shipid).attr("orgp",freesmprice.toFixed(2) );
		}
        el.html(freesmprice.toFixed(2));
		jisuan_total();

	});
	
	
    
    $("#bizhong").val($.cookie('bizhong'));

    //保费
	$(".baofei").live('click', function(){
		yunfei  = $("#baofei").html();
		if($(this).attr("checked") == true){ 
			$("#insurance").html(yunfei);
		}else{
			$("#insurance").html(0);
		}
		jisuan_total();
    });
	
	
	function jisuan_total(){
		
		var point_money = 0;
		point_money=caculate_point();
		//return;
		point_money=point_money;
		//alert(point_money);
		$("#point_money").html(point_money);
		$("#point_money").attr("orgp",point_money);
		point_money = (point_money == undefined)?0:parseFloat(point_money);
		
		
		free_sub_total = $("#free_shipping_sub_total").html();
		free_sub_total = (free_sub_total == undefined)?0:parseFloat(free_sub_total);
		sub_total = $("#shipping_sub_total").html();
		cheknum = ($('.Need_Traking_number').attr("checked"))?parseFloat($('.Need_Traking_number').val()):0;
        cheknum = 0;
		sub_total = (sub_total == undefined)?0:parseFloat(sub_total);
		yunfei    = parseFloat($("#insurance").html());
		xx_sub_total = parseFloat($("#items_sub_total").html());
		$("#price_total").html((sub_total - point_money +yunfei + xx_sub_total+free_sub_total+cheknum).toFixed(2));
	}
	
	$(".paymentselect").live('click', function(){
			id = $(this).val();
			if (id == 'PayPal') {
				$("#bt_apple_code").show("slow");
			//	$("#showapp").show("slow");
			}else{
				$("#bt_apple_code").hide("slow");
				$("#showapp").hide("slow");
			}
			
		$(".paymentselect").each(function(){
			sid = $(this).val();
			if (sid==id){
				$("#subpaymentlist"+sid).show("slow");
			}else{
				$("#subpaymentlist"+sid).hide("slow");
			}
			 
	    });
    });
	
	
});

function chenkpayment(){
	try{
		var obj=document.getElementsByName("payment");
	}
	catch(err)
	{
		return false;
	}
	var l=obj.length;
	
	for(var i=0;i<l;i++)
	{
		if(obj[i].checked==true){
			//document.getElementById("payment_title").className="";
			return true;
		}
	}

	return false;
}

function chenkship(){
	 
	try{
		var obj=document.getElementsByName("shipping");
	}
	catch(err)
	{
		return false;
	}
	var l=obj.length;
	
	for(var i=0;i<l;i++)
	{
		if(obj[i].checked==true){
			//document.getElementById("payment_title").className="";
			return true;
		}
	}

	return false;
}
function checkInfo(){
	if(chenkship()!=true){		
		alert("Please choose shipping method");
		window.location.hash="ship";
		try{
			document.getElementsByName("shipping")[0].focus();
		}
		catch(err){
			
		}
		return false;
	}	
	
	if(chenkpayment()!=true){
			
		alert("Please choose payment method");
		window.location.hash="pay";
		try{
			document.getElementsByName("payment")[0].focus();
		}
		catch(err){
			
		}
		return false;
	}
	
	if ($("#postscript").val().length>500){
		$("#postscript").focus();
		alert("The review must be less than 500 chars.");
		return false;
	}
	return true;
}



function checkcode(obj){
	var obj = $(obj);
	var objvalue = encodeURIComponent(obj.val());
	var huance   = obj.attr('huance');  //huan chun zong jia 
	var isApply  = obj.attr('isApply');  //huan chun shi fou yingyong 
	var huancode = obj.attr('huancode');  //huan chun cu xiao ma , yongyu panduan cuxiaoma sfou you gaidong 
	var total_obj = $('span[entry="all_total_price"]');
	var total_p = parseFloat(huance).toFixed(2);
	
	if (isApply == "1") {
		if (objvalue!=huancode){
			total_obj.html(total_p);
			total_obj.attr('orgp',total_p);
			obj.attr('isApply','0')
			obj.attr('huance','0')
			alert('Please do not delete or modify the promotional code, or can not be the appropriate discount will be applied');
		}
	}
	
}

var hitnum = 1;
function showappdiv(showdiv){
	if (hitnum%2 == 0 ){
	    $("#"+showdiv).hide();
		$("#bt_apple_code").attr('class','bt_apple1');
	}else{
	    $("#"+showdiv).show();
		$("#bt_apple_code").attr('class','bt_apple2');
	}
	hitnum++;
}

function code_apply(obj_str){
	var obj = $("#"+obj_str);	
	var objvalue = encodeURIComponent(obj.val());
	if  (objvalue.length == 0) return false;
	if (objvalue.length > 40){
    	alert('Promotion code Please do not enter too many characters');
		return false;
	}
	hitnum = 1;
	$('#apply_msg').html('Loading...');
    $('#hidden-coupon').length > 0 ? $.post('/m-dropshipping-a-apply_coupon.htm', {
        coupon: objvalue,
        dropshipping: $('#hidden-dropshipping').length,
        price: $('#items_sub_total').html()
    }, function(data) {
        if (data) {
            $('#apply_msg').html(data);
            $('#hidden-coupon').val() && re_load();
        }
        else {
            re_load();
        }
    }) : re_load('/m-flow-a-cart.htm?pcode='+objvalue);
}

/**
 * checkout页面事件绑定
 * 
 */
function checkoutBinds() {
    showConsignee();
    saveConsignee();
    checkConsignee();
    confirmDropshippingInfo();
    changeCountry();
}

/**
 * 确认多订单中某个订单
 * 
 */
function confirmDropshippingInfo() {
    $('#btn-confirm').click(function() {
        var el = $('#form-consignee');
        
        if (el.valid()) {
            $.post('/m-dropshipping-a-checkout_confirm', el.serialize(), function (data) {
                if (data == '1') {
                    location.replace('/m-users-a-sign.htm?ref=' + encodeURIComponent(location.href));
                }
                else {
                    location.replace('/m-dropshipping-a-order_confirm.html');
                }
            });
        }
        else {
            $('html,body').animate({
                scrollTop: el.offset().top
            }, 300);
        }
    });
}

/**
 * 更新国家
 * 
 */
function changeCountry() {
    $('#hidden-reload').length > 0 && $('select[id="country"]').change(function()  {
        this.value && (location.search = 'country=' + this.value);
    });
}

/**
 * checkout页面显示编辑收货地址
 * 
 */
function showConsignee() {
    $('#a-show-consignee').click(function() {
        $('#tb-consignee').show();
        $('#div-consignee').hide();
    });
}

/**
 * cart页面购买了其它产品
 * 
 */
function setAlsoBuoght() {
    $('#div-also-bought').jCarouselLite({
        btnNext: "#detailsrightbar",
        btnPrev: "#detailsleftbar",
        vertical: false,
        play:true,
        auto: 3000,
        visible: 8,
        scroll: 2,
        //mouseWheel: true,
        speed: 800
    });
}

/**
 * checkout页面保存收货地址
 * 
 */
function saveConsignee() {
    $('#btn-save-consignee').click(function() {
        if ($('#form-consignee').valid()) {
            this.disabled = true;
            $.post('m-flow-a-consignee.htm', $('#form-consignee').serialize() + '&from_checkout=1', function() {
                re_load('/m-flow-a-checkout.htm?ajax=true');
            });
        }
    });
    $('#btn-cancel-consignee').click(function() {
        $('#tb-consignee').hide();
        $('#div-consignee').show();
    });
}

/**
 * checkout页面验证收货地址
 * 
 */
function checkConsignee() {
    $('#form-consignee').validate({
        rules: {
            firstname: {
                required: true,
                maxlength: 60
            },
            lastname: {
                required: true,
                maxlength: 60
            },
            tel: {
                required: true,
                maxlength: 60
            },
            email: {
                required: true,
                maxlength: 60,
                email: true
            },
            addressline1: {
                required: true,
                maxlength: 120
            },
            city: {
                required: true,
                maxlength: 80
            },
            province: {
                required: true,
                maxlength: 80
            },
            country: {
                required: true
            },
            zipcode: {
                required: true,
                maxlength: 20
            }
        },
        messages: {
            firstname: {
                required: firstname_msg,
                maxlength: firstname_maxlength_msg
            },
            lastname: {
                required: lastname_msg,
                maxlength: lastname_maxlength_msg
            },
            tel: {
                required: tel_msg,
                maxlength: tel_maxlength_msg
            },
            email: {
                required: email_msg,
                maxlength: email_maxlength_msg
            },
            addressline1: {
                required: addressline1_msg,
                maxlength: addressline1_maxlength_msg
            },
            city: {
                required: city_msg,
                maxlength: city_maxlength_msg
            },
            province: {
                required: province_msg,
                maxlength: province_maxlength_msg
            },
            country: {
                required: country_msg
            },
            zipcode: {
                required: zipcode_msg,
                maxlength: zipcode_maxlength_msg
            }
        },
        success: function(label) {
            // set &nbsp; as text for IE
            label.html("&nbsp;").addClass("checked");
        }
    });
}

