
var data_discount = null;
var AT_DELIVERY_PRICE = 0;
$(document).ready(function(){
   
    
    $(".bgh-menu > div, .bgh-menu .bgh-button").on("click",function(){
        var cat = $(this).data("idcategory");
        //$(".category").hide();
        $(".bgh-menu div").removeClass("active");
        //console.log(".category-"+cat);
        

        var scrollTo = $("#category-border-"+cat);
        var container = $('.bgh-body-container');
        var position = scrollTo.offset().top - container.offset().top + container.scrollTop();
        console.log(position+" >ofset "+container.offset().top);
        container.animate({
            scrollTop: position
        });
        $("#menu-"+cat).addClass("active");
        $("#title-cart #menubar").trigger("click");
    });

    $("#search-on-home input").on("keyup",function(){
        var ky = $(this).val().toLowerCase();
        $(".category").show();
        $(".product-card").each(function(){
            var name = $(this).find(".product-name").html().toLowerCase();
            if(name.includes(ky)){
                $(this).show();
            }else{
                $(this).hide();
            }
        })
    });

    
    $(".bgh-body").swipe( {        
        swipeRight:function(event, direction, distance, duration, fingerCount, fingerData) {
           
            if($("#fp-cart").hasClass("force")){
                force_the_cart();
            }else{
                if($("#top-menu").hasClass("show-up")){
                    $("#title-cart #menubar").trigger("click");
                 }
                fp_hide_boba();     
            }
        },
        swipeLeft:function(event, direction, distance, duration, fingerCount, fingerData) {
           

            if($("#fp-cart").hasClass("force")){
                force_the_cart();
            }else{
                $("#title-cart  #menubar").trigger("click");   
            }
        },
        threshold:2
    });
    /*
    $("#top-menu").swipe({
        swipeRight:function(event, direction, distance, duration, fingerCount, fingerData) {
            if($("#fp-cart").hasClass("force")){
                force_the_cart();
            }else{
                $("#title-cart #menubar").trigger("click");   
            }
        },
        swipeLeft:function(event, direction, distance, duration, fingerCount, fingerData) {
            
        },
        threshold:2
    });*/

    $("#fp-cart").swipe({
        swipeRight:function(event, direction, distance, duration, fingerCount, fingerData) {
            
        },
        swipeLeft:function(event, direction, distance, duration, fingerCount, fingerData) {
            if($("#fp-cart").hasClass("force")){
                force_the_cart();
            }else{
                fp_hide_boba();
            }            
        },
        threshold:2
    });

    if(screen.width<=760){
        $("#fp-payment-container").swipe( {    
            swipeRight:function(event, direction, distance, duration, fingerCount, fingerData) {
                force_the_cart();
            },
            swipeLeft:function(event, direction, distance, duration, fingerCount, fingerData) {
                force_the_cart();
            },
            threshold:2
        });    
    }

});


function share_product(id_items){
    alert(id_items);
}



var isDownY3 = false;
var startY3;
var scrollTop3;
var slider3;
function adding_product_scroll(){
    slider3 = document.querySelector('#fp-product .bgh-body-container');
    slider3.addEventListener('mousedown', (e) => {
        console.log("MOUSE DOWN");
        isDownY3 = true;
        startY3 = e.pageY - slider3.offsetTop;
        scrollTop3 = slider3.scrollTop;
      });
      slider3.addEventListener('mouseleave', () => {
        isDownY3 = false;
      });
      slider3.addEventListener('mouseup', () => {
        isDownY3 = false;
      });
      slider3.addEventListener('mousemove', (e) => {
        if(!isDownY3) return;
        e.preventDefault();
        const x = e.pageY - slider3.offsetTop;
        const walk = (x - startY3) * 1; //scroll-fast
        slider3.scrollTop = scrollTop3 - walk;
      });
}

