$(document).on('click','.cart_qty_remove',function(){
    var index=$(".cartDialog_item_info_remove").index(this);
    var inpobj = $(".qty_val").eq(index);
    var qty_val_origin=parseInt(inpobj.val());
    var qty_productid_origin=parseInt(inpobj.attr('pid'));
    var qty_vid=parseInt(inpobj.attr('vid'));
    num = 0;
    if(num == 0){
        $(".cartDialog_item").eq(index).remove();
    }
    var total_qty=0;
    var total_price=0; 
    $(".cartDialog_item").each(function(index,ele){
        total_qty+=parseInt($(this).find('.cartDialog_item_info_qty').text())
        total_price+=parseFloat($(this).find('.current_price').attr('data-price'))
    });
    $(".cart_dialog_footer_total b").text('$'+total_price);
    if(total_qty>0){
        $(".packetTip").show();
    }else{
        $(".packetTip").hide();
    }
	var cid = parseInt(inpobj.attr('cid'));
	add_cart(qty_productid_origin,qty_vid,0,'update_cart',cid);
	return;    
});


$(function(){
    console.log('init');
    var winW=window.innerWidth;
    var localHref=window.location.href;
    var pageUri=localHref.substring(localHref.lastIndexOf('/')+1,localHref.indexOf('.html'))+'.html';

    var announcement_H=$(".announcement").height();
    var header_H=$(".header").height();
    var cartHead_H=$(".cartHead").height();
    $(window).on('scroll',function () {
        if($(window).scrollTop()>announcement_H){
            $(".header").addClass('header_fixed');
            $(".toTop").show();
            $('body').css('padding-top',header_H);
            $(".product_purchase").css('top',header_H+20);
            if(winW<=1240 && pageUri=='cart.html'){
                $(".cartHead").addClass('cartHead_fixed');
                $('body').css('padding-top',cartHead_H+20);
            }
        }else{
            $(".header").removeClass('header_fixed');
            $(".toTop").hide();
            $('body').css('padding-top',0);
            $(".product_purchase").css('top',0);
            if(winW<=1240 && pageUri=='cart.html'){
                $(".cartHead").removeClass('cartHead_fixed');
                $('body').css('padding-top',0);
            }
        }
    });

    $(".toTop").click(function(){
        $('body,html').animate({scrollTop: 0}, 800);
    });

    ;(function($){
        $.fn.extend({
            donetyping: function(callback,timeout){
                timeout = timeout || 1e3;
                var timeoutReference,
                    doneTyping = function(el){
                        if (!timeoutReference) return;
                        timeoutReference = null;
                        callback.call(el);
                    };
                return this.each(function(i,el){
                    var $el = $(el);
                    $el.is(':input') && $el.on('keyup keypress paste',function(e){
                        if (e.type=='keyup' && e.keyCode!=8) return;

                        if (timeoutReference) clearTimeout(timeoutReference);
                        timeoutReference = setTimeout(function(){
                            doneTyping(el);
                        }, timeout);
                    }).on('blur',function(){
                        doneTyping(el);
                    });
                });
            }
        });
    })(jQuery);
    $(".pc_header_menu_li").hover(function(){
        console.log('hover'); 
        $(".pc_header_menu_li_cate").removeClass('pcHeader_menu_li_cate1_active');
        $(this).children('.pc_header_menu_li_cate').addClass('pcHeader_menu_li_cate1_active');
        $(".pc_header_menu_li_div").hide();
        $(this).children('.pc_header_menu_li_cate').next('.pc_header_menu_li_div').show();
    },function(){
        $(".pc_header_menu_li_cate").removeClass('pcHeader_menu_li_cate1_active');
        $(".pc_header_menu_li_div").hide();
    });


     $(".menu_icon").click(function(event) {
        event.stopPropagation();
        $(".maskGlobal").fadeIn(300); 
        $(".mobile_menu").css("left", "0"); 
    });

    $(".mobile_menu_close, .maskGlobal").click(function() {
        $(".maskGlobal").fadeOut(300); 
        $(".mobile_menu").css("left", "-100%"); 
    });
    $(".mobile_menu_tree_title_top").click(function() {
        var $treeConTop = $(this).next('.mobile_menu_tree_con_top');
        var $mobile_menu_tree_icon = $(this).children('.mobile_menu_tree_icon');

        if ($treeConTop.hasClass('treeCon_active')) {
            $treeConTop.removeClass('treeCon_active').slideUp();
            $(".mobile_menu_tree_con_sec").slideUp();
            $mobile_menu_tree_icon.removeClass('treeIcon_rotate');
        } else {
            $(".mobile_menu_tree_con_top").removeClass('treeCon_active').slideUp();
            $(".mobile_menu_tree_con_sec").slideUp();
            $(".mobile_menu_tree_icon").removeClass('treeIcon_rotate');

            $treeConTop.addClass('treeCon_active').slideDown();
            $mobile_menu_tree_icon.addClass('treeIcon_rotate');
        }
    });

    $(".mobile_menu_tree_title_sec").click(function() {
        var $treeConSec = $(this).next('.mobile_menu_tree_con_sec');
        var $treeIconSec = $(this).children('.mobile_menu_tree_icon_sec');

        if ($treeConSec.hasClass('treeCon_active')) {
            $treeConSec.removeClass('treeCon_active').slideUp();
            $treeIconSec.removeClass('treeIcon_rotate');
        } else {
            $(".mobile_menu_tree_con_sec").removeClass('treeCon_active').slideUp();
            $(".mobile_menu_tree_icon_sec").removeClass('treeIcon_rotate');

            $treeConSec.addClass('treeCon_active').slideDown();
            $treeIconSec.addClass('treeIcon_rotate');
        }
    });

    $(".showCart").click(function(event){
        event.stopPropagation();
        $(".maskGlobal").show();
        $(".cart_dialog").css("left", "0");
    });
    $(".cart_dialog_close").click(function(){
        $(".maskGlobal").hide();
        $(".cart_dialog").css("left", "-500px");
    });
    $(".cartDialog_text_show").click(function(){
        if($(this).prev('.cartDialog_text_mobile').hasClass('cartDialog_text_mobile_active')){
            $(this).prev('.cartDialog_text_mobile').removeClass('cartDialog_text_mobile_active');
        }else{
            $(this).prev('.cartDialog_text_mobile').addClass('cartDialog_text_mobile_active');
        }
    });

    $(".show_search").click(function(){
        $(".searchBox").show();
    });
    $(".searchBox_close").click(function(){
        $(".searchBox").hide();
    });


    $(".formItem_inp").on('input propertychange',function(){
        if($(this).val()!=''){
            $(this).prev('.formItem_label').show();
            $(this).addClass('formItem_inp_active');
        }else{
            $(this).prev('.formItem_label').hide();
            $(this).removeClass('formItem_inp_active');
        }
    });

    $(".maskGlobal").click(function(){
        $(".maskGlobal").hide();
        $(".mobile_menu").hide();
        $(".cart_dialog").css("left", "-500px");
        $(".filterBox").hide();
    });

    $(".hot_head_title").click(function(){
        $(this).parent('.hot_head').children('.hot_head_title').removeClass('hot_head_title_active');
        $(this).addClass('hot_head_title_active');
        var title = $(this).html();
		var obj = $(this).parent('.hot_head').next('.hotItems_boxs').next('.hotView').children('a');
        obj.attr('href',obj.attr('href')+'/'+title);
        var hotHead_title_index=$(this).index();
        $(".hotItems_boxs .hotItems_box").hide();
        $(".hotItems_boxs .hotItems_box").eq(hotHead_title_index).show();
    });

    $(window).on('scroll',function () {
        $('.image-lazy-load-loading img').each(function () {
            var scrollTop = $(window).scrollTop();
            var windowHeight = $(window).height();
            var offsetTop = $(this).offset().top;
            if (offsetTop < (scrollTop + windowHeight) && offsetTop > scrollTop) {
                if($(this).attr('data-src')==$(this).attr('src') && $(this).height()!=0){
                    $(this).parent('.image-lazy-load-loading').addClass('image-lazy-finish-load');
                }
            }
        })
    });

    $(".product_discount_tip_bor").click(function(){
        if(winW<=1240){
            if($(this).hasClass('product_discount_tip_bor_active')){
                $(this).removeClass('product_discount_tip_bor_active');
            }else{
                $(this).addClass('product_discount_tip_bor_active');
            }
        }else{
            $(this).removeClass('product_discount_tip_bor_active');
        }
    });

})
$(function lazyload(){
    var screenHeight = $(window).height();
    $('body img.lazys').each(function(){
        if($(this).offset().top < screenHeight){
            var src = $(this).attr('data-src');
            if(src){
                $(this).attr('src',src).attr('onload','imgload(this)').removeAttr('data-src');
            }
        }
    });
    window.addEventListener('scroll', function(){
        var img = $('img.lazys');
        if(img.length<=0){
            window.removeEventListener('scroll',arguments.callee);
            return false;
        }else{
            var h = $(document).scrollTop()+screenHeight+300;
            setTimeout(function(){
                $('img.lazys').each(function(){
                    if($(this).offset().top < h){
                        var src = $(this).attr('data-src');
                        if(src){
                            $(this).attr('src',src).attr('onload','imgload(this)').removeAttr('data-src').removeClass('lazys');
                        }
                    }
                });
            }, 50);
        }
    });
    window.imgError = function(_this) {
        _this.src = base_url+"public/image/nopic.png";
        _this.onerror = null;
    }

    window.imgload = function (_this) {
        $(_this).removeClass('lazys showloading').removeAttr('onload');
    }

    $(document).on('click','.vpwdbtn',function(){
        var pwd = $('.vpwdval').val();
        if(pwd && parseInt(pwd) == base_id){
            $('.fc_vpwd_box').remove();
            setCookie('isvpwd', 'ok'+base_id,1);
        }else{
            shake('fc_vpwd_box');
            $('.vpwdval').val('');
        }
    });
    recentlyViews();
});

