jQuery(function($){
    $('.buy-num button').click(function(){
        click_change_goodsnum($(this));
    });
    $('.buy-num input').blur(function(){
        click_change_goodsnum($(this).siblings('button'));
    });
    $('div.tabCon_3 dd a').click(function(){
        window.location.reload();
    });
    $("#check_box").prop("checked", true);
    check_select('cart_id[]');
    //compute_price();
});
//计算总价
function compute_price(){
    var all_goods_price = all_save_price = 0;
    $("div.buy-item").each(function(){
        var shop_all_price = shop_all_weight = 0;
        if($(this).find('.buy_list.promot .event_info.event_info_new').length>0) {
            $(this).find('.buy_list.promot .event_info.event_info_new').each(function () {
                var promot_id = parseInt($(this).attr('rel'));
                var this_promot_goods_price = 0;
                if (promot_id > 0) {
                    var this_promot_goods_num = true;
                    $(this).parent().parent().find('.buy_list .buy-goods[promotrel="' + promot_id + '"]').each(function () {
                        if ($(this).parent().is(':visible') && $(this).find("input[type='checkbox'].goods_check").is(':checked')) {
                            //商品单价
                            var goods_unit_price = parseFloat($(this).find('.buy-price em').html());
                            //商品数量
                            var goods_num = parseInt($(this).find('.buy-num input').val());
                            //单重
                            var goods_weight = parseFloat($(this).find('.buy-weight input').val());
                            //总重
                            shop_all_weight += goods_num * goods_weight;
                            //商品总价
                            this_promot_goods_price += goods_unit_price * goods_num;
                            this_promot_goods_num = false;
                        }
                    });
                    var this_promot_parent = $(this);
                    click_change_price(this_promot_parent, promot_id, this_promot_goods_price);
                }
                var cur_price = $(this).attr('cur');
                var ori_price = $(this).attr('ori');
                cur_price = (parseFloat(cur_price) > 0) ? parseFloat(cur_price) : parseFloat(this_promot_goods_price);
                ori_price = (parseFloat(ori_price) > 0) ? parseFloat(ori_price) : parseFloat(this_promot_goods_price);
                var sav_price = parseFloat(ori_price - cur_price);
                shop_all_price += parseFloat(cur_price);
                all_goods_price += parseFloat(cur_price);
                all_save_price += parseFloat(sav_price);
            });
        }
        if($(this).find('.buy_list .buy-goods[promotrel="0"]').length>0){
            var this_promot_goods_price = 0;
            $(this).find('.buy_list .buy-goods[promotrel="0"]').each(function () {
                if ($(this).parent().is(':visible') && $(this).find("input[type='checkbox'].goods_check").is(':checked')) {
                    //商品单价
                    var goods_unit_price = parseFloat($(this).find('.buy-price em').html());
                    //商品数量
                    var goods_num = parseInt($(this).find('.buy-num input').val());
                    //单重
                    var goods_weight = parseFloat($(this).find('.buy-weight input').val());
                    //总重
                    shop_all_weight += goods_num * goods_weight;
                    //商品总价
                    this_promot_goods_price += goods_unit_price * goods_num;
                }
            });
            var cur_price = parseFloat(this_promot_goods_price);
            var ori_price = parseFloat(this_promot_goods_price);
            var sav_price = parseFloat(ori_price - cur_price);
            shop_all_price += parseFloat(cur_price);
            all_goods_price += parseFloat(cur_price);
            all_save_price += parseFloat(sav_price);
        }
        $(this).find('.buy-freight .amount strong').html(foramtmoney(shop_all_price));
        $(this).find('.buy-freight .weight strong').html(foramtmoney(shop_all_weight)+'KG');
    });
    $('#totalPrice').html('¥'+foramtmoney(all_goods_price));
    if(all_save_price!=0) $('.buy_text p.text2').html('(不含运费 ，共节省¥'+foramtmoney(all_save_price)+' )');
    else $('.buy_text p.text2').html('(不含运费)');
    /*******************************/
    /****如果购物车里没东西了就刷新页面***/
    var is_visible=0;
    $('.buy_list .buy-goods').each(function(){
        if($(this).parent().is(':visible')){
            is_visible=1;
        }
    });
    if(is_visible==0){window.location.reload();}
    /*******************************/
}
//改变活动，刷新页面
function change_act(cart_id,act_id){
    var querydata = new Object;
    querydata['cart_id']=cart_id;
    querydata['act_id']=act_id;
    $.ajax({
        url: APP + "Cart/change_act",
        type: "post",
        data: querydata,
        dataType: "json",
        success: function (ret) {
//                alert(JSON.stringify(ret));
            if(ret.status==1){
                window.location.reload();
            }else return;//$.showErr('更换活动失败',0,'hc');
        }
    });
};
//购物数量加减
function click_change_goodsnum(obj){
    var goodsnum = parseInt($(obj).siblings('input').val());
    var goodsstock = parseInt($(obj).siblings('input').attr('sto'));
    var goodsinu = parseInt($(obj).siblings('input').attr('inu'));
    var goodsanu = parseInt($(obj).siblings('input').attr('anu'));
    if(goodsnum>0){
        if($(obj).text()=='+'){
            goodsnum = goodsnum+1;
        }else if($(obj).text()=='-'){
            if(goodsnum>1){
                goodsnum = goodsnum-1;
            }else{
                click_del_goods(obj);
            }
        }
        if((goodsnum>goodsstock)) goodsnum = goodsstock;
        if((goodsanu>0)) {
            if((goodsnum>goodsanu)) goodsnum = goodsanu;
        }
        if((goodsinu>0)) {
            if((goodsnum<goodsinu)) goodsnum = goodsinu;
        }
    }else{
        goodsnum = 1;
    }
    $(obj).siblings('input').val(goodsnum);
    click_change_promot(obj,$(obj).parent().parent().parent().parent(),1);
}
//活动改变