var BODY_AFTER_DRAG = false;
function show_product(id_items){
    if(BODY_AFTER_DRAG){
        console.log("after drag BODY");
        BODY_AFTER_DRAG=false;
        return;
    }
    var data = boba.getRegulerData();
    data['action'] = "fp-product";
    data['id_items'] = id_items;
    showLoading();
    $.post("",data,function(res){
        $("#fp-product-container").html(res);
        $("#fp-home").hide();
        $("#fp-cart .bgh-footer").hide();
        $("#fp-product-container").show();
        adding_product_scroll();
        dismissLoading();
    });
}

function show_product_mod(id_items,mod){
    var data = boba.getRegulerData();
    data['modifier'] = mod.split(",");
    data['action'] = "fp-product";
    data['id_items'] = id_items;
    showLoading();
    $.post("",data,function(res){
        $("#fp-product-container").html(res);
        $("#fp-home").hide();
        $("#fp-cart .bgh-footer").hide();
        $("#fp-product-container").show();
        adding_product_scroll();
        dismissLoading();
    });
}

function slide_main(num){
    $('#top-menu').animate({scrollLeft : '+='+num});
}

function slide_body(num){
    $('.bgh-body-container').animate({scrollTop : '+='+num}); 
}

function slide_idx(num,idx){
    $('#'+idx).animate({scrollLeft : '+='+num});  
    //document.getElementById('').scrollLeft += num;
    //$("#top-menu").scrollLeft(num);
    //document.getElementById('container').scrollLeft += 20;
}

function increment(coded,increment){
    var qt = Number(ALL_PRODUCT_LIST[coded].quantity);
    qt += Number(increment);
    if(qt<1){
        qt = 1;
    }
    ALL_PRODUCT_LIST[coded].quantity = qt;
    reload_cart();
    reloading_payment_cart();
}

function increment_item(increment){
    var num = Number($("#quantity").val());
    num +=  increment;
    if(num<1){
        num = 1;
    }
    $("#quantity").val(num);

}

function __setCookie(name,value,days) {
    let id_branch = $("#boba_id_branch").val();
    if(id_branch!=""){
        name = name+"_"+id_branch;
    }

    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}

function openit(element){
    var event;
    event = document.createEvent('MouseEvents');
    event.initMouseEvent('mousedown', true, true, window);
    element.dispatchEvent(event);
}

function pickit(e){
    var val = $(e).val();
    var id = $(e).data("id");
    ALL_PRODUCT_LIST[id]["dc"] = val;
    reload_cart();
    reloading_payment_cart();
}

function generate_dc(curval,id){
    if(data_discount==null){
        data_discount = $.parseJSON($("#list-discount").html());
        console.log(data_discount);
    }
    let html = "<span class='dc-cart'><select class='open-in-it' onclick='openit(this)' onchange='pickit(this)' data-id='"+id+"'  id='dc_"+id+"'>";
    $(data_discount).each(function(x,y){
        console.log(y);
        let name = y.name;
        let vals = y.value;
        html += "<option value='"+vals+"' "+(curval==vals?"selected='selected' ":"")+" >"+name+"</option>";
    });
    html += "<option value='0' "+(curval==0?"selected='selected' ":"")+" > - Please Select Discount- </option>";
    html += "</select></span>";
    return html;
}