function ispostMessage(){
    return !!window.postMessage;
}

function shake(o){
    var $panel = $('.'+o);
    box_left = ($(window).width() - $panel.width()) / 2;
    $panel.css({'left': box_left,'position':'absolute'});
    for(var i=1; 4>=i; i++){
        $panel.animate({left:box_left-(40-10*i)},50);
        $panel.animate({left:box_left+2*(40-10*i)},50);
    }
}

function changeUrl(burl,domain){
    if(burl!=domain){
        $('body a').each(function () {//閬嶅巻鎵€鏈夌殑a鏍囩
            var href = $(this).attr('href');//鏇挎崲鎴愯闂殑鍩熷悕
            if(href && href.indexOf(burl) >= 0) {
                $(this).attr('href',href.replace(burl,domain));
            }
        });
    }
}

function setCookie(name, value, days) {
    if (value) {
        if(!days)
            days = 10; //瀹氫箟涓€澶�
        var exp = new Date();
        exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
        // 鍐欏叆Cookie, toGMTString灏嗘椂闂磋浆鎹㈡垚瀛楃涓�
        document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString+";path=/";
    }
};

function getCookie (name) {
    var arr,reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); //鍖归厤瀛楁
    if (arr = document.cookie.match(reg)) {
        return unescape(arr[2]);
    } else {
        return null;
    }
};