function click_change_promot(obj,parents,type){
    //更换商品数量价格
    if(type==1){click_change_num_price(obj)};
    //循环计算活动与商品之间的价格
    $(parents).find('.buy_list.promot .event_info.event_info_new').each(function(){
        var promot_id = parseInt($(this).attr('rel'));
        if(promot_id>0){
            var this_promot_goods_price = 0;
            var this_promot_goods_num = true;
            $(parents).find('.buy_list .buy-goods[promotrel="'+promot_id+'"]').each(function(){
                if($(this).parent().is(':visible')){
                    //商品单价
                    var goods_unit_price = parseFloat($(this).find('.buy-price em').html());
                    //商品数量
                    var goods_num = parseInt($(this).find('.buy-num input').val());
                    //商品总价
                    this_promot_goods_price+=goods_unit_price*goods_num;
                    this_promot_goods_num = false;
                }

            });
            //若当前活动下无商品   remove
            if(this_promot_goods_num){$(this).parent().remove();}
            var this_promot_parent = $(parents).find('.event_info.event_info_new[rel="'+promot_id+'"]');
            click_change_price(this_promot_parent,promot_id,this_promot_goods_price);
        }
    });
    compute_price();
    //end
}
//计算数量价格
function click_change_num_price(obj){
    //数量
    var goodsnum = parseInt($(obj).siblings('input').val());
    //单价
    var goodsprice = $(obj).parent().parent().find('.buy-price em').html();
    //单重
    var goods_weight = parseFloat($(obj).parent().parent().find('.buy-weight').find('input').val());
    //总重
    $(obj).parent().parent().find('.buy-weight span').html(foramtmoney(goodsnum*goods_weight)+'KG');
    //合计
    $(obj).parent().parent().find('.buy-price-count strong').html(foramtmoney(goodsnum*goodsprice));

}
//计算活动价格
function click_change_price(parents,promot_id,prices){
    prices = parseFloat(prices);
    var demo_prices = orig_prices =  prices;//alert(JSON.stringify(promot_lists_json[promot_id]));
    if(!promot_lists_json[promot_id])return true;
    var act_name = promot_lists_json[promot_id]['act_name'];
    var min_amount = parseFloat(promot_lists_json[promot_id]['min_amount']);//金额下限
    var max_amount = parseFloat(promot_lists_json[promot_id]['max_amount']);//金额上限
    var act_type = promot_lists_json[promot_id]['act_type'];//类型:1满减2满折
    var act_type_ext = parseFloat(promot_lists_json[promot_id]['act_type_ext']);//优惠值
    var is_addup = promot_lists_json[promot_id]['is_addup'];//当活动为限时促销时 是否叠加
    //满足活动最低价
    if(prices>=min_amount){
        if(act_type==1){
            if(is_addup==1){
                if(max_amount&&prices>=max_amount){demo_prices = max_amount;}
                if(max_amount==0){demo_prices=prices;}
            if(min_amount>0) prices = prices - (Math.floor(demo_prices/min_amount)*act_type_ext);
            }else{
                prices = prices - act_type_ext;
            }
        }else if(act_type==2){
            prices = prices*(act_type_ext/100);
        }

        $(parents).find('.koujian').html('已优惠：'+foramtmoney(orig_prices-prices));
        $(parents).find('.view-detail-btn').hide();
    }else{
        $(parents).find('.koujian').hide();
    }
    $(parents).attr('cur',prices);
    $(parents).attr('ori',orig_prices);
    prices = foramtmoney(prices);
    orig_prices = foramtmoney(orig_prices);
    $(parents).find('.buy-price-count strong').html(prices);
    $(parents).find('.buy-price-count del').html(orig_prices);
    if(act_name){$(parents).find('.inblock').html(act_name);}
}
//删除商品
function click_del_goods(obj){
    $.showConfirm('确认删除？',function(){
        del_goods(obj);
    },1,'hc');
}
function del_goods(obj){
    //Ajax 删除商品
    var querydata = new Object;
    querydata['id'] = new Object;
    if(obj){
        var cart_id=$(obj).parent().parent().parent().find("input[name='del_id']").val();
        querydata['id'][cart_id]=cart_id;
    }else {
        $('input[name="cart_id[]"]:checked').each(function () {
            var cart_id = $(this).val();
            //del_goods('#del_cart' + cart_id);
            querydata['id'][cart_id]=cart_id;
        });
    }
    $.ajax({
        url: APP + "Cart/del_cart",
        type: "post",
        data: querydata,
        dataType: "json",
        success: function (ret) {
//                alert(JSON.stringify(ret));
            if(ret.status==1){
//                    window.location.reload();
                //活动变动
                if(obj){
                    $(obj).parent().parent().parent().hide();
                    click_change_promot(obj,$(obj).parent().parent().parent().parent(),0);
                }else {
                    $('input[name="cart_id[]"]:checked').each(function () {
                        var cart_id = $(this).val();
                        var cart=$('#del_cart' + cart_id);
                        $(cart).parent().parent().parent().hide();
                        click_change_promot(cart,$(cart).parent().parent().parent().parent(),0);
                    });
                }
            }else $.showErr('删除失败',0,'hc');
        }
    });
    //End
}
/**
 * 批量删除
 */