function reload_cart(){
    console.log("===>RELOAD CART ("+Array.isArray(ALL_PRODUCT_LIST)+") <====");
    if(Array.isArray(ALL_PRODUCT_LIST)){
        ALL_PRODUCT_LIST = {};
    }
    console.log(ALL_PRODUCT_LIST);
    console.log("====>END RELOAD CART<=====");
    
    var html = "";
    var total = 0;  
    var points = 0;
    var count = 0;
    

    $.each(ALL_PRODUCT_LIST,function(i,x){
        console.log("EACH "+i);
        html += "<div>";
        html += "<h5 data-coded="+x.coded+" class='name'>"+x.name+" @$"+x.total;
        html += " <div class='noted'>"+x.noted+"</div>";
        html += "</h5>";

    

        var subtt = (x.total*x.quantity);    
        var dsc = x.dc * subtt/100;
        subtt = subtt-dsc;

        var subpoints = 0;
        if( !(typeof(x['points']) === "undefined") ){
            subpoints = (x.points*x.quantity);
        }
        points += subpoints;
        

        html += generate_dc(x.dc,x.coded);
        html += "<h5 class='quantity'><i class='fa fa-plus' onClick=\"increment('"+x.coded+"',1)\"></i> &nbsp; "+x.quantity+" &nbsp;<i class='fa fa-minus' onClick=\"increment('"+x.coded+"',-1)\"></i> </h5>";
        html += "<h5 class='price'> $"+subtt.toFixed(2)+"</h5>";
        html += "<h5 class='remove-btn' onclick=\"fp_remove_cart('"+x.coded+"')\" ><i class='fa fa-trash'></i></h5>";
        
        
        html += "</div>";
        //var one_total = x.total*x.quantity;
        
        total += Number(subtt.toFixed(2));
        count += Number(x.quantity);
    });
    console.log("HTML CART ===> "+html);
    total = total.toFixed(2);
    var tax = getTax(total);
   

    $("#bgh-total-cart h3#subtotal").html("$"+total);
    $("#bgh-total-cart h3#delivery").html("$"+AT_DELIVERY_PRICE );
    
    $("#bgh-total-cart h3#tax").html("$"+tax);
    var ttl = Number(tax)+Number(total)+Number(AT_DELIVERY_PRICE);

    var mtp = Number($("#boba_mtp").val());
    var ptp  = ttl*mtp;
    //$("#bgh-total-cart h3#total").html("$"+ttl.toFixed(2)+" or - "+ptp.toFixed(2)+"pt");
    $("#bgh-total-cart h3#total").html("$"+ttl.toFixed(2));

    $("#bgh-total-cart h3#points").html("+"+points+"pt");
    //$("#bgh-total-cart h3.price").html("$"+total);
    
    
    $("#bgh-body-cart").html(html);
    if(__curret_freebies!=null){
        var _name = __curret_freebies['name'];
        var _qty = __curret_freebies['qty'];
        if(typeof(_name) !== "undefined"){
            if(_name.length>0){
                html += "<div class='cart-freebies'><h4>Freebies</h4></div>";
            }
            for (var i = 0; i < _name.length; i++) {
                html += "<div class='cart-freebies'><h5>"+_name+[i]+" x "+_qty[i]+"</h5></div>";
            }    
        }
    }

    $("#bgh-body-cart").html(html);
    add_action();
    $(".cart_counter").html(count);
    __setCookie('allcart',JSON.stringify(ALL_PRODUCT_LIST),100);

    try{
        $(".open-in-it").select2({
            minimumResultsForSearch: Infinity
        });    
    }catch(e){
        console.log(e);
    }
/*
    $('.open-in-it').on('click', function() {
        //alert("Anjay");
    });

    $('.open-in-it').on('select2:open', function() {
        //alert("Anjay");
    });*/

    /*$('.open-in-it').on('select2:opening, select2:closing', function( event ) {
        var $searchfield = $(this).parent().find('.select2-search__field');
        $searchfield.prop('disabled', true);
        var d = $(this).select2('data');
        console.log(d+" TIARA");
    });*/

    /** generate clover sesson */
    _payment.getCloverSession();
    if( _payment.getMachine()!=""){
        var dt = boba.getRegulerData();
        dt['action'] = "fp-save-cart-cookie";
        dt['allcart'] = JSON.stringify(ALL_PRODUCT_LIST);
        dt['machine'] = _payment.getMachine();
        dt['name'] = $("#fp_location_name").val();
        dt['phone'] = $("#fp_location_phone").val();
        dt['clover_session'] = _payment.getCloverSession();
        
        $.post("",dt,function(res){
            console.log("SAVING ==> "+res);
        });    
    }

};

function fp_remove_cart(coded){
    delete ALL_PRODUCT_LIST[coded];
    if(coded == _current_coded){
        fp_product_cancel();
    }
    //fp_product_cancel();
    reload_cart();
    save_member_cart();
};