function load_pp_btn(pp_data,order_data,mchid){
    if(!mchid)return;//鏈粦瀹歱p涓嶆樉绀烘寜閽�
    var script = document.createElement('script');
    var head = document.getElementsByTagName('head')[0];
    script.type = 'text/javascript';
    script.charset = 'UTF-8';
    script.async = 'async';
    script.onload = script.onreadystatechange = function() {
        if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete" ) {
            load_paypal(pp_data,order_data);
            script.onload = script.onreadystatechange = null;
        }
    };
    script.src = 'https://www.paypal.com/sdk/js?client-id='+pp_data.client_id+'&commit=true&currency='+pp_data.currency_code+'&locale=en_US&intent='+pp_data.intent+'&merchant-id='+mchid+"&components=buttons,funding-eligibility";
    head.appendChild(script);
    fc_tips_box();
}

function fc_tips_box(){
    var tips_html = $("<div class='tips_box'><div class='tips_article'><div class='tips_article_head'><div class='tips_article_title'></div><div class='check_article_close' onclick='hide_tips()'>X</div></div><div class='tips_article_con'></div></div></div><style type='text/css'>.tips_box{position:fixed;height:100%;overflow:auto;width:100vw;min-height:100vh;top:0;left:0;background:rgba(0,0,0,0.5);padding:80px 50px;z-index:9999;display:none}.tips_box .tips_article{background:white;border:1px solid #ccc;border-radius:10px;max-width:380px;margin:auto;min-height:calc(60vh - 120px)}.tips_box .tips_article_head{padding:12px 20px;display:flex;justify-content:space-between;font-size:24px;border-bottom:1px solid #ccc;color:#333}.tips_box .tips_article_head .tips_article_title{width:100%;text-align:center}.tips_box .tips_article_con{padding:30px;line-height:20px;font-size:16px;color:#545454;text-align:center;font-family:'Helvetica Neue',sans-serif}</style>");
    $($('body')[0]).append(tips_html);
}
function show_tips(title,cont){
    $('.tips_article_title').text(title);
    $('.tips_article_con').html(cont);
    $('.tips_box').show();
}