function all_del(){
    $.showConfirm('确认删除？',function(){
        del_goods('');
    },1,'hc');
}
/**
 * 领取优惠券
 * @param id
 */
function get_ecv(id){
    var query=new Object();
    query.id=id;
    $.ajax({
        url:APP + "Goods/get_ecv",
        data:query,
        type:"post",
        success:function(data){
            if(data.status==1) {
                $.showSuccess(data.info,0,'hc');
                $(".ticket_"+id).find('div.coupon-amount').removeClass('RedPape');
                $(".ticket_"+id).find("div.coupon-op span.CouponBtn").html('已领取').addClass('CouponBtn-success');
                $(".ticket_"+id).find("div.coupon-op").removeAttr('onclick');
                var Jcount=$(".ticket_"+id).parent().siblings('div.coupon-title').find('.J_ReceivedCount');
                var j_count=Jcount.html();
                j_count++;
                Jcount.html(j_count);
                var jp_count=Jcount.parent().attr('count');
                if(j_count==jp_count){
                    Jcount.parent().html('<span class="icon-laba"></span>已领取 <em class="J_ReceivedCount">'+j_count+'</em> 张优惠券');
                }
            }else{
                $.showErr(data.info,0,'hc');
            }
        }
    })
}
/**
 * 选择全部
 */