function getTax(total){
    var tx = Number($("#tax_def").val());
    cold_hot = 0;
    var product_tax = 0;
    $.each(ALL_PRODUCT_LIST,function(i,x){
        cold_hot    += Number(x.cold_hot);
        product_tax += (Number(x.total)*x.quantity*x.tax_rate/100);
        var lwr = x.name.toLowerCase();
        if(lwr.includes(" hot ")){
            cold_hot++;
        }
    });
    var tax = 0;
    if(cold_hot>0){
        tax = total * tx / 100;
    }
    tax += product_tax;
    tax = tax.toFixed(2);
    return tax;

}

function getRewardPoints(){
    var points = 0;
    $.each(ALL_PRODUCT_LIST,function(i,x){
        var subpoints = 0;
        if( !(typeof(x['points']) === "undefined") ){
            subpoints = (x.points*x.quantity);
        }
        points += subpoints;        
    });
    return points;
}

function getSubTotal(){
    var total = 0;  
    $.each(ALL_PRODUCT_LIST,function(i,x){
        var cur_tt = Number(x.total)*x.quantity;
        total += cur_tt - cur_tt*Number(x.dc)/100;
    });
    total = total.toFixed(2);
    return total;
}

function getTotal(){
    total = getSubTotal();
    var tax = getTax(total);
    var ttl = Number(total)+Number(tax); 
    return ttl.toFixed(2);
}

function countItem(){
    var count = 0;  
    $.each(ALL_PRODUCT_LIST,function(i,x){
        count += x.quantity;
    });
    return count;
}

function getDescription(){
    var desc = "";  
    $.each(ALL_PRODUCT_LIST,function(i,x){
        desc += x.origin_name+",";
    });
    return desc;
}
var _current_coded = "";


var IS_CART_DRAGGED = false;
function add_action(){
    $("#bgh-body-cart > div > h5.name").on("click",function(){
        if(IS_CART_DRAGGED){
            IS_CART_DRAGGED = false;
            return;
        }
        console.log(this);
        var coded   = $(this).data("coded");
        var current = ALL_PRODUCT_LIST[coded];
        _current_coded = coded;
        var id_items     = current.origin_id;
        var data         = boba.getRegulerData();
        data['action']   = "fp-product";
        data['id_items'] = id_items;
        data['coded']    = coded;
        data['modifier'] = current.detail;
        data['noted']    = current.noted;
        data['quantity']    = current.quantity;
        data['cold_hot']    = current.cold_hot;
        
        
        showLoading();
        $.post("",data,function(res){
            $("#fp-product-container").html(res);
            $("#fp-home").hide();
            $("#fp-product-container").show();
            adding_product_scroll();
            if($(".cart_count").is(":visible")){
                $("#fp-cart .bgh-footer").hide();
                fp_hide_boba();
            }
            dismissLoading();
        });
    });
};

function fp_cancel_cart(){    
    if(is_on_kiosk()){
        ALL_PRODUCT_LIST = {};
    }
    reload_cart();
    close_menu();
}

function fp_save_cart(){    
    close_menu();
}

function fp_browse_only(){    
    $("#fp-weclose").hide();
    $("#fp-orders").show();
    //load_menu(this,'fp-browse-only');
}

function fp_hide_cart(){
    ALL_PRODUCT_LIST = {};
    reload_cart();
    $("#div-cashier").html("");
    sidebar();
    navigate();
}

function fp_checkout_cart_tips_skip(){
    let total_price = getTotal();
    var tips = 0;
    let delivery_price = _location.getDeliveryPrice();
    let total_all = Number(total_price)*1+Number(delivery_price)*1+Number(tips)*1;

    _payment.setCost(total_all);
    _payment.setMembership($("#fp_location_membership_barcode").val());
    _payment.setTopUp(false);

    _payment.show();
    _payment.setCallBack(function(data){
        data = _location.addData(data);
        data['tips'] = tips;
        save_checkout(data);
    });
}