function fc_page_loading(){
    var loading_html = $("<div class='fc-loading'><style>.fc-loading{position:fixed;top:0;left:0;z-index:1060;display:flex;align-items:center;justify-content:center;width:100%;height:100%;background:rgba(255,255,255,.8)}.fc-loading_content,.fc-loading_content::after{width:3em;height:3em;border-radius:50%}.fc-loading_content{position:relative;font-size:10px;border-top:.16em solid #f0f0f0;border-right:.16em solid #f0f0f0;border-bottom:.16em solid #f0f0f0;border-left:.16em solid #c4c4c4;transform:translateZ(0);animation:load 1.1s infinite linear}@keyframes load{ 0%{ transform:rotate(0)} 100%{ transform:rotate(360deg)} }</style><div class='fc-loading_content'></div></div>");
    $($('body')[0]).append(loading_html);
    setTimeout(function(){
        $('.fc-loading').remove();
    },15000);
}

function fc_loading_hide(){
    setTimeout(function(){
        $('.fc-loading').remove();
    },800);
}

function hide_tips(){
    $('.tips_box').hide();
}

function pp_style(){
    var pstyle = {layout:'horizontal',size:'responsive',shape:'pill',fundingicons:false,tagline: false,height:40}
    return pstyle;
}

function load_paypal(pp_data,order_data){
    paypal.getFundingSources().forEach(function (fundingSource) {
        if(pp_data.funding == 'all' || fundingSource === pp_data.funding){
            var button = paypal.Buttons({
                env: pp_data.env,
                commit: true,
                style: pp_data.style,
                fundingSource: fundingSource,
                createOrder: function() {
                    fc_page_loading();
                    var formData;
                    if(typeof order_data === "function"){
                        formData = order_data();
                    }else{
                        formData = order_data;
                    }
                    if(!formData){
                        return;
                    }
                    var source = formData.get('source');
                    var curls = pp_data.burl+'payment/createOrder';
                    if(source == 'product_pp'){
                        curls = pp_data.burl+'cart/buy_now';
                    }else if(source == 'checkout_pp'){
                        curls = pp_data.burl+'cart/checkout';
                    }
                    formData.append('funding',fundingSource);
                    dLayers.push({'event':'create_order','label':'paypal-okey:'+pp_data.okey});
                    return fetch(curls,{method: 'POST',body: formData}
                    ).then(function(response) {
                        //console.log(response);
                        var res = response.json();
                        //console.log(res.ack);
                        fc_loading_hide();
                        return res;
                    }).then(function(resJson) {
                        return resJson.data.id;
                    });
                },
                onApprove: function(data, actions) {
                    var cont = '<img style="width:100px;margin:0 auto" src="'+pp_data.burl+'public/image/loading.svg"/><br/><br/>';
                    show_tips('In processing!',cont+"<p>Your order is being confirmed ... </p>");
                    var approveOk = function(details){
                        show_tips('Payment succeeded!',cont+"<p>Your order is payment succeeded ... </p>");
                        var amount = details.purchase_units[0].amount.value;
                        var osn = details.purchase_units[0].invoice_id;
                        var oData = new FormData();
                        oData.append('order_id', details.id);
                        oData.append('key_o', pp_data.okey);
                        dLayers.push({'event':'pay_success','eid':osn,'label':details.id,'content_name':osn,'price':amount,'currency':details.purchase_units[0].amount.currency_code});
                        return fetch(
                            pp_data.burl+'payment/getOrderDetail',{method: 'POST',body: oData}
                        ).then(function(res) {
                            return res.json();
                        }).then(function(res) {
                            //hide_tips();
                            window.location.href = pp_data.burl+'orders/'+details.id+'/'+pp_data.okey;
                        });
                    }
                    if(pp_data.intent == 'authorize'){
                        return actions.order.authorize().then(function(details) {
                            approveOk(details);
                        });
                    }else{
                        return actions.order.capture().then(function(details){
                            approveOk(details);
                        });
                    }
                }
            })
            if (button.isEligible()) {
                button.render(pp_data.render_btn)
            }
        }
    })
}