function check_select(name,shop_id,cart_id) {
    shop_id = parseInt(shop_id);
    cart_id = parseInt(cart_id);
    if(shop_id>=0){
        if(cart_id>0){
            //判断是否店铺下商品都选中了
            var is_goods_all=true;
            $("input[name='" + name + "'][shop_id='" + shop_id + "'].goods_check").each(function() {
                if ($(this).prop("checked") == false) is_goods_all=false;
            });
            if(is_goods_all==true) $("#check_box_shop_id_"+shop_id).prop("checked",true);
            else $("#check_box_shop_id_"+shop_id).prop("checked",false);
            /**************************************/
            /*这段和!cart_id>0的代码相似，但不可以合一起*/
            if ($("#check_box_shop_id_" + shop_id).prop("checked") == false) {
                $("#check_box").prop("checked", false);
            } else {
                //判断是否店铺都选中了
                var is_all = true;
                $("input[name='" + name + "'].shop_check").each(function () {
                    if ($(this).prop("checked") == false) is_all = false;
                });
                if (is_all == true) $("#check_box").prop("checked", true);
                else $("#check_box").prop("checked", false);
            }
            /**************************************/
        }else {
            if ($("#check_box_shop_id_" + shop_id).prop("checked") == false) {
                $("input[name='" + name + "'][shop_id='" + shop_id + "']").each(function () {
                    this.checked = false;
                });
                $("#check_box").prop("checked", false);
            } else {
                $("input[name='" + name + "'][shop_id='" + shop_id + "']").each(function () {
                    this.checked = true;
                });
                //判断是否店铺都选中了
                var is_all = true;
                $("input[name='" + name + "'].shop_check").each(function () {
                    if ($(this).prop("checked") == false) is_all = false;
                });
                if (is_all == true) $("#check_box").prop("checked", true);
                else $("#check_box").prop("checked", false);
            }
        }
    }else{
        if ($("#check_box").prop("checked") == false) {
            $("input[name='" + name + "']").each(function() {
                this.checked = false;
            });
        } else {
            $("input[name='" + name + "']").each(function() {
                this.checked = true;
            });
        }
    }
    compute_price();
}

//提交购物车
function sub_cart(){
    var querydata = new Object;
    querydata['id'] = new Array();
    querydata['number'] = new Array();
    $("input[name='cart_id[]'].goods_check").each(function() {
        if ($(this).parent().parent().is(':visible') && $(this).prop("checked") == true){
            querydata['id'].push($(this).val());
            querydata['number'].push($(this).parent().find("div.buy-num input[type='text']").val());
        }
    });
    $.ajax({
        url: APP + "Cart/sub_cart",
        type: "post",
        data: querydata,
        dataType: "json",
        success: function (ret) {
                //alert(JSON.stringify(ret));
            if(ret.status==1){
                window.location.href=ret.url
            }else if(ret.status==2) {
				$.openUrl(ret.url, ret.msg, 'ID', '800', function () {
                    return false;
                }, function () {
                    return false;
                });
			}else $.showErr(ret.msg,0,'hc');
        }
    });
}
//加入收藏
function add_favorite(id,type,cart_id){
    $.get(APP+"Home/Integral/favorite", { id: id,type:type,is_on:0}, function(data){
        if(data.status==0) {
            $.openUrl(data.url, data.msg, 'ID', '800', function () {
                return false;
            }, function () {
                return false;
            });
        }else if(data.status == 2){
            $("#words_"+cart_id).html('加入收藏');
            $.showSuccess(data.msg,0,'hc');
        }else if(data.status == 3){
            $.showErr(data.msg,0,'hc');
        }else{
            $("#words_"+cart_id).html('取消收藏');
            $.showSuccess(data.msg,0,'hc');
        }
    });
}