function checkingIsClose(){

    var d = {
        page:"boba",
        action:"fp-check-close",
        is_goblooge_test:is_goblooge_do_test()
    };

    $.post("",d,function(res){
        var j = getContent(res);
        if(j==1 && !is_on_kiosk() && !is_on_cashier() ){
            $("#fp-weclose").show();
            $(".no-browse-only").remove();
            $(".icontent").hide();
        }else{
            $("#fp-weclose").hide();
            $(".browse-only").remove();
            $("#fp-orders").show();
            $(".icontent").hide();
        }
    });

    return false;
}

function checkingDeliveryOK(){
    if($("#fp_location_at_delivery").val()=="1" && $("#fp_location_at_delivery_uber_quote_id").val()==""){
        smis_alert("Delivery Problem","you pick delivery service but the location and price seem not set, try to set delivery location again and make sure your location deliverable, too close or too far area can't use delivery service.");
        return false;
    }
    return true;
}

function fp_checkout_cart_tips_accept(){
    if(checkingPhoneName()==0 || checkingIsClose() || !checkingDeliveryOK()){
        return;
    }
        

    let total_price = getTotal();
    var tips = Number(smis_get_data("#fp_tips_tips"))*1;
    let delivery_price = _location.getDeliveryPrice();
    let total_all = Number(total_price)*1+Number(delivery_price)*1+Number(tips)*1;

    
    
    _payment.logTelegram("Checkout Price "+total_all+" Clover Session : <strong>"+_payment.getCloverSession()+"</strong>");
    _payment.setCost(total_all);
    _payment.setMembership($("#fp_location_membership_barcode").val());
    _payment.setTopUp(false);

    _payment.show();
    _payment.setCallBack(function(data){
        data = _location.addData(data);
        data['tips'] = tips;
        save_checkout(data);
    });
    
    let width = screen.width;
    
    if(width<992){
        $("#fp-cart").addClass("force");
        $("#fp-cart").addClass("force-hide");
    }
    $("#fp-cart").show();
}

function reloading_payment_cart(){
    let total_price = getTotal();
    var tips = Number(smis_get_data("#fp_tips_tips"))*1;
    let delivery_price = _location.getDeliveryPrice();
    let total_all = Number(total_price)*1+Number(delivery_price)*1+Number(tips)*1;
    _payment.setCost(total_all);
    _payment.calculate();
}

function checkingPhoneName(){
    if(!is_on_kiosk() && !is_on_cashier() && $("#fp_location_phone").val()==""){
        showFullWarning("Name and Phone is Mandatory","Please Fill Name and Phone its mandatory","normal_model","");
        return 0;
    }

    if($("#fp_location_at_delivery").val()=="1" && $("#fp_location_at_delivery_address").val()==""){
        showFullWarning("Address is Mandatory","Please add your address to continue","normal_model","<a href='#' onclick='hideWarning()' class='btn btn-danger'>Ok</a>",true);
        return 0;
    }

    $(".scan-card").hide();
    $("#fp_location_membership_barcode").hide();
    
    if($("#fp_location_name").val()==""){
        if(is_on_cashier() || is_on_kiosk()){
            showFullWarning("Phone and Name","Your name is require. And phone number is recommended to get order status  notification on your phone. Thank you","normal_model","");
            return 0;
        }else{

            $("#fp_location_phone").trigger("input");
            var phone =  $("#fp_location_phone").val();
            
            phone = phone.substring(1, 4);
            var codephone = Number(phone);
            if( (codephone<201 || codephone>989) && !is_on_kiosk() && !is_on_cashier()){
                showFullWarning("Phone is Wrong","Please fill Phone Correct Number","normal_model","");
                return 0;
            }
            showFullWarning("Register or Login","Please register for free membership or login to manage your orders and earn points for your purchase before continue","normal_model","");
            return 0;
        }
        
    }
    
    
    return 1;
}

function fp_checkout_cart(){
    if(checkingPhoneName()==0){
        return;
    }
    let total_price = getTotal();
    let delivery_price = _location.getDeliveryPrice();
    let total_all = Number(total_price)+delivery_price;

    _payment.setCost(total_all);
    _payment.setMembership($("#fp_location_membership_barcode").val());
    _payment.setTopUp(false);

    _payment.show();
    _payment.setCallBack(function(data){
        data = _location.addData(data);
        save_checkout(data);
    });
}