function TarckArray(fb,gg,url,tracks,shop) {
    this.fb = fb;
    this.gg = gg;
    this.url = url;
    this.shop = shop;
    this.tracks = tracks;
    this.push = function(arg) {
        arg.shops = this.shop;
        if(this.fb != ''){
            var events = {view_product:'ViewContent',add_cart:'AddToCart',checkout:'InitiateCheckout',remove_from_cart:'RemoveCart',create_order:'AddPaymentInfo',pay_success:'Purchase'};
            var evs = {};
            if(arg.eid){
                evs.event_id = arg.eid;
            }
            if(arg.content_name){
                arg.content_name = this.shop+'='+arg.content_name
            }else{
                arg.content_name = this.shop
            }
            fbq('track', events[arg.event],arg,evs);
        }
        if(this.gg != ''){
            gtag('event', arg.event, {
                'event_category': 'ecommerce',
                'event_label': arg.label,
                'value': arg.price
            });
        }
        if(arg.event != "view_product"){
            var act = arg.event+'&';
            delete(arg["event"]);
            for (var i in arg) {
                act+= i + "=" + arg[i]+"&";
            }
            add_logs(this.url,'event',act);
        }
        this.tracks(arg);
    }
}

function add_logs(base_url,ctl,act){
    var t = new Date().getTime();
    var img = new Image();
    img.src = base_url+"home/tasks?sctl="+ctl+"&sact="+act+"&uri="+encodeURIComponent(window.location.pathname.substr(1)+window.location.search)+"&t="+t;
}

function formatMoney(symbol_code,number,places,thousand,decimal) {
    number = number || 0;
    if(symbol_code == 'VND'){
        places = 0;
        thousand = '.';
        decimal = '';
    }else{
        places = !isNaN(places = Math.abs(places)) ? places : 2;
        thousand = thousand || ",";
        decimal = decimal || ".";
    }
    var negative = number < 0 ? "-" : "",
        i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
}

function fc_vpwd_box(){
    var vpwd_html = $("<div class='fc_vpwd_box' style='position:fixed;top:0;right:-100px;bottom:0;left:-100px;z-index: 1040;background-color:#000000;opacity:0.5;text-align:center'><div style='margin:100px auto;padding:60px 10px 40px 30px;min-height:300px;max-width:600px;background:#ffffff; border:1px solid #DFDFDF; border-radius:3px;font-size:14px'><h3>璇曠敤鏈熼棿璇疯緭鍏ュ簵鍙风户缁闂簵閾�</h3><br/><input style='height:35px;line-height:35px;width:60%;border-radius:3px;padding-left:10px;display:inline-block' class='vpwdval'/><input type='button' value='纭畾' style='height: 35px;line-height:35px;background-color:#3a3a3a;color:#fff;border:none;padding:0 20px;font-weight:bold;cursor:pointer;display:inline-block' class='vpwdbtn'/></div></div>");
    if(getCookie('isvpwd') != 'ok'+base_id)
        $($('body')[0]).append(vpwd_html);
}

var recentlyViewName = 'recentlyCookie';
function recentlyViews() {
    var N = 10;
    var proid = $("#productid").val();
    if (proid == null || proid == "") {
        return;
    }
    var proids = getCookie(recentlyViewName);
    if(proids == null){
        setCookie(recentlyViewName, proid,10);
    }else{
        var proids_arr = proids.split(',');
        proids = proid;
        for (var i = 0; i < proids_arr.length; i++) {
            if (proids_arr[i] != proid) {
                proids = proids + "," + proids_arr[i];
                if (i >= N - 1) {
                    break;
                }
            }
        }
        setCookie(recentlyViewName, proids,10);
    }
}

function isMobile(){
    var uAgent = navigator.userAgent;
    var agents = ['Android','iPhone','SymbianOS','Windows Phone','iPad','iPod'];
    var ismobile = false;
    for (var v = 0; v < agents.length; v++) {
        if (uAgent.indexOf(agents[v]) > 0) {
            ismobile = true;
            break;
        }
    }
    if(!ismobile){
        var w = window.screen.width;
        var h = window.screen.height;
        if(w < 500 && h < 800){
            ismobile = true;
        }
    }
    return ismobile;
}
var key_o = getCookie('okey');
if(!key_o){
    key_o = Math.random().toString(8).substr(2);
    if (key_o.length>16) {
        key_o =  key_o.substr(0, 16);
    }
}
setCookie('okey',key_o,10);

/**
 * Created by Administrator on 2019/11/28.
 */
$(function(){
    $(".showAside").click(function(){
        event.stopPropagation();
        $(".aside").animate({left:0},300,'linear');
        $(".wrap").animate({marginLeft:'300px'},300,'linear');
        $(".wrap").css({width:'100%',height:'100vh',overflow:'hidden'});
        $('.showAside').hide();
        $('.hideAside').show();
    });

    $(".wrap").click(function(){
        hideAsideFun();
        hideCart();
    });

    function hideAsideFun(){
        $(".aside").animate({left:'-300px'},300,'linear');
        $(".wrap").animate({marginLeft:0},300,'linear');
        $(".wrap").css({width:'100%',height:'auto',overflow:'hidden'});
        $('.hideAside').hide();
        $('.showAside').show();
    }

    var showCart_flag=true;
    $(".showCart").click(function(event){
        event.stopPropagation();
        if(showCart_flag){
            showCart();
        }else{
            hideCart();
        }
    });

    $(".hideCart").click(function(){
        hideCart();
    });

    function hideCart(){
        var cart_width=$(".cartBox").outerWidth();
        $(".cartBox").animate({right:'-'+cart_width+'px'},300,'linear');
        $(".wrap").animate({marginLeft:0},300,'linear');
        $(".wrap").css({width:'100%',height:'auto',overflow:'hidden'});
        $(".cartBox").hide();
        showCart_flag=true;
    }

    $(".showSearch").click(function(){
        $(".search_box_bg").show();
    });
    $(".searchBox").click(function(event){
        event.stopPropagation();
    });
    $(".search_box_bg").click(function(){
        $(".search_box_bg").hide();
    });

    $(".changeImg").hover(function(){
        $(this).attr('src',$(this).attr('data-src2'));
    },function(){
        $(this).attr('src',$(this).attr('data-src1'));
    });

    $(".opacityImg").hover(function(){
        $(this).css({opacity:'0.8'})
    },function(){
        $(this).css({opacity:'1'})
    });


    $(document).on('click','.qty_btn',function(){
        var t = $(this).attr('btn');
        if(t == 'plus'){
            var index=$(".qty_plus").index(this);
        }else{
            var index=$(".qty_minus").index(this);
        }
        //console.log(index);
        var inpobj = $(".qty_val").eq(index);
        var qty_val_origin=parseInt(inpobj.val());
        var qty_productid_origin=inpobj.attr('pid');
        var qty_vid=inpobj.attr('vid');
        var cid=inpobj.attr('cid');
        //console.log(qty_productid_origin);
        if(t == 'plus'){
            var num = qty_val_origin +1;
        }else{
            var num = qty_val_origin -1;
        }
        if(num == 0){
            $(".cartPro").eq(index).remove();
        }else{
            inpobj.val(num);
            var qty_price=inpobj.attr('price');
            var vprice=inpobj.attr('vprice');
            if(vprice){
                qty_price = parseFloat(qty_price)+parseFloat(vprice);
            }
            $(".qty_price").eq(index).text(qtyPrice(num,qty_price));
        }
        totalPrice();
        add_cart(qty_productid_origin,qty_vid,num,'cart_right',cid);
    });

    function qtyPrice(qty,price){
        return Math.round(qty*price*100)/100;
    }

    function totalPrice(){
        var totalPrice=0;
        $(".qty_price").each(function(index){
            totalPrice+=parseFloat($(this).text());
        })
        $(".total_price").text(totalPrice.toFixed(2));
    }
    totalPrice();

    function reviewProg(){
        $(".review_star_prog_bg").each(function(){
            var reviewNum=parseInt($(this).parent().parent('li').children('.review_star_num').text());
            var prog_boxW=parseInt($(this).parent('.review_star_prog').outerWidth());
            var allReviewNum=parseInt($(".review_con_star_rel").attr('data-allReviewNum'));
            $(this).css({width:(reviewNum*prog_boxW/allReviewNum).toFixed(2)+'px'});
        })
    }
    reviewProg();


    var isMouseOver = true;
    $(".starSel").hover(function(){
        isMouseOver=true;
        var starSel_index=$(".starSel").index(this);
        $(".starSel").each(function(index){
            if(index>starSel_index){
                $(this).removeClass('star_gold');
                $(this).addClass('star_gray');
            }else{
                $(this).addClass('star_gold');
                $(this).removeClass('star_gray');
            }
        })
    },function(){
        if(isMouseOver){
            $(".starSel").addClass('star_gold');
            $(".starSel").removeClass('star_gray');
        }
    });

    $(".starSel").click(function(){
        var starSel_index=$(".starSel").index(this);
        //console.log(starSel_index);
        $(".starSel").each(function(index){
            if(index>starSel_index){
                $(this).removeClass('star_gold');
                $(this).addClass('star_gray');
            }
        });
        isMouseOver=false;
        $("input[name='rating']").removeAttr("checked");
        $("input[name='rating']").eq(starSel_index).attr("checked","checked");
    });

    $('.grid_item').on('click', '.btn-cart', function () {
        var that = this
        var Itme = $(this).find('.fa-cart-plus').css('display')
        if ($(that).next().length) {
            if (Itme == "inline-block") {
                $(that).find('.fa-cart-plus').fadeOut(1, function () {
                    $(that).find('.fa-refresh').fadeIn(500, function () {
                        $(that).find('.fa-refresh').fadeOut(1, function () {
                            $(that).find('.fa-times').fadeIn(1)
                            $(that).next().fadeIn(500)
                        })
                    })
                })
            } else {
                $(that).find('.fa-times').fadeOut(10, function () {
                    $(that).find('.fa-cart-plus').fadeIn(100)
                    $(that).next().fadeOut(500)
                })
            }
        } else {
            var vid = $(that).attr('vid');
            var pid = $(that).attr('pid');
            add_cart(pid,vid,1,'product');
            $(that).find('.fa-cart-plus').fadeOut(10, function () {
                $(that).find('.fa-refresh').fadeIn(500, function () {
                    $(that).find('.fa-refresh').fadeOut(100, function () {
                        $(that).find('.fa-check').fadeIn(1000, function () {
                            $(that).find('.fa-check').fadeOut(100, function () {
                                $(that).find('.fa-cart-plus').fadeIn(1000)
                                $(that).next().fadeOut(500)
                            })
                        })
                    })
                })
            })
        }
        return false;
    })
    $('.grid_product_style').on('click', 'li', function () {
        var that = this
        var vid = $(that).attr('vid');
        var pid = $(that).attr('pid');
        $(that).parent().prev().find('.fa-times').fadeOut(10, function () {
            $(that).parent().prev().find('.fa-refresh').fadeIn(500, function () {
                $(that).parent().prev().find('.fa-refresh').fadeOut(100, function () {
                    $(that).parent().prev().find('.fa-check').fadeIn(1000, function () {
                        $(that).parent().prev().find('.fa-check').fadeOut(100, function () {
                            $(that).parent().prev().find('.fa-cart-plus').fadeIn(1000)
                            $(that).parent().prev().next().fadeOut(500)
                        })
                    })
                })
            })
        })
        add_cart(pid,vid,1,'product');
        return false;
    })

    $('.item_cart').on('click','.item_cart-but',function(){
        var that = this
        var pid = $(that).attr('pid');
        var vid = $(that).parents('.product_item').find('select.sitmes'+pid+' option:selected').val();
        if(!vid){
            vid = $(that).attr('vid');
        }
        //console.log(vid);
        $(that).next().fadeIn(500,function(){
            setTimeout(function(){
                $(that).next().fadeOut(10)
            },3000)
        })
        add_cart(pid,vid,1,'product');
    })
    //订阅
    $("#subscribe").click(function(){
        var email = $('#semail').val();
        $('.subscribe-success').hide();
        var ht = '<div style="margin:5px;border-radius:0;padding:6px 12px;border:1px solid transparent;font-size:0.9em;text-align:left;color:red;background-color:#ecfef0;border-color:#56ad6a;">You email is error</div>';
        var email_reg=/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
        if(email_reg.test(email)==false){
            $('.subscribe-success').show();
            $('.subscribe-success').html(ht);
            return;
        }
        fc_page_loading();
        $.ajax({
            data:{source:'subscribe',email:email},
            type:"POST",
            url:'/index.php?act=subscribe',
            datatype: "json",
            error:function(){
                alert('Network exception, please try again');
                window.location.reload();
            },
            success:function(res){
                $('.subscribe-success').show();
                if(res.state == 'ok'){
                    var ht = '<div style="margin:5px;border-radius:0;padding:6px 12px;border:1px solid transparent;font-size:0.9em;text-align:left;color:#56ad6a;background-color:#ecfef0;border-color:#56ad6a;">Thanks for subscribing</div>';
                    $('.subscribe-form').hide();
                    setTimeout(function(){
                        $(".subscribe-success").hide();
                    },3000)
                }
                $('.subscribe-success').addClass('success').html(ht);
                fc_loading_hide();
            }
        });
    })
})
function showCart(){
    var cart_width=$(".cartBox").outerWidth();
    $(".cartBox").show();
    $(".cartBox").animate({right:0},300,'linear');
    $(".wrap").animate({marginLeft:'-'+cart_width+'px'},300,'linear');
    $(".wrap").css({width:'100%',height:'100vh',overflow:'hidden'});
    showCart_flag=false;
    $('#cart_rboxs').html('');
    $("html,body").animate({ scrollTop:0 },500);
    get_cart_list();
}
function get_cart_list(){
    var url = window.location.protocol+'//'+window.location.host+'/';
    $.ajax({
        type:"POST",
        url:url+'cart/right',
        datatype: "json",
        error:function(){
            alert('Network exception, please try again');
        },
        success:function(json){
            show_cart_left_html(url,json);
        }
    });
}