function fp_tips(){
    $("#fp-tips").show();
    let total_price = getTotal();
    let delivery_price = _location.getDeliveryPrice();
    let total_all = Number(total_price)+delivery_price;

    smis_edit("#fp_tips_subtotal",total_price);
    smis_edit("#fp_tips_delivery_fee",delivery_price);
    smis_edit("#fp_tips_tips",0);
    smis_edit("#fp_tips_total",total_all.toFixed(2));

    $("#fp-tips").show();

}

var __curret_freebies = null;
function addFreebies(id){
    var data = boba.getRegulerData();
    data['action'] = "fp-freebies";
    data['command'] = "add";
    data['id_item'] = id;
    showLoading();
    $.post("",data,function(res){
        __curret_freebies = getContent(res);
        reload_cart();
        dismissLoading();
    });
}


function minFreebies(id){
    var data = boba.getRegulerData();
    data['action'] = "fp-freebies";
    data['command'] = "sub";
    data['id_item'] = id;
    showLoading();
    $.post("",data,function(res){
        __curret_freebies = getContent(res);
        reload_cart();
        dismissLoading();
    });
}


function fp_freebies(back=false){

    var subtotl = getSubTotal();
    if(subtotl==0 && !back){
        showWarning("Cart Empty","Please Select item you want to purchase");
        return;
    }

    //$("#top-menu").removeClass("show-up");
    //if($("#fp-cart").hasClass("show")){
    //    $("#fp-cart").removeClass("show");
    //    $(".back_cart").hide();
    //    $(".on_cart").show();   
    //}
    //$("#fp-cart").hide();
    var data = boba.getRegulerData();
    data['action'] = "fp-freebies";
    data['total_price'] = subtotl;
    showLoading();
    $.post("",data,function(res){
        __curret_freebies = getContent(res);
        reload_cart();
        dismissLoading();
    });
}

function fp_back_home(){
    if(is_not_member() || is_on_kiosk() || is_on_cashier()){
        fp_cancel_cart();
    }else{
        fp_back_to_member();
    }
}

function fp_tips_freebies(){
    if(is_on_kiosk() || is_on_cashier()){
        $(".in-kiosk").show();
        $(".in-phone").hide();
    }else{
        $(".in-kiosk").hide();
        $(".in-phone").show();
    }
    $("#fp-cart").removeClass("show");
    $(".btn-boba-arrow ").hide();
    hideWarning();
    fp_tips();
}

function fp_tips_back_with_freebies(){
    if(is_on_kiosk() || is_on_cashier()){
        $("#member_button").hide();
    }else{
        $("#member_button").show();
    }
    $("#fp-tips").hide();
    fp_freebies(true);
}

function fp_tips_back_no_freebies(){
    if(is_on_kiosk() || is_on_cashier()){
        $("#member_button, .member-button").hide();
        $(".non-member-button").show();
    }else{
        $(".non-member-button").hide();
        $("#member_button, .member-button").show();
    }
    $("#fp-cart").removeClass("force");
    $("#fp-cart").removeClass("force-hide");
    $("#fp-cart").show();
    $("#fp-tips").hide();
    $(".btn-boba-arrow ").show();
    _location.hide();
    hideWarning();
}


function check_kiosk_or_cashier(){

}

function fp_checkout_location(){
    
    if(is_on_cashier() || is_on_kiosk() ){
        let total_price = getTotal();
        _location.setCurrentTotal(total_price);
        _location.show();    
    }else{
        //if in mobile auto detect login and then if yes, then fo to login
        var d = {
            page:"boba",
            action:"fp-check-login"
        }
        $.post("",d,function(res){
            var j = getContent(res);
            if(j==1){
                let total_price = getTotal();
                _location.setCurrentTotal(total_price);
                _location.show();
                fp_login_pop_up();
            }else{
                let total_price = getTotal();
                _location.setCurrentTotal(total_price);
                _location.show();   
            }
        });
    }
    fp_location.opening_trigger();

}