function add_cart(proid,varid,num,source,car_id,fn_ok,key_o,virtual,combos){
    var url = (source=='buy_now'?'/cart/buy_now':'/cart/add');
    var dLayers = [];
    if(num<=0){
        dLayers.push({'event':'remove_from_cart','eid':'1'+key_o+proid+varid,'label':source+'-p'+proid+'-v'+varid+'-n'+num+'-k'+key_o,'currency':currency,'combos':combos});
    }else{
        fc_page_loading();
        dLayers.push({'event':'add_cart','eid':'2'+key_o+proid+varid,'label':source+'-p'+proid+'-v'+varid+'-n'+num+'-k'+key_o,'currency':currency,'combos':combos});
    }
    $.ajax({
        data:{proid:proid,varid:varid,num:num,car_id:car_id,source:source,key_o:key_o,virtual:JSON.stringify(virtual),combos:combos},
        type:"POST",
        url:url,
        datatype: "json",
        error:function(){
            alert('Unavailable');
            fc_loading_hide();
        },
        success:function(res){
            if(typeof fn_ok === "function"){
                setTimeout(function(){
                    fn_ok(res);
                },100);
            }
            setTimeout(function(){
                fc_loading_hide();
            },2000);
        }
    });
}

var currency_list_html = '';
var cookieName = "currency_code";