function fp_hide_boba(){
    $("#top-menu").removeClass("show-up");
    if($("#fp-cart").hasClass("show")){
        $("#fp-cart").removeClass("show");
        $(".back_cart").hide();
        $(".on_cart").show();
    }else{
        $("#fp-cart").addClass("show");
        $(".back_cart").show();   
        $(".on_cart").hide();    
    }
    /*
    if($("#fp-boba").is(":visible")){
        $("#fp-boba").hide("fast");
        $(".back_cart").show();   
        $(".on_cart").hide();      
    }else{
        $("#fp-boba").show("fast");
        $(".back_cart").hide();
        $(".on_cart").show();      
    }*/
}

function is_not_member(){
    return $('#fp_location_membership_barcode').val()=="";
}

function fp_cancel_location(){
    _location.hide();
    hideWarning();
    $("#fp-cart").show();

    if( is_not_member() || is_on_cashier() || is_on_kiosk()){
        $("#back-member").hide();
        //("#back-non-member").show();
    }else{
        $("#back-member").show();
        //$("#back-non-member").hide();
    }

}

function is_member(){
    if(is_on_cashier() || is_on_kiosk()){
        return false;
    }
    if($("#member_id").val()!="" && $("#member_id").val()!=null){
        return true;
    }else{
        return false;
    }
}

function save_checkout(data){   
    _payment.logTelegram("Start Saving Checkout... "+_payment.getCloverSession()+" "+JSON.stringify(data)); 
    //showWarning("Please wait...","we processing your order, please wait 30 sec");
    data['items']           = ALL_PRODUCT_LIST;
    data["action"]          = "fp-save-order";
    data["page"]            = "boba";
    
    data["name"]            = $("#fp_location_name").val();
    data["phone"]           = $("#fp_location_phone").val();
    data["card"]            = $("#fp_location_membership_barcode").val();
    try{
        data["total"]           = getTotal();
        data["subtotal"]        = getSubTotal();
        data["tax_percent"]     = Number($("#tax_def").val());
        data["tax"]             = getTax(data["total"]);
        data["points_rewarded"] = getRewardPoints();    
    }catch(e){
        data["error"] = e.message;
    }
    _payment.logTelegram("Post Saving Checkout... "+_payment.getCloverSession()+" "+JSON.stringify(data)); 
    showLoading();
    $.post("",data,function(res){
        //hideWarning();

        try{
            var json = getContent(res);
            if(json=="1"){
                _location.reset();
                _location.hide();
                _payment.reset();    
                _payment.hide();       
                $("#fp-tips").hide();  
                ALL_PRODUCT_LIST = {};
                reload_cart();   
            }
    
            if(is_member()){
                _payment.logTelegram("Done Saving Checkout Member... "+_payment.getCloverSession()+" "+JSON.stringify(data)); 
                fp_back_to_member(true);
            }else{
                console.log("is member no : reloading");
                _payment.logTelegram("Done Saving Checkout Member... "+_payment.getCloverSession()+" "+JSON.stringify(data)); 
                setTimeout(function(){
                    smis_reload();
                },3000);
                
                /*
                if(data['paid_change']>0){
                    setTimeout(function(){
                        smis_reload();
                        //alert("PAID CHANGE");
                        //reloading on the frontpage after purchasing 
                    },13000);
                }else{
                    setTimeout(function(){
                        //alert("NO CHANGE");
                        smis_reload();
                        //reloading on the frontpage after purchasing
                    },3000);
                }*/
    
                    
            }
        }catch(e){
            //showWarning("Connection unstable","please tell the admin about conneciton unstable");
        }
        /**non member simply reset it all */
        
    }).fail(function(e){
        //showWarning("We encounter problem","will resume in 3 second");
        setTimeout(function(){
            save_checkout(data);
        },3000);
    })
    .always(function(){
        dismissLoading();
    });
};


function fp_cancel_payment(){
    $("#fp-payment").hide("fast");    
}

$(".back_cart").hide(); 

var bcode = "";