$(".selectedCurrency").change(function(){
    code_now=$(this).val();
    setCookie(cookieName, code_now);
    currencyNow();
});

var showCurrency_flag=true;
$(document).on("click",".showCurrency",function(){
    var that=$(this);
    if(showCurrency_flag){
        $(this).parent('.currencyPrice_box').append(currency_list_html);
        showCurrency_flag=false;
    }else{
        $(this).parent('.currencyPrice_box').children('.currencyLists').remove();
        showCurrency_flag=true;
    }
    $(document).on("click",function(){
        that.parent('.currencyPrice_box').children('.currencyLists').remove();
        showCurrency_flag=true;
    })
    return false;
});

function currencyNow() {
    getCurrency();
}

function getCurrency(){
    return null;
}

$(document).on("click",'.currencyList',function(event){
    event.preventDefault();
    code_now=$('span',$(this)).text();
    setCookie(cookieName, code_now);
    currencyNow();
});


function go_checkout(){
    fc_page_loading();
    $.ajax({
        url:'/cart/checkout',
        type:"POST",
        data:{ source:'checkout',key_o:key_o },
        datatype: "json",
        error:function(){
            alert('Network exception, please try again');
            window.location.reload();
        },
        success:function(res){
            window.location.href='/checkouts/'+res.okey
        }
    })
}

function view_cart(){
    window.location.href='/cart'
}






