'use strict'
let OPT_BILLING_ADDRESS = 0;
let cart_l = 0;
let Cart = (function() {
    let cookieName;
    let read_cart = (cart_cookie)?JSON.parse(cart_cookie):{};
    let cookie_act = '';
    function Cart(cookieName = 'dssf_cart') {
        this.cookieName = 'dssf_cart';
        this.readCookie = function() {
            return read_cart;
            //return Cookies.getJSON(cookieName);
        }
    }    

    function _switchCartButtons(status) {
        status = Number(status);
        var html = "<button class='btn btn-warning btn-buy-cart'><i class='fa fa-fw fa-shopping-cart'></i> GO TO CART</button>";
        if (status === 1) {
            html = "<button class='btn btn-info disabled'><i class='fa fa-fw fa-shopping-cart'></i> ADDING TO CART</button>";
        }
        $(".cart-btn-container").html(html);
    }

    Cart.prototype.showAlert = function(msg, type) {
        $(".alert-" + type).html(msg).show();
        setTimeout(function() {
            $(".alert-" + type).hide();
        }, 10000);
    }

    Cart.prototype.addPart = function(part) {
        let cart = this.readCookie();
        let products = {};
        if (cart!==null && cart !== ''  && typeof cart !== 'undefined') 
        {
           products = cart;
        }
        if (part.gc_unique_id) {
            products[part.gc_unique_id] = part;
        } else {
            products[part.uuid] = part;
        }
        this.setCookie(products);
        _switchCartButtons(3);
        this.showAlert('Product added To Cart', 'info');
    }

    Cart.prototype.removePart = function(uuid) {
        let cart = this.readCookie();
        if (uuid in cart) {
            for (let key in cart) {
                if(cart[key].is_addon && cart[key].parent_uuid == uuid)
                {
                    delete cart[cart[key].uuid];
                }                
            }
            delete cart[uuid];
            cookie_act = 'delete';
            this.setCookie(cart);
            this.checkCart();
            return true;
        }
        return false;
    }

    Cart.prototype.updatePart = function(part) {
        let uuid = part.uuid;
        let cart = this.readCookie();
        if (part.part_type == "GiftCertificate") {
            uuid = part.gc_unique_id;
        }
        if (uuid in cart) {
            cart[uuid] = part;
        } 
        this.setCookie(cart);
    }

    Cart.prototype.isUUIDExists = function(uuid) {
        let cart = this.readCookie();
        if (uuid in cart) {
            return true;
        }
        return false;
    }

    Cart.prototype.checkCart = function() {
        if (this.cartCount() === 0) {
            $(".con-cart").html('<h3 class="text-center text-banner text-muted">Cart is Empty!</h3>');
        }
    }

    Cart.prototype.cartCount = function() {
        let cart = this.readCookie();
        return cart ? Object.keys(cart).length : 0;
    }

    Cart.prototype.cartTotal = function() {
        let cart = this.readCookie();
        if (typeof cart !== 'undefined') {
            let subTotal = 0.0;
            let ship_cost = 0;
            for (let key in cart) {
                let prod = cart[key];
                if($("#show_tax_inclusive_price_in_storefront").length>0 && $("#show_tax_inclusive_price_in_storefront").val()==1)//FeatureTag
                {
                    if($("#cart_page_gc_subtotal_shows_zero").length>0 && $("#cart_page_gc_subtotal_shows_zero").val()==1)//FeatureTag
                    {
                        if(prod.part_type=="GiftCertificate"){
                            subTotal += Number(prod.price) * Number(prod.count);    
                        }else{
                            if(is_tax_inclusive==1){
                                subTotal += Number(prod.tax_inclusive_price) * Number(prod.count);
                            }else{
                                subTotal += Number(prod.price) * Number(prod.count);    
                            }
                        }
                    }else{
                        if(is_tax_inclusive==1){
                            subTotal += Number(prod.tax_inclusive_price) * Number(prod.count);
                        }else{
                            subTotal += Number(prod.price) * Number(prod.count);    
                        }
                    }
                }else{
                    subTotal += Number(prod.price) * Number(prod.count);
                }
            }
            subTotal = subTotal.toFixed(2);
            subTotal = formatMoney(subTotal);
            $("#amountPayable").html(subTotal);
        } else {
            $("#amountPayable").html($("#currency_symbol").val()+'0.00');
        }
    }

    Cart.prototype.assignTotal = function() {
        this.cartTotal();
        //$("#amountPayable").html(this.cartTotal());
    }

    Cart.prototype.assignCount = function() {
        $(".cart-count").html(this.cartCount());
    }

    Cart.prototype.setCookie = function(value) {
        if($("#enable_maintenance_mode_in_add_to_cart_on_sf").length>0 && $("#enable_maintenance_mode_in_add_to_cart_on_sf").val()==1) //FeatureTag
        {
            if(ADD_TO_CART_MAINTENANCE_MODE==1){

            }else{
               var data = JSON.stringify(value);
                this.clearCookie();
                $.ajax({
                    url: BASE_PATH + '/site/cart_cookie',
                    type: "post",
                    data: {
                        'name': this.cookieName,
                        'arg': data,
                        'cookie_act' : cookie_act
                    },
                    success: function (data) {
                        if(data==true){

                            cart_l++;
                        }
                    }
                });
                this.assignTotal();
                this.assignCount(); 
            }
        }else{
            var data = JSON.stringify(value);
            this.clearCookie();
            // Cookies.set(this.cookieName, data, {
            //     expires: 7
            // }, {
            //     domain: DOMAIN_NAME
            // });
            // cart_l++;
            $.ajax({
                url: BASE_PATH + '/site/cart_cookie',
                type: "post",
                data: {
                    'name': this.cookieName,
                    'arg': data,
                    'cookie_act' : cookie_act
                },
                success: function (data) {
                    if(data==true){

                        cart_l++;
                    }
                }
            });
            this.assignTotal();
            this.assignCount();
        }
    }

    Cart.prototype.clearCookie = function() {
        Cookies.set(this.cookieName, '', {
            expires: -1
        }, {
            domain: DOMAIN_NAME
        });
        this.assignTotal();
        this.assignCount();
    }
    return Cart;
})();

let XHR = (function() {
    let params, type, async, method, baseUrl;

    function XHR(baseUrl) {
        this.baseUrl = baseUrl;
    }

    let _toParam = (ary) => {
        if (!(ary instanceof Array)) {
            console.warn('Exception: Not an array');
            return false;
        }
        var str = '';
        for (var len = ary.length, i = 0; i < len; i++) {

            str += ary[i].join('=');
            str += (i === len - 1) ? '' : '&';
        }
        return str;
    }

    XHR.prototype.call = function(method, params = {}, type = 'GET', async = true) {
        this.method = method;
        this.params = Object.keys(params).map((i) => {
            return [i, params[i]]
        });
        this.type = type;
        this.async = async;

        return new Promise((resolve, reject) => {
            let url = this.baseUrl + method;
            let xhr = new XMLHttpRequest();


            xhr.open(this.type, url, this.async);
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            xhr.send(_toParam(this.params));
            xhr.onload = () => {
                if (xhr.status >= 200 && xhr.status < 400) {
                    resolve(JSON.parse(xhr.response));
                } else {
                    reject(new Error(`${xhr.status} - Error Fetching Data form Server`));
                }
            };
            xhr.onerror = () => {
                reject(new Error(`${xhr.status} - Error Fetching Data form Server`));
            };
        });
    }

    return XHR;
})();

let cart = new Cart();
let xhr = new XHR(BASE_PATH + '/api/');

function init_cart() {
    cart.assignTotal();
    cart.assignCount();
}
window.onload = function() {
    init_cart();
}

$( document ).ready(function() {

        $('.allowdec').keypress(function(event){
            if ((event.which != 46 || $(this).val().indexOf('.') != -1)&& (event.which < 48 || event.which > 57))
            {
            if((event.which != 46 || $(this).val().indexOf('.') != -1))
            {
              //alert('Multiple Decimals are not allowed');
            }
            event.preventDefault();
            }
            if(this.value.indexOf(".")>-1 && (this.value.split('.')[1].length > 1))
            {
            //alert('Two numbers only allowed after decimal point');
            //event.preventDefault();
            }
        });
        $(document).on('click', '.travel_deposit_btn', function(){
            var px = 0;
            $('.paytravelcart').each(function () {
                if (this.checked) {
                    var travel_cart_id = $(this).attr("data_id");
                    var tr_obj = "#trip_due_"+travel_cart_id;
                    var trip_due = parseFloat($(tr_obj).val());
                    if(parseFloat(trip_due) == 0 || $(tr_obj).val()==''){
                        px++;
                    }
                }
            });
            if(px==0)
            {
                $('.paytravelcart').each(function () {
                    if (this.checked) {
                        var travel_cart_id = $(this).attr("data_id");                 
                        // var obj = this;
                        // var travel_cart_id = $(obj).attr("data_travel_cart_id");
                        trip_balance_add_to_cart(travel_cart_id);                    
                    }
                });
            }else{
                alert("Enter valid Pay Trip Balance."); 
                return false;    
            }
        });
        $(document).on('click', '.travel_deposit_by_btn', function(){
            var obj = this;
            var travel_cart_id = $(obj).attr("data_travel_cart_id");
            if($("#redirect_to_respective_store_for_trip_deposit_payment").length>0 && $("#redirect_to_respective_store_for_trip_deposit_payment").val()==1){
                var trip_due = parseFloat($("#trip_due_"+travel_cart_id).val());
                var trip_due_max = parseFloat($("#trip_due_"+travel_cart_id).attr("data_max"));
                if(trip_due_max<trip_due){
                    $("#trip_due_"+travel_cart_id).val(trip_due_max);
                }
                trip_balance_add_to_cart(travel_cart_id,obj);
            }else{
                trip_balance_add_to_cart(travel_cart_id);                    
            }
        });
       
});

function trip_balance_add_to_cart(travel_cart_id, obj){
    var trip_due = parseFloat($("#trip_due_"+travel_cart_id).val());
    var trip_due_max = parseFloat($("#trip_due_"+travel_cart_id).attr("data_max"));
    // var trip_due_min = 1; //parseFloat($("#trip_due_"+travel_cart_id).attr("data_min"));
    // if(trip_due_min>0 && trip_due_min>trip_due)
    // {
    //     var min_pay = $("#trip_due_"+travel_cart_id).attr("data_min_pay");
    //     alert("The minimum payment should be "+min_pay);
    //     return false;
    // }
    if(trip_due>0){
        if($("#redirect_to_respective_store_for_trip_deposit_payment").length>0 && $("#redirect_to_respective_store_for_trip_deposit_payment").val()==1){
            if(obj!=''){
                var contact_uuid = $(obj).attr("data_contact_uuid");
                var data_travel_cart_store_url = $(obj).attr("data_travel_cart_store_url");
                var travel_cart_id = $(obj).attr("data_travel_cart_id");
                var trip_due = parseFloat($("#trip_due_"+travel_cart_id).val());
                var str_url = data_travel_cart_store_url+"/auto_login/"+contact_uuid+"/"+travel_cart_id+"/"+trip_due;
                if($(".page-numbers .current").length>0){
                    str_url += "?page="+$(".page-numbers .current").html();
                }
            }
            if(data_travel_cart_store_url){
                    var sub_store_name = $(obj).attr("data_sub_store");
                    var r = confirm("You are being redirected to "+sub_store_name+" to complete your payment");
                    if(r){
                        window.open(str_url, '_blank');
                    }else{
                        $("#trip_due_"+travel_cart_id).val('');
                    }
                
                return false;                
            }else{
                var trip_deposit = JSON.parse($("#trip_deposit_"+travel_cart_id).val());
                trip_deposit[travel_cart_id].price = trip_due;
                cart.addPart(trip_deposit[travel_cart_id]);
                var trip_deposit_cart_interval = setInterval(function () {
                    if(cart_l>0)
                    {
                        clearInterval(trip_deposit_cart_interval);
                        $.notify({
                            from: "bottom",
                            title: "<strong></strong> ",
                            icon: 'glyphicon glyphicon-shopping-cart',
                            message: "Added to your cart successfully...!"
                        },{timer: 1000,type: 'success',animate: {enter: 'animated lightSpeedIn',exit: 'animated lightSpeedOut'}});
                        
                        //window.location.reload();
                        window.location = BASE_PATH+"/checkout";
                    }
                },1000);    
            }
        }else{
            var trip_deposit = JSON.parse($("#trip_deposit_"+travel_cart_id).val());
            trip_deposit[travel_cart_id].price = trip_due;
            cart.addPart(trip_deposit[travel_cart_id]);
            var trip_deposit_cart_interval = setInterval(function () {
                if(cart_l>0)
                {
                    clearInterval(trip_deposit_cart_interval);
                    $.notify({
                        from: "bottom",
                        title: "<strong></strong> ",
                        icon: 'glyphicon glyphicon-shopping-cart',
                        message: "Added to your cart successfully...!"
                    },{timer: 1000,type: 'success',animate: {enter: 'animated lightSpeedIn',exit: 'animated lightSpeedOut'}});
                    
                    //window.location.reload();
                    window.location = BASE_PATH+"/checkout";
                }
            },1000);
        } 
    }else{
        alert("Enter valid Pay Trip Balance");
        $("#trip_due_"+travel_cart_id).focus();
        return false;
    }
}

function addToCart(handle, count, cInv,part_type='') {
    if($("#enable_maintenance_mode_in_add_to_cart_on_sf").length>0 && $("#enable_maintenance_mode_in_add_to_cart_on_sf").val()==1) //FeatureTag
    {
        if(ADD_TO_CART_MAINTENANCE_MODE==1){
            $.notify({
                title: "<strong class='insufficient-quantity-cart'>Alert: System Maintenance</strong> ",
                icon: 'glyphicon glyphicon-info-sign',
                message: ADD_TO_CART_MAINTENANCE_MODE_MSG
            }, {
                timer: 2000,
                type: 'danger',
                animate: {
                    enter: 'animated lightSpeedIn',
                    exit: 'animated lightSpeedOut'
                }
            });
            setTimeout(function () {
                window.location.reload();
            },1000); 
            return false;        
        }
    }

    var e = document.getElementById("numProductQty");
    var isValid = (!cInv) ? true : e.validity.valid;

    if (handle && isValid) {
        let params = {handle: handle,part_type:( (part_type=="")?'product':part_type )};
        xhr.call('getPartDetails', params, 'POST')
            .then(function(data) {
                if (data.status) {
                    
                    $.notify({
                        from: "bottom",
                        title: "<strong></strong> ",
                        icon: 'glyphicon glyphicon-shopping-cart',
                        message: "Added to your cart successfully...!"
                    }, {
                        timer: 1000,
                        type: 'success',
                        animate: {
                            enter: 'animated lightSpeedIn',
                            exit: 'animated lightSpeedOut'
                        }
                    });
                    
                    data.data.count = count;
                    cart.addPart(data.data);
                    var part_cart_interval = setInterval(function () {
                        if(cart_l>0)
                        {
                            clearInterval(part_cart_interval);
                            window.location.reload();
                        }
                    },1000);    
                   
                }
            });

    } else if (!e.validity.valid) {
        
        $.notify({
            title: "<strong class='insufficient-quantity-cart'></strong> ",
            icon: 'glyphicon glyphicon-shopping-cart',
            message: "Insufficient Quantity!"
        }, {
            timer: 2000,
            type: 'dangert',
            animate: {
                enter: 'animated lightSpeedIn',
                exit: 'animated lightSpeedOut'
            }
        });
        
        cart.showAlert('Insufficient Quantity!', 'danger');
        
       //setTimeout(window.location.href = BASE_PATH+"/products/"+handle , 6000);
       setTimeout( 
  function() {
    window.location.reload('BASE_PATH+"/products/"+handle');
  }, 3000);
    } else {
        
        $.notify({
            title: "<strong></strong> ",
            icon: 'glyphicon glyphicon-shopping-cart',
            message: "Unable to add product to cart!"
        }, {
            timer: 1000,
            type: 'dangert',
            animate: {
                enter: 'animated lightSpeedIn',
                exit: 'animated lightSpeedOut'
            }
        });
        
        cart.showAlert('Unable to add product to cart!', 'danger');
    }
}


if (CONTROLL == "calendar") {
    Array.prototype.contains = function(v) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] === v) return true;
        }
        return false;
    };

    Array.prototype.unique = function() {
        var arr = [];
        for (var i = 0; i < this.length; i++) {
            if (!arr.contains(this[i])) {
                arr.push(this[i]);
            }
        }
        return arr;
    }
}

function addToCalCart(handle, count, type, travel_total, from_cart) {
    if($("#allow_products_as_course_to_ssi").length>0 && $("#allow_products_as_course_to_ssi").val()==1) //FeatureTag
    {
        if ( (type == 'Course' || type == 'Product') && checkAddStudentForm()) {
            getCourseRegisteredUsers();
            preserveContact(handle);
            if (REG_USERS.length > 0) {
                var reg_name = [];
                var reg_email = [];
                $.each(REG_USERS, function(i, item) {
                    reg_name.push(item.name);
                    reg_email.push(item.email.toLowerCase());
                });
            }
            console.log("reg_name", typeof reg_name);
            // Use a Set to filter out duplicate names
            if (new Set(reg_name).size !== REG_USERS.length) {
                alert("You have entered the same student name more than once. Please remove to proceed.");
                return false;
            }            
            if ((ssi_id !== '' || tdisdi_id !== '' || padi_id !== '') && new Set(reg_email).size !== REG_USERS.length) {
                alert("Students' emails should be unique");
                return false;
            }           
            proceedAddToCalCart(handle, count, type, travel_total, from_cart);
        }
    }else{
        if (type == 'course' && checkAddStudentForm()) {
            getCourseRegisteredUsers();
            preserveContact(handle);
            if (REG_USERS.length > 0) {
                var reg_name = [];
                var reg_email = [];
                $.each(REG_USERS, function(i, item) {
                    reg_name.push(item.name);
                    reg_email.push(item.email.toLowerCase());                
                });
            }
            if (reg_name.unique().length != REG_USERS.length) {
                alert("You have entered the same student name more than once. Please remove to proceed.");
                return false;
            }
            
                if ( (ssi_id!='' || tdisdi_id!='' || padi_id!='')  && reg_email.unique().length != REG_USERS.length) {
                    alert("Students email should be unique")
                    return false;
                }
            
            proceedAddToCalCart(handle, count, type, travel_total, from_cart);
        }
    }
    if ((type == 'travel' || type == 'charter') && checkAddOptionForm()) {
        getTravelRegisteredUsers();
        getTravelAddonOptions();
        preserveContact(handle);
        if (REG_USERS.length > 0) {
            var reg_name = [];
            var reg_email = [];
            $.each(REG_USERS, function(i, item) {
                    reg_name.push(item.name+"_"+item.option_id);
                
                reg_email.push(item.email);
            });
        }
        if (reg_name.unique().length != REG_USERS.length) {
            alert("You have entered the same traveler name more than once. Please remove to proceed.");
            return false;
        }
        if (reg_email.unique().length != REG_USERS.length) {
            //alert("You have entered more than one repeated traveller email, Please check and confirm?")
            //return false;
        }
        proceedAddToCalCart(handle, count, type, travel_total, from_cart);
    }
}
var cal_checkout_btn = false;
var cart_msg = '';
var xck_out = 0;
function proceedAddToCalCart(handle, count, type, travel_total, from_cart) {
    if (handle) {
        let params = {
            handle: handle,
            part_type: type,
            travel_total: travel_total,
            count:count
        };
        xhr.call('getPartDetails', params, 'POST')
            .then(function(data) {
                if (data.status) {
                    
                    $.notify({
                        title: "<strong></strong> ",
                        icon: 'glyphicon glyphicon-shopping-cart',
                        message: cart_msg //"Added to your cart successfully...!"
                    }, {
                        timer: 1000,
                        type: 'success',
                        animate: {
                            enter: 'animated lightSpeedIn',
                            exit: 'animated lightSpeedOut'
                        }
                    });
                    if (type == 'travel' || type == 'charter') {
                        data.data.count = 1;
                    } else {
                        data.data.count = count;
                    }
                    data.data.original_count = count;
                    var addon_cnt = 0;
                    // if(data.data.addons)
                    // {
                    //     $.each(data.data.addons, function(key, item) {
                    //         cart.addPart(item);
                    //         addon_cnt++;
                    //     });
                    // }
                    cart.addPart(data.data);
                    cart.assignCount();
                    addon_cnt++;
                    var course_addon_interval = setInterval(function () {
                        
                            console.log(cart_l+"----"+addon_cnt+"-------"+from_cart+"-----"+cal_checkout_btn)
                        
                        if(cart_l==addon_cnt)
                        {
                            clearInterval(course_addon_interval);
                            if(cal_checkout_btn==true){
                                    cal_checkout_btn = false;
                                    xck_out++;
                                    if($("#contact_user_id").length>0 && $("#contact_user_id").val()!='' && $("#contact_user_id").val()!=undefined){
                                        setTimeout(function(){ window.location.href = BASE_PATH+"/checkout"; },700) ;
                                    }else{
                                        $("#signin_signup").show();  
                                        show_signin_form();
                                    }
                                
                            }else{
                                if(from_cart == 'yes'){
                                    window.location.href = BASE_PATH+"/cart";
                                }else{
                                    window.location.reload();
                                }
                            }
                        }
                    },1200);
                        if(cal_checkout_btn==true)
                        {
                            if($("#contact_user_id").length>0 && $("#contact_user_id").val()!='' && $("#contact_user_id").val()!=undefined){
                                setTimeout(function(){ window.location.href = BASE_PATH+"/checkout"; },700) 
                            }else{
                                $("#signin_signup").show(); 
                                show_signin_form();                                       
                            }
                        }
                        console.log(cal_checkout_btn+"==========xck_out===="+xck_out);
                    
                }
            });
        hideMainDialog();
    }
}

function deleteFromCart(uuid, el, unique_id) {
    if (unique_id != '') {

            if(unique_id!=$(el).attr("del-part")){
                var cart_res = cart.removePart($(el).attr("del-part"));
            }else{
                var cart_res = cart.removePart(unique_id);
            }

    } else {
        var cart_res = cart.removePart(uuid);
    }
    if (cart_res) {
        $(el).closest("tr").remove();

        $("li." + uuid).remove();

        var amount = ($("#amountPayable").length != 0) ? $("#amountPayable").html() : '$ 0.00';

        var tot_item = parseInt($(".tot_items").attr("data-tot")) - 1;
        $(".tot_items").attr("data-tot", tot_item);
        $(".amountPayable").html(amount);
        var tot_item = parseInt($(".tot_items").attr("data-tot"));
        $(".tot_items").attr("data-tot", tot_item);
        $(".tot_items").html(tot_item + " item(s) - " + amount);
        
        if($(".item_not_available").length==0)
        {
            if (CONTROLL == "products" && ACTION == "cart" )
            {
                if($(".btn_place_order").length>0)
                {
                    $(".btn_place_order").attr("disabled",false);
                }
                else if($("#place_order").length>0)
                {
                    $("#place_order").attr("disabled",false);
                }
            }
        }


        $.notify({
            title: "<strong></strong> ",
            icon: 'glyphicon glyphicon-shopping-cart',
            message: "Deleted from your cart successfully...!"
        }, {
            timer: 1000,
            type: 'success',
            animate: {
                enter: 'animated lightSpeedIn',
                exit: 'animated lightSpeedOut'
            }
        });
        

    }

}
function deleteFromCartTop(uuid, el, unique_id) {
    if (confirm('Are you sure you want to remove this item from your cart??')) {
        if (unique_id != '') {

                if(unique_id!=$(el).attr("del-part")){
                    var cart_res = cart.removePart($(el).attr("del-part"));
                }else{
                    var cart_res = cart.removePart(unique_id);
                }

        } else {
            var cart_res = cart.removePart(uuid);
        }
        if (cart_res) {
            $(el).parent().parent().remove();
            $.ajax({
                url: BASE_PATH + "/ajax/remove_shipping",
                success: function(result) {}
            });
            
            $.notify({
                title: "<strong></strong> ",
                icon: 'glyphicon glyphicon-shopping-cart',
                message: "Deleted from your cart successfully...!"
            }, {
                timer: 1000,
                type: 'success',
                animate: {
                    enter: 'animated lightSpeedIn',
                    exit: 'animated lightSpeedOut'
                }
            });
            var rm_part_cart_interval = setInterval(function () {
                if(cart_l>0)
                {
                    clearInterval(rm_part_cart_interval);
                    window.location.reload();
                }
            },1000);  
            //setTimeout(location.reload(), 1000);
        }
    }
    return false;
}
if($("#addon_qty_can_not_be_edited").length>0 && $("#addon_qty_can_not_be_edited").val()==1) //FeatureTag
{
    var focusin=0;
    var timeoutId;
    $(document).on('focus', '.cart_qty ', function(e){
        //console.log("focusin===",focusin);
        if(focusin==0){
            
        }else{
            $("#place_order").parent().fadeOut();
        }
    });
    $(document).on('keydown', '.cart_qty', function(e) {
        focusin++;
        if (focusin == 1) { // Focus is incremented before this check, so it's 1 when first focused
            $("#place_order").parent().fadeOut();
        }        
        var obj = $(this);
        // Clear the previous timeout if the user is still typing
        clearTimeout(timeoutId);
        // Set a new timeout to trigger the change event after 2 seconds
        timeoutId = setTimeout(function() {  
            //console.log("Trigger===");
            obj.trigger("change"); 
            focusin = 0; // Reset focusin counter after triggering change
        }, 500);
        //console.log("focusin2===", focusin);
    });
    $(document).on('keyup', '.cart_qty ', function(e){
        //console.log("focusin1===",focusin);
        if ($(this).val() === "") {
            alert("The field cannot be left empty.");
            //console.log("Trigger 1==="); 
            $(this).val(1).trigger("change");
        }else{
            var input = $(this).val();
            var min = parseInt($(this).attr('min'));
            if (input < min) {
                $(this).val(min);
                //console.log("Trigger 2==="); 
                $(this).trigger("change"); 
                alert("Please enter a qty should be greater then or equal to "+ min);
            }                     
        }
        if(focusin==0){
            
        }else{
            focusin = 0;
            $("#place_order").parent().fadeOut();
        }
    });
}
function changeUnitCount(handle, uuid, e, product_type, original_count) {

    if($("#addon_qty_can_not_be_edited").length>0 && $("#addon_qty_can_not_be_edited").val()==1) //FeatureTag
    {
        if(e.value > 0){
            $("#place_order").parent().fadeOut();
            // $(e).attr("readonly", true);
            $(e).parent().find(".loader_cart_pos").removeClass("hide");
        }
        if(parseInt($(e).attr("data-addon"))==1 && parseInt($(e).attr("min"))>0 ){
            if(parseInt($(e).attr("min"))>parseInt(e.value)){
                var alrmsg = 'This product is should be place qty with: '+$(e).attr("min");                
                cart.showAlert(alrmsg, 'danger');
                // $(e).val($(e).attr("min"));
                // $(e).attr("readonly", false);
                $("#place_order").parent().fadeIn();
                $(e).parent().find(".loader_cart_pos").addClass("hide");
                return false;
            }
        }        
    }

    if (cart.isUUIDExists(uuid) && e.value > 0) {
        let params;
        if($("#addon_qty_can_not_be_edited").length>0 && $("#addon_qty_can_not_be_edited").val()==1) //FeatureTag
        {
            if(parseInt($(e).attr("data-addon"))==1){
                params = {
                    parent_id : $(e).attr("data-parent_id"),
                    addon: true,
                    uuid : uuid,
                    handle: handle,
                    count: $(e).val(),
                    product_type: product_type.toLowerCase()
                };
            }else{
                params = {
                    uuid : uuid,
                    handle: handle,
                    count: $(e).val(),
                    product_type: product_type.toLowerCase()
                };
            }
        }else{
            params = {
                handle: handle,
                count: $(e).val(),
                product_type: product_type.toLowerCase()
            };
        }
        if (product_type == "GiftCertificate") {
            params.gc_key = $(e).attr('data-key');
        }
        xhr.call('checkStock', params, 'POST')
            .then(function(data) {
                if (data.status) {
                    if($("#PSO_"+data.data.part['uuid']).length>0)
                    {
                        if(data.data.PSO_msg)
                        {
                            $("#PSO_"+data.data.part['uuid']).html(data.data.PSO_msg);
                        }else{
                            $("#PSO_"+data.data.part['uuid']).html('');
                        }
                    }
                    return data.data;
                }
            })
            .then(function(data) {
                if (!data.available) {
                    if(data.nla==true)
                    {
                        var alrmsg = 'This product is no longer available. Maximum order quantity available: '+data.stock;
                    }
                    else{
                        var alrmsg = 'We are Sorry! We are able to accomodate only '+ data.processed +' quantity of <strong>'+ data.title +'</strong> for each customer';
                    }
                    cart.showAlert(alrmsg, 'danger');
                }
                $(e).val(data.processed);
                if (product_type == "Travel" || product_type == "Charter" || product_type == "Course") {
                } else {
                    $(e).closest("tr").find(".sub-total").html(data.subTotal);
                }
                return data;
            })
            .then(function(data) {
                if (product_type == "Travel" || product_type == "Charter") {
                    if (data.available)
                        gotoCalenderRegister(handle, (original_count + 1), product_type);
                } else if (product_type == "Course") {
                    if (data.available)
                        gotoCalenderRegister(handle, (e.value), product_type);
                } else {
                    cart.updatePart(data.part);
                }
                if($("#addon_qty_can_not_be_edited").length>0 && $("#addon_qty_can_not_be_edited").val()==1) //FeatureTag
                {
                    var intervalId = setInterval(function() {
                        console.log("loader_cart_pos===>", $(".loader_cart_pos:visible").length);
                        
                        if ($(".loader_cart_pos:visible").length == 0) {
                            $("#place_order").parent().fadeIn(); 
                            clearInterval(intervalId); // Stop the interval once the condition is met
                        }                        
                    }, 1000);

                    setTimeout(function(){                                               
                        $(e).parent().find(".loader_cart_pos").addClass("hide");                                               
                    },1000);                    
                }
            });
    }
}

function gotoCalenderRegister(handle, count, product_type) {
    let params = {
        handle: handle,
        count: count,
        product_type: product_type
    };
    xhr.call('getCollection', params, 'POST')
        .then(function(data) {
            if (data.status) {
                if (product_type == "Course") {
                    window.location.href = BASE_PATH + "/calendar/register/" + data.data['collection_uuid'] + "/" + data.data['id'] + "/" + data.data['count'] + "/" + data.data['handle'];
                } else {
                    window.location.href = BASE_PATH + "/calendar/reserve/" + data.data['collection_uuid'] + "/" + data.data['id'] + "/" + count + "/" + data.data['handle'];
                }
            }
        })
}

function clearCookie() {
    cart.clearCookie();
}

function shippingOptionChanged(e) {
    var opt = $(e).val();

    if (opt === 'new_shipping') {
        OPT_BILLING_ADDRESS = 1;
        $("#conNewShipping").slideDown();
    } else if (opt === 'same_as_shipping') {
        OPT_BILLING_ADDRESS = 0;
        $("#conNewShipping").slideUp();
    }
}
$(document).ready(function() {
    if(paypal_flag==1){
        if($("#terms_conditions").length==false)
        {
            $("#smart-button-container").show();
        }
        if($("#DirectPayAuthForm").length==0){
            $("#btnSubmitPay").hide();        
        }
    }
});
$(document).on('click', '#terms_conditions ', function(){
    if($("#terms_conditions").prop("checked"))
    {
        $(".terms_conditions").removeClass("error").css({"font-weight":"600","padding":"0px 10px"});
        $(".terms_conditions_error").css({"border":"none","padding":"0px 10px","margin-bottom":"10px"});
        if(paypal_flag==1){
            $("#smart-button-container").show();
        }
    }else{
        if(paypal_flag==1){
            $("#smart-button-container").hide();
        }
    }
});
function pform_submit(fid)
{
    if($("#when_submitting_to_pay_check_the_available_stocks").length>0 && $("#when_submitting_to_pay_check_the_available_stocks").val()==1) //FeatureTag
    {
        if($("#terms_conditions").length>0){
            if(!$("#terms_conditions").prop("checked"))
            {
                $(".terms_conditions").addClass("error").css({"font-weight":"600","padding":"0px 10px"});
                $(".terms_conditions_error").css({"border":"1px solid","padding":"0px 10px","margin-bottom":"10px"});
                alert("Please accept the terms & conditions to proceed further.");
                $('#btnSubmitPay').attr("disabled", false);
                return false;
            }
        }
        $.ajax({
            url: BASE_PATH + "/checkout/check_inventory_qty",
            async: true,
            success: function success(res) {
                var json = $.parseJSON(res);
                var qty_str = "";
                $.each(json.data,function(index, value){
                    console.log(index + '===========> ' + value);
                    qty_str += "<br>"+value;
                });
                if(json.status==0){
                    $.notify({
                        title: "",
                        icon: 'glyphicon glyphicon-cart',
                        message: qty_str
                    }, {
                        offset: {
                            x: 50,
                            y: 200
                        },
                        timer: 3000,
                        type: 'danger',
                        animate: {
                            enter: 'animated lightSpeedIn',
                            exit: 'animated lightSpeedOut'
                        }
                    });
                    setTimeout(function(){                
                        window.location.href = BASE_PATH + "/cart";
                    },2000);
                    return false;
                }else{
                        reset_payment_counter(600);
                   if(fid == "paylaterAuthForm" && $('#click_to_pay_ar_payment_portal').val()==1){
                        process_payment();                   
                    }
                    $('#'+fid).submit();
                    if($("#storefront_order_processing_method_upgrade").length>0 && $("#storefront_order_processing_method_upgrade").val()==1)
                    { 
                        if(fid == "DirectPayAuthForm"){
                            process_payment();                   
                        } 
                    }  
                }
            }
        });
    }else{
        if($("#terms_conditions").length>0){
            if(!$("#terms_conditions").prop("checked"))
            {
                $(".terms_conditions").addClass("error").css({"font-weight":"600","padding":"0px 10px"});
                $(".terms_conditions_error").css({"border":"1px solid","padding":"0px 10px","margin-bottom":"10px"});
                alert("Please accept the terms & conditions to proceed further.");
                $('#btnSubmitPay').attr("disabled", false);
                return false;
            }else
            {
                    if(fid == "paylaterAuthForm" && $('#click_to_pay_ar_payment_portal').val()==1){
                        process_payment();                   
                    }
                    $('#'+fid).submit();
                    if($("#storefront_order_processing_method_upgrade").length>0 && $("#storefront_order_processing_method_upgrade").val()==1)
                    { 
                        if(fid == "DirectPayAuthForm"){
                            process_payment();                   
                        } 
                    }   
            }
        }
        else{
            if(fid == "paylaterAuthForm" && $('#click_to_pay_ar_payment_portal').val()==1){
                process_payment();                   
            }
            $('#'+fid).submit();
            if($("#storefront_order_processing_method_upgrade").length>0 && $("#storefront_order_processing_method_upgrade").val()==1)
            { 
                if(fid == "DirectPayAuthForm"){
                    process_payment();                   
                } 
            }
        }
    }
}
var pwd_cap_error = false;
var prevent_cc = 0;

    var tot_attempt = 5;

function prevent_cc_testing()
{
    
}



function prevent_cc_testing_new()
{   
    $("#btnSubmitPay").attr("disabled", true);
    $.notify({
        title: "",
        icon: 'glyphicon glyphicon-cart',
        message: "You have tried too many attempts.."
    }, {
        offset: {
            x: 50,
            y: 200
        },
        timer: 1000,
        type: 'danger',
        animate: {
            enter: 'animated lightSpeedIn',
            exit: 'animated lightSpeedOut'
        }
    });
    setTimeout(function(){ 
            if($("#duplicate_charge_in_payment_portal").length>0 && $("#duplicate_charge_in_payment_portal").val()==1){
                getHasChanges(true); 
            }
            window.location.href = BASE_PATH + "/cart";

    },500);
    return false;
}

$(document).on('mouseover', '#btnSubmitPay', function() {
   
        if($("#google_captcha_action_name_changes").length>0 && $("#google_captcha_action_name_changes").val()==1) //FeatureTag
        {
            reset_captcha('',CHECKOUT_ACTION);
        }else{
            reset_captcha();
        }
    
});


$(document).on('click', '#btnSubmitPay', function() {
    if($("#pay_by").attr("data-action")=="cc")
    {
        var cccn = $("#CreditCardCardNumber").val();
        var cccv = $("#CreditCardCvv").val();
        var cce = $("#CreditCardExpiry").val();
        var ccn = $("#CreditCardName").val();
        var amountPayable_ship = parseFloat($("#amountPayable_ship").attr("data-amount"));
        if( (cccn=='' || cccv=='' || cce=='' || ccn=='') && amountPayable_ship>0 )
        {
            if(amountPayable_ship>0)
            {
                $(".gc_error").html("The gift certificate you have entered don't have sufficient balance to complete the order. Enter an additional gift certificate or use credit card to pay the balance");//.fadeIn();
                //setTimeout(function(){ $(".gc_error").fadeOut(); },5000);
                $("#gc_serial_number").focus();
                return false;
            }
        }
    }
    if ($("#DirectPayAuthForm").length) {
        $('#btnSubmitPay').attr("disabled", true);
        pform_submit("DirectPayAuthForm");
    }
    else if ($("#CreditCardAuthForm").length) {
        if($("#CreditCardAuthForm").valid())
        {
            var btnObj = this;
            $(btnObj).attr('disabled', true);
            $('#btnSubmitPay').attr("disabled", true);
            
                if($("#google_captcha_action_name_changes").length>0 && $("#google_captcha_action_name_changes").val()==1) //FeatureTag
                {
                    reset_captcha('',CHECKOUT_ACTION);
                }else{
                    reset_captcha();
                }                     
                pform_submit("CreditCardAuthForm");
                       
        }
    }else if($("#payment-form").length)
    { 
        if(act_url=='direct_pay')
        {   
            var btnObj = this;
            $(btnObj).attr('disabled', true);
            $('#btnSubmitPay').attr("disabled", true);
            if($("#google_captcha_action_name_changes").length>0 && $("#google_captcha_action_name_changes").val()==1) //FeatureTag
            {
                reset_captcha('',CHECKOUT_ACTION);
            }else{
                reset_captcha();
            }
            pform_submit("payment-form");
        }else{    
    console.log('cc',manualInputStates);
    
    if(manualInputStates['cardNumber']==false  ){
                    $('#card-errors1').html(errorInputmsg['cardNumber']);
                     $('#card-errors1').css('display','block');
                    $("#btnSubmitPay").attr("disabled", false);
                }else{
                        $('#card-errors1').html('');
                        $('#card-errors1').css('display','none');
                }
                if( manualInputStates['cardExpiry']==false ){
                    $('#card-errors3').html(errorInputmsg['cardExpiry']);
                     $('#card-errors3').css('display','block');
                    $("#btnSubmitPay").attr("disabled", false);
                }else{
                        $('#card-errors3').html('');
                        $('#card-errors3').css('display','none');
                }
                if( manualInputStates['cardCvc']==false  ){
                    $('#card-errors2').html(errorInputmsg['cardCvc']);
                     $('#card-errors2').css('display','block');
                    $("#btnSubmitPay").attr("disabled", false);
                }else{
                        $('#card-errors2').html('');
                        $('#card-errors2').css('display','none');
                }
                if( manualInputStates['postalCode']==false){
                    $('#card-errors4').html(errorInputmsg['postalCode']);
                     $('#card-errors4').css('display','block');
                    $("#btnSubmitPay").attr("disabled", false);
                }else{
                        $('#card-errors4').html('');
                        $('#card-errors4').css('display','none');
                }
        if($("#payment-form").valid() && (manualInputStates['cardNumber']==true && manualInputStates['cardExpiry']==true && manualInputStates['cardCvc']==true  && manualInputStates['postalCode']==true))
        {
            var btnObj = this;
            $(btnObj).attr('disabled', true);
            $('#btnSubmitPay').attr("disabled", true);
            
                if($("#google_captcha_action_name_changes").length>0 && $("#google_captcha_action_name_changes").val()==1) //FeatureTag
                {
                    reset_captcha('',CHECKOUT_ACTION);
                }else{
                    reset_captcha();
                }
                pform_submit("payment-form");
           
        }
        }
    }else if($("#CardConnectCreditCardAuthForm").length)
    {
        if($("#click_to_pay_ar_payment_portal").val()==1 && $("#pat_typ_partial").is(":checked") && parseFloat($("#amountPayable_ship").attr("data-amount"))==0){
            process_payment();
        } 
        else{ 
            if($("#CardConnectCreditCardAuthForm").valid()){
                var btnObj = this;
                $(btnObj).attr('disabled', true);
                $('#btnSubmitPay').attr("disabled", true);
                
                    if($("#google_captcha_action_name_changes").length>0 && $("#google_captcha_action_name_changes").val()==1) //FeatureTag
                    {
                        reset_captcha('',CHECKOUT_ACTION);
                    }else{
                        reset_captcha();
                    }
                    pform_submit("CardConnectCreditCardAuthForm");
                
                
            }
        }
        
    }else if($("#AdyenCreditCardAuthForm").length)
    {
        if($("#AdyenCreditCardAuthForm").valid()){
            var btnObj = this;
            $(btnObj).attr('disabled', true);
            $('#btnSubmitPay').attr("disabled", true);
            
                if($("#google_captcha_action_name_changes").length>0 && $("#google_captcha_action_name_changes").val()==1) //FeatureTag
                {
                    reset_captcha('',CHECKOUT_ACTION);
                }else{
                    reset_captcha();
                }                        
                pform_submit("AdyenCreditCardAuthForm");
                        
        }
        
    }else if($("#WorldPayCreditCardAuthForm").length)
    {
        if(act_url=='direct_pay')
        {   
            var btnObj = this;
            $(btnObj).attr('disabled', true);
            $('#btnSubmitPay').attr("disabled", true);
            if($("#google_captcha_action_name_changes").length>0 && $("#google_captcha_action_name_changes").val()==1) //FeatureTag
            {
                reset_captcha('',CHECKOUT_ACTION);
            }else{
                reset_captcha();
            }
            pform_submit("DirectPayAuthForm");
        }else{  
            $('#btnSubmitPay').attr("disabled", true);
            pform_submit("WorldPayCreditCardAuthForm");
        }
    }else if($("#TsysCreditCardAuthForm").length)
    { 
        var btnObj = this;
        $(btnObj).attr('disabled', true);
        $('#btnSubmitPay').attr("disabled", true);
        $.ajax({
            url: BASE_PATH + "/site/verify_captcha",
            type: "POST",
            data: {
                captcha: $("#cc_security #g-recaptcha-response").val(),
                action: $("#cc_security #action").val(),
                UserCaptcha: $("#cc_security #UserCaptcha").length ? $("#cc_security #UserCaptcha").val() : '',
                scode: $("#cc_security #UserCaptcha").length ? $("#cc_security #UserCaptcha").attr('data-val') : ''

            },
            success: function success(res) {
                if($("#google_captcha_action_name_changes").length>0 && $("#google_captcha_action_name_changes").val()==1) //FeatureTag
                {
                    reset_captcha('',CHECKOUT_ACTION);
                }else{
                    reset_captcha();
                }
                var obj = JSON.parse(res);
                if (Object.keys(obj).length > 1 && obj.success == true && obj.action && obj.score == captcha_threshold || Object.keys(obj).length == 1 && obj.success == true) {
                    $('#btnSubmitPay').attr("disabled", true);
                    pform_submit("TsysCreditCardAuthForm");
                } else {
                    $(btnObj).attr('disabled', false);
                    $('.creload:visible').trigger('click');
                    $(".simple_security").fadeIn();
                    $(btnObj).attr('disabled', false);
                     
                        if (obj.message) {
                            $("#cc_security #UserCaptcha").after('<label id="usercaptcha-error" class="error" for="usercaptcha">' + obj.message + '</label>');
                        } else {
                            $("#cc_security #UserCaptcha").after('<label id="usercaptcha-error" class="error" for="usercaptcha">Please enter the security code</label>');
    }
    
                }
            }
}); 
    }
    else if(paypal_flag==1 && $("#PaypalCreditCardAuthForm").length>0)
    {
        if($("#PaypalCreditCardAuthForm").valid()){
            var btnObj = this;
            $(btnObj).attr('disabled', true);
            $('#btnSubmitPay').attr("disabled", true);
            
                if($("#google_captcha_action_name_changes").length>0 && $("#google_captcha_action_name_changes").val()==1) //FeatureTag
                {
                    reset_captcha('',CHECKOUT_ACTION);
                }else{
                    reset_captcha();
                }                      
                pform_submit("PaypalCreditCardAuthForm");
            
            
        }
        
    }else if($("#paylaterAuthForm").length && $("#click_to_pay_ar_payment_portal").val()==1){
        //if($("#paylaterAuthForm").valid() || true){
            var btnObj = this;
            $(btnObj).attr('disabled', true)
            if($("#google_captcha_action_name_changes").length>0 && $("#google_captcha_action_name_changes").val()==1) //FeatureTag
            {
                reset_captcha('',CHECKOUT_ACTION);
            }else{
                reset_captcha();
            }                     
            if($.trim($("#amountPayable_ship").attr("data-amount"))<=0){
                $(".pl_error").html("Pay Later Amount should not be zero or empty!"); 
                $(btnObj).attr('disabled', false)
            }else{
                pform_submit("paylaterAuthForm");
            }
            
            /*
            var btnObj = this;
            $(btnObj).attr('disabled', true);
            $('#btnSubmitPay').attr("disabled", true); 
            $.ajax({
                url: BASE_PATH + "/site/verify_captcha",
                type: "POST",
                data: {
                    captcha: $("#cc_security #g-recaptcha-response").val(),
                    action: $("#cc_security #action").val(),
                    UserCaptcha: $("#cc_security #UserCaptcha").length ? $("#cc_security #UserCaptcha").val() : '',
                    scode: $("#cc_security #UserCaptcha").length ? $("#cc_security #UserCaptcha").attr('data-val') : ''

                },
                success: function success(res) {
                    if($("#storefront_order_processing_method_upgrade").length>0 && $("#storefront_order_processing_method_upgrade").val()==1){}else{ //FeatureTag
                        reset_captcha();
                    }
                    var obj = JSON.parse(res);
                    if (Object.keys(obj).length > 1 && obj.success == true && obj.action && obj.score == captcha_threshold || Object.keys(obj).length == 1 && obj.success == true) {
                        $('#btnSubmitPay').attr("disabled", true);
                        if($.trim($("#amountPayable_ship").attr("data-amount"))<=0){
                            $(".pl_error").html("Pay Later Amount should not be zero or empty!"); 
                            
                           }else{
                                pform_submit("paylaterAuthForm");
                           }
                          
            
                    } else {
                        $(btnObj).attr('disabled', false);
                        $('.creload:visible').trigger('click');
                        if($("#storefront_order_processing_method_upgrade").length>0 && $("#storefront_order_processing_method_upgrade").val()==1){
                            prevent_cc_testing();
                        }
                        $(".simple_security").fadeIn();
                        $(btnObj).attr('disabled', false);
                         
                            if (obj.message) {
                                $("#cc_security #UserCaptcha").after('<label id="usercaptcha-error" class="error" for="usercaptcha">' + obj.message + '</label>');
                            } else {
                                $("#cc_security #UserCaptcha").after('<label id="usercaptcha-error" class="error" for="usercaptcha">Please enter the security code</label>');
                            }
        
                    }
                }
            });
            */            
        //}                 
    }    
}); 

$(document).on('click', '.btn_place_order', function() {
    $("#signin_signup").show();
    $(".guest_acc").show();
    $.ajax({
        url: BASE_PATH + "/ajax/set_ref",
        success: function(result) {}
    });
});
$(document).on('click', '.guest_form_btn', function() {
    $("#signin_signup").hide();
    window.location.href = BASE_PATH + "/checkout";
});

function show_register_form(){
    $("#span_sign_in").css("display","none");
    $("#span_sign_up").css("display","block");
        if($("#LoginInfoCreateAccountForm:visible").length)
        {
            $("#LoginInfoCreateAccountForm:visible .simple_security").hide();
            if( !$('#LoginInfoCreateAccountForm:visible #g-recaptcha-response').length )
                $('#LoginInfoCreateAccountForm:visible #action').after("<input type='hidden' id='g-recaptcha-response' name='g-recaptcha-response' value=''  >");
            if($("#google_captcha_action_name_changes").length>0 && $("#google_captcha_action_name_changes").val()==1) //FeatureTag
            {
                reset_captcha('',REGISTER_ACTION);
            }else{
                reset_captcha();
            }
        }
   
}

function show_signin_form() {
    $("#span_sign_in").css("display", "block");
    $("#span_sign_up").css("display", "none");
}

function OpenForgotPass() {
    $("#forgot_password").show();
}

function hideshow(which) {
    $(which).hide();
        if ( (CONTROLL == "calendar" && ACTION == "register") || (CONTROLL == "calendar" && ACTION == "reserve") ) 
        {
            window.location.reload();
        }
    
}
$(document).on('click', '#pickup_in_store', function() {
    cart.assignTotal();
});

function shippingMethodChanged(e) {
    var opt = $(e).val();        
    let subTotal = 0.0;
    let ship_cost = 0;  
    subTotal = Number($("#hidden_subTotal").val());
    
    var shipObj = ''
    if($("#deliveryAmount_ship").length){    
        shipObj = $("#deliveryAmount_ship");                       
    }
    if($("#shipping_price").length){    
        shipObj = $("#shipping_price");                       
    }


    if($('#pickup_in_store').length && opt!="pickup_in_store")
    {
        $('#pickup_in_store').prop('checked',false);
    }
    if($('#free_shipping').length && opt!="free_shipping")
    {
        $('#free_shipping').prop('checked',false);
    }
    if($('#flat_rate').length && opt!="flat_rate")
    {
        $('#flat_rate').prop('checked',false);
    }
    if($('#price_based').length && opt!="price_based")
    {
        $('#price_based').prop('checked',false);
    }
    if($('#local_delivery').length && opt!="local_delivery")
    {
        $('#local_delivery').prop('checked',false);
    }
    if($('.ups_shipping').length)
    {
        $('.ups_shipping').prop('checked',false);
    }

    $.ajax({
        url: BASE_PATH+"/api/getShippingCost",
        method: 'post',
        data: {
           "shipping_method":opt,
           'free_shipping_flag': $("#hidden_free_shipping_flag").val()
        },
        success: function(result){
           var json = $.parseJSON(result);
           $("#amountPayable_ship").html(json.total);            
           shipObj.html(json.shipping_price);            
        }
     });
}

function addCommas(nStr) {
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

$(document).on('click', '.alert_place_order', function() {
    $("#go-top").trigger("click");
    cart.showAlert('One or more reservations in your cart has expired. Please add the reservation details again to proceed', 'danger');
});

if ($("#CustomerInfoState").length) {

}
$(document).ready(function() {
    if ($("#CustomerInfoState").length) {
        $("#CustomerInfoState").trigger("change");
    }
});
$(document).on('change', '#CustomerInfoState', function() {
    if($("#remove_duplicitous_shipping_address_step").length>0 && $("#remove_duplicitous_shipping_address_step").val()==1)
    {
        var charter_travel = {};
        $(".charter_travel").each(function() {
            var ct_id = $(this).attr("id");
            var ct_tax = parseFloat($(this).attr("data-tax"));
            var ct_amount = parseFloat($(this).attr("data-amount"));
            charter_travel[ct_id] = {};
            charter_travel[ct_id].tax = ct_tax;
            charter_travel[ct_id].amount = ct_amount;
        });
        $.ajax({
            url: BASE_PATH + "/checkout/getCostSummary",
            method: 'post',
            data: {
                'shipping' : $("#shipping_price").length,
                'state': $(this).val(),
                'charter_travel': charter_travel,
            },
            success: function(result) {
                var json = $.parseJSON(result);
                if (json.charter_travel) {
                    $.each(json.charter_travel, function(i, part) {
                        $("#" + i).html($("#" + i).attr('data-count') + " x " + part.amount);
                    });
                }
                if ($("#cart_tax").length) {
                    $("#cart_tax").html(json.tax);
                }
                $("#amountPayable_ship").html(json.total);
                $("#cart_subtotal").html(json.sub);
            }
        });
    }
    else if($("#trip_deposit_issue").length>0 && $("#trip_deposit_issue").val()==1)
    {
        var charter_travel = {};
        $(".charter_travel").each(function() {
            var ct_id = $(this).attr("id");
            var ct_tax = parseFloat($(this).attr("data-tax"));
            var ct_amount = parseFloat($(this).attr("data-amount"));
            charter_travel[ct_id] = {};
            charter_travel[ct_id].tax = ct_tax;
            charter_travel[ct_id].amount = ct_amount;
        });
        $.ajax({
            url: BASE_PATH + "/checkout/getCostSummary",
            method: 'post',
            data: {
                'shipping' : $("#shipping_price").length,
                'state': $(this).val(),
                'charter_travel': charter_travel,
            },
            success: function(result) {
                var json = $.parseJSON(result);
                if (json.charter_travel) {
                    $.each(json.charter_travel, function(i, part) {
                        $("#" + i).html($("#" + i).attr('data-count') + " x " + part.amount);
                    });
                }
                if ($("#cart_tax").length) {
                    $("#cart_tax").html(json.tax);
                }
                $("#amountPayable_ship").html(json.total);
                $("#cart_subtotal").html(json.sub);
            }
        });
    }
    else{
        var state = $(this).val();
        var cart_tax = parseFloat($("#cart_tax").attr('data-amount'));
        var amountPayable_ship = parseFloat($("#amountPayable_ship").attr("data-amount"));
        var cart_subtotal = parseFloat($("#cart_subtotal").attr("data-amount"));
        var amountPayable_ship1 = '';
        var tt_exempt = 0;
        if($("#remove_duplicitous_shipping_address_step").length>0 && $("#remove_duplicitous_shipping_address_step").val()==1)
        {
            if (state != null && state != '' && state != store_home_state && exempt_tax_out_state == 1) {
                amountPayable_ship1 = amountPayable_ship - cart_tax;
                cart_tax = 0;
                tt_exempt = 1;
            } else {
                amountPayable_ship1 = amountPayable_ship;
            }
        }
        else{
            if (state != '' && state != store_home_state && exempt_tax_out_state == 1) {
                amountPayable_ship1 = amountPayable_ship - cart_tax;
                cart_tax = 0;
                tt_exempt = 1;
            } else {
                amountPayable_ship1 = amountPayable_ship;
            }
        }

        var charter_travel = {};
        $(".charter_travel").each(function() {
            var ct_id = $(this).attr("id");
            var ct_tax = parseFloat($(this).attr("data-tax"));
            var ct_amount = parseFloat($(this).attr("data-amount"));
            charter_travel[ct_id] = {};
            charter_travel[ct_id].tax = ct_tax;
            charter_travel[ct_id].amount = ct_amount;
        });

        $.ajax({
            url: BASE_PATH + "/ajax/set_currency",
            method: 'post',
            data: {
                "tax": cart_tax,
                "total": amountPayable_ship1,
                "sub": cart_subtotal,
                'charter_travel': charter_travel,
                "exempt_tax_out_state": tt_exempt
            },
            success: function(result) {
                var json = $.parseJSON(result);
                if (json.charter_travel) {
                    $.each(json.charter_travel, function(i, part) {
                        $("#" + i).html($("#" + i).attr('data-count') + " x " + part.amount);
                    });
                }
                if ($("#cart_tax").length) {
                    $("#cart_tax").html(json.tax);
                }
                $("#amountPayable_ship").html(json.total);
                $("#cart_subtotal").html(json.sub);
            }
        });
    }

});

function proceed_pay_validate()
{
    var CustomerInfoShippingForm_validate = $("#CustomerInfoShippingForm:visible").validate().checkForm();
    if(  CustomerInfoShippingForm_validate == true)
    {
           var captcha_length_check = $("#CustomerInfoShippingForm:visible #UserCaptchaContactCreate").length; 
       
        if(captcha_length_check)
        {
            $('.proceed_pay').attr('disabled',true);

                var userCreatContactData = {
                    captcha:$("#CustomerInfoShippingForm #g-recaptcha-response").val(),
                    action: "user/contact_create",
                    UserCaptcha : ($("#CustomerInfoShippingForm #UserCaptchaContactCreate").length)?$("#CustomerInfoShippingForm #UserCaptchaContactCreate").val():'',
                    scode : ($("#CustomerInfoShippingForm #UserCaptchaContactCreate").length)?$("#CustomerInfoShippingForm #UserCaptchaContactCreate").attr('data-val'):''

                };
            $.ajax({
                url:BASE_PATH+"/site/verify_captcha",
                type:"POST",
                data: userCreatContactData,
                success:function(res){
                    if($("#google_captcha_action_name_changes").length>0 && $("#google_captcha_action_name_changes").val()==1) //FeatureTag
                    {
                        reset_captcha('',REGISTER_ACTION);
                    }else{
                        reset_captcha();
                    }
                    var obj = JSON.parse(res);
                    if(     (Object.keys(obj).length>1 && obj.success==true && obj.action && obj.score==captcha_threshold) ||  
                            (Object.keys(obj).length==1 && obj.success==true)
                        ) 
                    {
                        $("#CustomerInfoShippingForm #g-recaptcha-response").val('');
                        if($('.proceed_pay').length>0){
                            //$('.proceed_pay').html("Proceed to Shipping");
                            $('.proceed_pay').prop('disabled', false);
                        } 
                        $("#CustomerInfoShippingForm").submit();
                    }
                    else
                    {
                        $("#CustomerInfoShippingForm:visible .simple_security").fadeIn();
                        $('.proceed_pay').attr('disabled',false);
                        $('.creload:visible').trigger('click');                    
                        if(pwd_cap_error==true){
                            if(($("#avalara_tax_api").length>0 && $("#avalara_tax_api").val()==1) || ($("#remove_duplicitous_shipping_address_step").length>0 && $("#remove_duplicitous_shipping_address_step").val()==1)) //FeatureTag
                            {
                                $("#CustomerInfoShippingForm:visible").find("#usercaptcha-error").remove();
                            }
                            if(obj.message){
                                $("#CustomerInfoShippingForm #UserCaptcha").after('<label id="usercaptcha-error" class="error" for="usercaptcha">'+obj.message+'</label>');
                            }else{
                                $("#CustomerInfoShippingForm #UserCaptcha").after('<label id="usercaptcha-error" class="error" for="usercaptcha">Please enter the security code</label>');    
                            }
                        }else{
                                if(obj.message){
                                    $("#CustomerInfoShippingForm #UserCaptchaContactCreate").after('<label id="usercaptcha-error" class="error" for="UserCaptchaContactCreate">'+obj.message+'</label>');
                                }else{
                                    $("#CustomerInfoShippingForm #UserCaptchaContactCreate").after('<label id="usercaptcha-error" class="error" for="UserCaptchaContactCreate">Please enter the security code</label>');    
                                }
                            pwd_cap_error = true;
                        }                    
                    }
                }
            });
        }else{
            var cust_form = 'CustomerInfoShippingForm';
            if(!$("#" + cust_form).validate().checkForm()){
                if($('.proceed_pay').length>0){
                    //$('.proceed_pay').html("Proceed to Shipping");
                    $('.proceed_pay').prop('disabled', false);
                }
            }
            $("#" + cust_form).submit();
        }
    }else{
        $('.proceed_pay').attr('disabled',false);
        var cust_form = 'CustomerInfoShippingForm';
        if(!$("#" + cust_form).validate().checkForm()){
            if($('.proceed_pay').length>0){
                //$('.proceed_pay').html("Proceed to Shipping");
                $('.proceed_pay').prop('disabled', false);
            }
        }
        $("#" + cust_form).submit();
    }
    if(($("#avalara_tax_api").length>0 && $("#avalara_tax_api").val()==1) || ($("#remove_duplicitous_shipping_address_step").length>0 && $("#remove_duplicitous_shipping_address_step").val()==1)) //FeatureTag
    {
        $("#CustomerInfoShippingForm:visible").find("#usercaptcha-error").remove();
        if($("#CustomerInfoShippingForm:visible #UserCaptcha").val()=='')
        {
            $("#CustomerInfoShippingForm:visible #UserCaptcha").after('<label id="usercaptcha-error" class="error" for="usercaptcha">Please enter the security code</label>');       
        }
    }
}




$(document).on('click', '.proceed_pay ', function() {
    //$(".proceed_pay").html("<img src='"+BASE_PATH+"/img/loading1.gif'>Loading...");
    $(this).prop('disabled', true); 
    setTimeout(function()
    {
        var cust_form = 'CustomerInfoShippingForm';
        if ($("#" + cust_form).attr('data-token') != '') {
            $("#" + cust_form).attr('action', '/checkout/payment/' + $("#" + cust_form).attr('data-token'));
        }
        if ($(".ck_email").length > 0 && $(".ck_email").val() != '') {
            $.ajax({
                url: BASE_PATH + "/site/checkEmail",
                type: "post",
                async: false,
                data: {
                    email_id: function() {
                        return $("#CustomerInfoEmail").val();
                    }
                },
                success: function(msg) {
                    if ($.trim(msg) == "false") {
                        $("#signin_signup").show();
                    } else {
                        if($("#avalara_tax_api").length>0 && $("#avalara_tax_api").val()==1) //FeatureTag
                        {
                            proceed_pay_validate();                        
                        }
                        else{
                            if(!$("#" + cust_form).validate().checkForm()){
                                if($('.proceed_pay').length>0){
                                    //$('.proceed_pay').html("Proceed to Shipping");
                                    $('.proceed_pay').prop('disabled', false);
                                }
                            }
                            $("#" + cust_form).submit();
                        }
                        
                    }
                }
            });
        } else {
            if($("#avalara_tax_api").length>0 && $("#avalara_tax_api").val()==1)  //FeatureTag
            {
                proceed_pay_validate();                        
            }
            else{ 
                if(!$("#" + cust_form).validate().checkForm()){
                    if($('.proceed_pay').length>0){
                        //$('.proceed_pay').html("Proceed to Shipping");
                        $('.proceed_pay').prop('disabled', false);
                    }                
                }
                $("#" + cust_form).submit();
            }        
        }
    },1000);
});
function htmlDecode(input) {
  var doc = new DOMParser().parseFromString(input, "text/html");
  return doc.documentElement.textContent;
}
$(document).on('change', '.ck_fname, .ck_lname, .ck_email ', function() {
    var dssf_tmp_id = this.value;
    if (dssf_tmp_id != 'new') {
        var data_type = $(this).attr("data-type");
        if (data_type == 'fname') {
            $(".ck_lname").val(dssf_tmp_id);
            $(".ck_email").val(dssf_tmp_id);
        } else if (data_type == "lname") {
            $(".ck_fname").val(dssf_tmp_id);
            $(".ck_email").val(dssf_tmp_id);
        } else if (data_type == "email") {
            $(".ck_fname").val(dssf_tmp_id);
            $(".ck_lname").val(dssf_tmp_id);
        }
        $("#CustomerInfoFirstName").val(htmlDecode($(".ck_fname").find("option:selected").html())).attr("type", "hidden");
        $("#CustomerInfoLastName").val(htmlDecode($(".ck_lname").find("option:selected").html())).attr("type", "hidden");
        if ($(".ck_email").val() != null) {
            $("#CustomerInfoEmail").val($(".ck_email").find("option:selected").html()).attr("type", "hidden");
            $(".ck_email").removeClass("hide");

            var res = $("#CustomerInfoEmail").val().split(" (");
            $("#CustomerInfoEmail").val(res[0]);

            $.ajax({
                url: BASE_PATH + "/site/checkEmail",
                type: "post",
                async: false,
                data: {
                    email_id: function() {
                        return $("#CustomerInfoEmail").val();
                    }
                },
                success: function(msg) {
                    if ($.trim(msg) == "false") {
                        $("#signin_signup").show();
                    }
                }
            });
        } else {
            $("#CustomerInfoEmail").attr("type", "text").val('');
            $(".ck_email").addClass("hide");
        }


        $("#CustomerInfoDssfTmpId").val(dssf_tmp_id).attr("type", "hidden");
        if ($("#CreditCardFirstName").length > 0) {
            $("#CreditCardFirstName").attr("type", 'hidden').val($(".ck_fname").find("option:selected").html());
        }
        if ($("#CreditCardLastName").length > 0) {
            $("#CreditCardLastName").attr("type", 'hidden').val($(".ck_fname").find("option:selected").html());
        }
    } else {
        $("#CustomerInfoDssfTmpId").val('');
        $(".ck_fname").remove();
        $(".ck_lname").remove();
        $(".ck_email").remove();
        $("#CustomerInfoFirstName").attr("type", 'text').val('');
        $("#CustomerInfoLastName").attr("type", 'text').val('');
        $("#CustomerInfoEmail").attr("type", 'text').val('');
        if ($("#CreditCardFirstName").length > 0) {
            $("#CreditCardFirstName").attr("type", 'text').val('');
            $("#CreditCardLastName").attr("type", 'text').val('');
        }
    }

});


$(document).ready(function() {
    $(".gc_amt_btn").click(function() {
        $(".gc_amt_btn").removeClass('gc-form-selected-btn');
        $(this).addClass('gc-form-selected-btn');

    });
    $("#add_to_cart_gc").click(function() {

        if($("#enable_maintenance_mode_in_add_to_cart_on_sf").length>0 && $("#enable_maintenance_mode_in_add_to_cart_on_sf").val()==1) //FeatureTag
        {
            if(ADD_TO_CART_MAINTENANCE_MODE==1){
                $.notify({
                    title: "<strong class='insufficient-quantity-cart'>Alert: System Maintenance</strong> ",
                    icon: 'glyphicon glyphicon-info-sign',
                    message: ADD_TO_CART_MAINTENANCE_MODE_MSG
                }, {
                    timer: 2000,
                    type: 'danger',
                    animate: {
                        enter: 'animated lightSpeedIn',
                        exit: 'animated lightSpeedOut'
                    }
                });
                setTimeout(function () {
                    window.location.reload();
                },1000); 
                return false;        
            }
        }

        $("#add_to_cart_gc").attr("disabled", true);
        if($("#gc_to_amount").val() == ''){
            $("#gc_to_amount").val($("#custom_gc_amount").val());
        }
        if ($("#gc_to_amount").val() == '' || $("#gc_to_amount").val() == 0) {
            if ($("#gc-amt-error").length == 0)
            {
                if($("#custom_gc_amount").length>0){
                    $("#gc_to_amount").after('<label id="gc-amt-error" style="color:#f00;font-weight:bold;">Please choose or enter gift card amount.</label>');
                }else{
                    $("#gc_to_amount").after('<label id="gc-amt-error" style="color:#f00;font-weight:bold;">Please choose gift card amount.</label>');
                }
            }

            $("#add_to_cart_gc").attr("disabled", false);
            return false;
        } else {
            $("#gc-amt-error").remove();
        }

        if ($("#gc_to_amount").val() < 1) {
            $("#gc_to_amount").after('<label id="gc-amt-error" style="color:#f00;font-weight:bold;">Gift card amount should be greater than 1.</label>');
            $("#add_to_cart_gc").attr("disabled", false);
            return false;
        }

        if ($("#gc_form").valid()) {
            var count = $("#gc_qty").val();
            let params = {
                handle: $(this).attr('data-handle'),
                part_type: 'GiftCertificate'
            };
            var formdata = $("#gc_form").serializeArray();
            $(formdata).each(function(index, obj) {
                params[obj.name] = obj.value;
            });
            var gc_unique_id = new Date().valueOf();
            params['gc_unique_id'] = gc_unique_id;

            xhr.call('getPartDetails', params, 'POST')
                .then(function(data) {
                    if (data.status) {
                        
                        $.notify({
                            from: "bottom",
                            title: "<strong></strong> ",
                            icon: 'glyphicon glyphicon-shopping-cart',
                            message: "Added to your cart successfully...!"
                        }, {
                            timer: 1000,
                            type: 'success',
                            animate: {
                                enter: 'animated lightSpeedIn',
                                exit: 'animated lightSpeedOut'
                            }
                        });
                        
                        data.data.count = count;
                        var gc_am_val = $("#gc_to_amount").val().replace("$", "");
                        if(/^[0-9.+]+$/.test(gc_am_val)){
                            data.data.price = gc_am_val;    
                        }                        
                        data.data.gc_unique_id = gc_unique_id;
                        cart.addPart(data.data);
                        var part_cart_interval = setInterval(function () {
                            if(cart_l>0)
                            {
                                clearInterval(part_cart_interval);
                                window.location.href = BASE_PATH + '/cart';
                            }
                        },1000); 
                        
                    }
                });
            return false;
        } else {
            $("#add_to_cart_gc").attr("disabled", false);
        }

    });
});

$(document).ready(function(){
   checkout_buttons(); 
});
function checkout_buttons()
{
    if($(".item_not_available").length>0)
    {

        if (CONTROLL == "checkout" && ACTION == "index" )
        {
            $(".proceed_pay").attr("disabled",true);
        }
        else if(CONTROLL == "checkout" && ACTION == "shipping")
        {
            $('#shipping_ahref').attr('disabled',true);
        }
        else if(CONTROLL == "checkout" && ACTION == "payment") 
        {
            $('#btnSubmitPay').attr('disabled',true);
        }
        else if (CONTROLL == "products" && ACTION == "cart" )
        {
            if($(".btn_place_order").length>0)
            {
                $(".btn_place_order").attr("disabled",true);
            }
            else if($("#place_order").length>0)
            {
                $("#place_order").attr("disabled",true);
            }
        }
        if (CONTROLL == "checkout")
        {
            setTimeout(function(){
                
                $.notify({
                    title: "",
                    icon: 'glyphicon glyphicon-cart',
                    message: "Please edit your cart and try again."
                }, {
                    offset: {
                        x: 50,
                        y: 200
                    },
                    timer: 1000,
                    type: 'danger',
                    animate: {
                        enter: 'animated lightSpeedIn',
                        exit: 'animated lightSpeedOut'
                    }
                });
                
            },1000);
        }
    }
}
function addToCartReplace(handle, count, cInv,pkg_replace,pkg_price,pkg_replace_price) {
    if($("#enable_maintenance_mode_in_add_to_cart_on_sf").length>0 && $("#enable_maintenance_mode_in_add_to_cart_on_sf").val()==1) //FeatureTag
    {
        if(ADD_TO_CART_MAINTENANCE_MODE==1){
            $.notify({
                title: "<strong class='insufficient-quantity-cart'>Alert: System Maintenance</strong> ",
                icon: 'glyphicon glyphicon-info-sign',
                message: ADD_TO_CART_MAINTENANCE_MODE_MSG
            }, {
                timer: 2000,
                type: 'danger',
                animate: {
                    enter: 'animated lightSpeedIn',
                    exit: 'animated lightSpeedOut'
                }
            });
            setTimeout(function () {
                window.location.reload();
            },1000); 
            return false;        
        }
    }
     var e = document.getElementById("numProductQty");
    var isValid = (!cInv) ? true : e.validity.valid;
    if(handle && isValid) {
        let params = {handle: handle,part_type:'product'};
        xhr.call('getPartDetails', params, 'POST')
            .then(function(data) {
                if(data.status) {
                    data.data.count = count;
                    data.data.pkg_replace = pkg_replace;
                    if(pkg_price!='')
                    {
                        data.data.price = pkg_price;
                    }
                    data.data.pkg_replace_price = pkg_replace_price;
                    cart.addPart(data.data);
                    var part_cart_interval = setInterval(function () {
                        if(cart_l>0)
                        {
                            clearInterval(part_cart_interval);
                            $.notify({
                                from: "bottom",
                                title: "<strong></strong> ",
                                icon: 'glyphicon glyphicon-shopping-cart',
                                message: "Added to your cart successfully...!"
                            },{timer: 1000,type: 'success',animate: {enter: 'animated lightSpeedIn',exit: 'animated lightSpeedOut'}});
                            
                            window.location.reload();
                        }
                    },1000); 
                }
            });
        
    }else if(!e.validity.valid) {
          
          $.notify({
                title: "<strong></strong> ",
                icon: 'glyphicon glyphicon-shopping-cart',
                message: "Insufficient Quantity!"
          },{timer: 1000,type: 'danger',animate: {enter: 'animated lightSpeedIn',exit: 'animated lightSpeedOut'}});
          
        cart.showAlert('Insufficient Quantity!', 'danger');
        location.reload();
    }else {
        
          $.notify({
                title: "<strong></strong> ",
                icon: 'glyphicon glyphicon-shopping-cart',
                message: "Unable to add product to cart!"
          },{timer: 1000,type: 'dangert',animate: {enter: 'animated lightSpeedIn',exit: 'animated lightSpeedOut'}});
          
          cart.showAlert('Unable to add product to cart!', 'danger');
    }
}

if (CONTROLL == "checkout" && (ACTION == "payment" || ACTION == "confirm") ) 
{
    (function (global) {
        if(typeof (global) === "undefined")
        {
            throw new Error("window is undefined");
        }
        var _hash = "!";
        var noBackPlease = function () {
            global.location.href += "#";
            global.setTimeout(function () {
                global.location.href += "!";
            }, 50);
        };
        global.onhashchange = function () {
            if (global.location.hash !== _hash) {
                global.location.hash = _hash;
            }
        };
        global.onload = function () {
            noBackPlease();
            document.body.onkeydown = function (e) {
                var elm = e.target.nodeName.toLowerCase();
                if (e.which === 8 && (elm !== 'input' && elm  !== 'textarea')) {
                    e.preventDefault();
                }
                e.stopPropagation();
            };
            
        };
    })(window);
}

$(document).on('click', '.remove_coupon ', function() {
    var c_id = $(this).attr('data-coupon');
    var c_id1 = $(this).attr('data-id');
    $("#coupon_" + c_id1).remove();
    $.ajax({
        url: BASE_PATH + "/api/remove_coupon",
        type: "post",
        async: false,
        data: {
            'coupon_code': c_id,
            'total': $("#amountPayable_ship").attr("data-amount")
        },
        success: function(result) {
            var obj = jQuery.parseJSON(result);
            $("#amountPayable_ship").attr("data-amount", obj.total).html(obj.tot_label);
            $("#coupon_value").html(obj.reward_val_label);
            $("#coupon_value").attr("data-amount", obj.reward_value);
            $("#coupon_code").attr('readonly', false);
                $(".coupon_success").addClass("hide");
            $.notify({
                from: "bottom",
                title: "<strong></strong> ",
                icon: 'glyphicon glyphicon-tags',
                message: ' Coupon removed successfully...!'
            }, {
                timer: 1000,
                type: 'success',
                animate: {
                    enter: 'animated lightSpeedIn',
                    exit: 'animated lightSpeedOut'
                }
            });
            
            
        }
    });
});
$(document).on('click', '#apply_coupon ', function() {
    var btnObj = $(this);
    if (CONTROLL == "checkout" && ACTION == "index") {
        var coupon_code = $("#coupon_code").val();
        if (coupon_code != '') {
            $.ajax({
                url: BASE_PATH + "/api/checkCouponValidity",
                type: "post",
                async: false,
                data: {
                    'coupon_code': coupon_code,
                    'total': $("#amountPayable_ship").attr("data-amount"),
                    'reward_value': $("#coupon_value").attr("data-amount")
                },
                success: function(result) {
                    var obj = jQuery.parseJSON(result);
                    if (obj.status == 1) {
                        $("#amountPayable_ship").attr("data-amount", obj.data.total).html(obj.data.tot_label);
                        $("#coupon_value").html(obj.data.reward_val_label);
                        $("#coupon_value").attr("data-amount", (parseFloat(obj.data.reward_value)+parseFloat($("#coupon_value").attr("data-amount"))) );
                        
                        $.notify({
                            from: "bottom",
                            title: "<strong></strong> ",
                            icon: 'glyphicon glyphicon-tags',
                            message: '  "' + coupon_code + '" has been applied successfully...!'
                        }, {
                            timer: 1000,
                            type: 'success',
                            animate: {
                                enter: 'animated lightSpeedIn',
                                exit: 'animated lightSpeedOut'
                            }
                        });
                        
                            $.each(obj.data.cart, function(i, tcart) {
                                console.log(tcart.id+"====="+tcart.part+"======"+tcart.category);
                                if(tcart.part==true && tcart.category==true)
                                {
                                    $(".coupon_"+tcart.id).removeClass("hide");
                                    console.log("1===="+tcart.id)
                                }
                                else if(tcart.part==true && tcart.category==undefined)
                                {
                                    $(".coupon_"+tcart.id).removeClass("hide");
                                    console.log("2===="+tcart.id)
                                }
                                else if( tcart.part==undefined && tcart.category==true)
                                {
                                    console.log("3===="+tcart.id)
                                    $(".coupon_"+tcart.id).removeClass("hide");
                                }
                            });
                        
                        var loyalty_reward_value = obj.data.reward_val_label1;
                        var loyalty_program_name = obj.data.program_name;
                        var loyalty_program_des = obj.data.description;
                        var str_html = '';
                        var cp_id = 1;
                        if($(".remove_coupon").length>0){
                            cp_id = parseInt($(".remove_coupon").last().attr('data-id'))+1;
                        }
                        str_html += "<div class='row dotted_border' id='coupon_" + cp_id + "'>";
                        str_html += "<div class='col-lg-2 RM_PLR15'>";
                        str_html += "<strong>" + coupon_code + "</strong>";
                        str_html += "</div>";
                        str_html += "<div class='col-lg-8 RM_PLR15'>";
                        str_html += "<strong>" + loyalty_program_name + "</strong> - ";
                        str_html += loyalty_program_des;
                        str_html += "</div>";
                        str_html += "<div class='col-lg-2 RM_PLR15'>";
                        str_html += loyalty_reward_value + "&nbsp;<i class='fa fa-trash-o remove_coupon' data-coupon='" + coupon_code + "' data-id='" + cp_id + "'></i>";
                        str_html += "</div></div>";
                        $("#coupon_details").append(str_html);
                        $("#coupon_code").focus().val('');
                    } else {
                        var msg = '  "' + coupon_code + '" is invalid coupon.';
                        if (obj.message) {
                            msg = obj.message;
                        }
                        $.notify({
                            from: "bottom",
                            title: "<strong></strong> ",
                            icon: 'glyphicon glyphicon-tags',
                            message: msg
                        }, {
                            timer: 1000,
                            type: 'danger',
                            animate: {
                                enter: 'animated lightSpeedIn',
                                exit: 'animated lightSpeedOut'
                            }
                        });
                        
                        $("#coupon_code").focus().val('');
                    }
                }
            });
        } else {
            $("#coupon_code").focus().val('');
            $.notify({
                from: "bottom",
                title: "<strong></strong> ",
                icon: 'glyphicon glyphicon-tags',
                message: 'Please enter the coupon..!'
            }, {
                timer: 1000,
                type: 'danger',
                animate: {
                    enter: 'animated lightSpeedIn',
                    exit: 'animated lightSpeedOut'
                }
            });
        }
    }
});
$(document).on('click', '.remove_gc ', function() {
    $("#gc_serial_number").attr('readonly',false);
    $('#pay_by').attr("disabled",false);
    
    $(".gc_error").html("");
    var gc_serial_number = $(this).attr('data-gc');
    $("tr." +gc_serial_number).remove();

    if($(".gc_serial_number_list").find('tr').length==1)
    {
        $(".gc_serial_number_list").addClass("hide");
    }
    $("#gc_apply").attr('disabled',false);
    
    $.ajax({
        url: BASE_PATH + "/api/removeGiftSerialNumber",
        type: "post",
        async: false,
        data: {
            'gc_serial_number': gc_serial_number,
            'total': $("#amountPayable_ship").attr("data-amount")
        },
        success: function(result) {
            var obj = jQuery.parseJSON(result);
            
             if($("#click_to_pay_ar_payment_portal").val()==1){
                if(obj.total_gc_price>0)
                {
                    var str_html = '';
                    str_html += "<div class='panel panel-default'>";
                    str_html += "<div class='panel-heading'>";                    
                    str_html += "<div class='row gc_disc' id='gc_discount' data-amount='"+obj.total_gc_price+"'>";                    
                    str_html += "<div class='col-lg-10 RM_PLR15'>";
                    str_html += "<strong>Gift Certificate</strong>";
                    str_html += "</div>";
                    str_html += "<div class='col-lg-2 RM_PLR15' style='text-align:right'>";
                    str_html +=  obj.total_gc_price_label;
                    str_html += "</div></div>";                
                    str_html += "<div class='row gc_discount_amt_due' id='gc_discount' data-amount='"+obj.total_gc_price+"'>";
                    str_html += "<div class='col-lg-10 RM_PLR15'>";
                    str_html += "<strong>Amount Due</strong>";
                    str_html += "</div>";
                    str_html += "<div class='col-lg-2 RM_PLR15 amt_due'  style='text-align:right'>";
                    str_html +=  obj.total_label;
                    str_html += "</div></div>";
                    
                    str_html += "</div>";
                    str_html += "</div>";

                    console.log('pay_rm_length',$(".pay_rm").length);
                    console.log('gc_discount',$("#gc_discount").length);
                    if($(".pay_rm").length > 0){
                        $(".gc_disc").parent().parent().remove();
                    }else{
                    if($("#gc_discount").length>0)
                    {
                        $("#gc_discount").parent().parent().remove();
                    }
                    }

                    console.log(str_html);
                    $(".costSummary").append(str_html);    
                    $("#amountPayable_ship").attr("data-amount",obj.total);
                }
                else
                {   console.log('pay_late_lable length', $(".pay_late_lable").length);
                    if($("#click_to_pay_ar_payment_portal").val()==1 && $(".pay_late_lable").length > 0){
                        
                        $(".gc_disc").remove();
                        $("#amountPayable_ship").attr("data-amount",obj.total);
                        $("#pay_late_amt_disp").html(obj.total_label);
                        $(".amt_due").html(obj.total_label);                    
                    }else{      
                        $(".gc_disc").parent().parent().remove();             
                    // $("#gc_discount").parent().parent().remove();
                    if($("#click_to_pay_ar_payment_portal").val()==1){
                        $("#amountPayable_ship").attr("data-amount",obj.total);
                        $(".amt_due").html(obj.total_label); 
                    }
                    else{
                    $("#amountPayable_ship").attr("data-amount",obj.total).html(obj.total_label);
                    }                
                    }
                }
            }else {
            
            if(obj.total_gc_price>0)
            {
                var str_html = '';
                str_html += "<div class='panel panel-default'>";
                str_html += "<div class='panel-heading'>";
                str_html += "<div class='row' id='gc_discount' data-amount='"+obj.total_gc_price+"'>";
                str_html += "<div class='col-lg-10 RM_PLR15'>";
                str_html += "<strong>Gift Certificate</strong>";
                str_html += "</div>";
                str_html += "<div class='col-lg-2 RM_PLR15' style='text-align:right'>";
                str_html +=  obj.total_gc_price_label;
                str_html += "</div></div>";
                str_html += "<div class='row' id='gc_discount' data-amount='"+obj.total_gc_price+"'>";
                str_html += "<div class='col-lg-10 RM_PLR15'>";
                str_html += "<strong>Amount Due</strong>";
                str_html += "</div>";
                str_html += "<div class='col-lg-2 RM_PLR15' style='text-align:right'>";
                str_html +=  obj.total_label;
                str_html += "</div></div>";
                str_html += "</div>";
                str_html += "</div>";
                if($("#gc_discount").length>0)
                {
                    $("#gc_discount").parent().parent().remove();
                }
                $(".costSummary").append(str_html);    
            }
            else
            {
                $("#gc_discount").parent().parent().remove();
            }
            
            $("#amountPayable_ship").attr("data-amount",obj.total).html(obj.total_label);

                if(parseFloat(obj.total)==0){
                   if(old_act_url=="world_pay_auth"){
                        $("#WorldPayCreditCardAuthForm").attr("action", "/checkout/direct_pay");
                        $("#WorldPayCreditCardAuthForm").attr("id","DirectPayAuthForm");
                   } 
                   act_url = 'direct_pay';
                }else{
                    act_url = old_act_url;
                    if(old_act_url=="world_pay_auth"){
                        $("#DirectPayAuthForm").attr("id","WorldPayCreditCardAuthForm");
                        $("#WorldPayCreditCardAuthForm").attr("action", "/checkout/world_pay_auth");
                    } 
                    if(paypal_flag==1){
                        $("#btnSubmitPay").hide();
                        $("#paypal-button-container").html("");
                        initPayPalButton();
                    }
                }
            }
            
            if(obj.total>0)
            {
                if($("#click_to_pay_ar_payment_portal").val()==1){
                    $("#card_pay").show();
                    $('#credit').css('display','inline');                   
                    $('#credit').prop('checked', true);
                    $('#credit').next('.pay_m').css('display','inline');
                    $('#credit-handkey-exist').css('display','inline');
                    $('.pay_m_type').css('display','inline');  
                    $('#save_vault').show();          
                } 
                
                if($(".gc_serial_number_list").find('tr').length==1)
                {
                    paybtn();
                }else{
                    $("#gc_serial_number").focus();
                    var emsg = "<p>The gift certificate you have entered don't have sufficient balance to complete the order. Enter an additional gift certificate or use credit card to pay the balance</p>";
                    var eclass = "gc_error";
                    paybtn(eclass,emsg);
                }
            }else{
                paybtn();
            }



            $.notify({
                from: "bottom",
                title: "<strong></strong> ",
                icon: 'glyphicon glyphicon-tags',
                message: ' Gift Certificate Number removed successfully...!'
            }, {
                timer: 1000,
                type: 'success',
                animate: {
                    enter: 'animated lightSpeedIn',
                    exit: 'animated lightSpeedOut'
                }
            });
        }
    });
});
$(document).on('keypress', '#gc_serial_number', function(event){
    if (event.keyCode === 13) {
        if($("#check_gc_balance").length>0){
            $("#check_gc_balance").trigger("click");
        }
        else if($("#gc_apply").length>0){
            $("#gc_apply").trigger("click");
        }
    }
});
$(document).on('keypress', '#UserCaptcha', function(event){
    if (event.keyCode === 13) {
        if($("#gc_captcha_verify").length>0){
            $("#gc_captcha_verify").trigger("click");
        }        
    }
});
$(document).on('click', '#gc_captcha_verify', function() {
    $('#gc_captcha_verify').attr("disabled",true).html("<img src='"+BASE_PATH +"/img/loading1.gif'>");
        if($("#UserCaptchaGiftCard").is(":visible") && $("#UserCaptchaGiftCard").val()!='') {
            var gc_captcha_data = { 
                'captcha_code':$("#UserCaptchaGiftCard").val(),   
                'action'   : 'user/redeem_gift_card'
            };
        }else{
           $(".gc_error").html("Please enter the captcha code"); 
           $('#gc_captcha_verify').attr("disabled",false).html("Submit");
           return false;
        }
    $.ajax({
        url: BASE_PATH + "/api/verifycaptcha",
        type: "post",
        async: false,
        data: gc_captcha_data,
        success: function(result) {
            setTimeout(function(){$('#gc_captcha_verify').attr("disabled",false).html("Submit");},1200);
            var obj = jQuery.parseJSON(result);
            if (obj.status == 0) {
                $(".gc_error").html("Invalid Captcha Code");
                gc_apply_click++;
                $(".creload:visible").trigger("click");
            }else{
                $(".gc_error").html("");
                $("#gc_serial_number").parent().parent().parent().removeClass("hide");
                $(".gc_captcha").addClass("hide");
                $("#gc_serial_number").focus();
                gc_apply_click = 0;
                if($(".gc_serial_number_list").find('tr').length>1)
                {
                    $(".gc_serial_number_list").removeClass("hide");
                }
                if(parseFloat($("#amountPayable_ship").attr("data-amount"))>0 && $(".gc_serial_number_list").find('tr').length>1)
                {
                    var err_msg = "<p>The gift certificate you have entered don't have sufficient balance to complete the order. Enter an additional gift certificate or use credit card to pay the balance</p>";
                    $(".gc_error").html(err_msg);
                }
                
            }
        }
    });
});
var gc_apply_click = 0;
$(document).on('click', '#gc_apply', function() {
    $('#gc_apply').attr("disabled",true).html("<img src='"+BASE_PATH +"/img/loading1.gif'>");
    if(gc_apply_click>=4)
    {
        $(".gc_captcha").removeClass("hide");
        $(".creload:visible").trigger("click");
        $("#UserCaptcha:visible").val("");
        $("#gc_serial_number").val("");
        $("#gc_serial_number").parent().parent().parent().addClass("hide");
        if($(".gc_serial_number_list").find('tr').length>1)
        {
            $(".gc_serial_number_list").addClass("hide");
        }
        $(".gc_error").html("");
        $('#gc_apply').attr("disabled",false).html("Apply");
        return false;
    }
    
    // if($("#UserCaptcha").is(":visible") && $("#UserCaptcha").val()=='') 
    // {
    //     $("#UserCaptcha").focus();
    //     $(".gc_error").html("Please enter the captcha code");  
    //     return false;
    // }
    
    $('#btnSubmitPay').attr("disabled", false);
    var gc_serial_number = $.trim($("#gc_serial_number").val());
    if(gc_serial_number=='')
    {
        $.notify({
            from: "bottom",
            title: "<strong></strong> ",
            icon: 'glyphicon glyphicon-gift',
            message: '  <b>Please enter Gift Certificate Number...!</b>'
        }, {
            timer: 1000,
            type: 'danger',
            offset: {   x: 50,  y: 200  },
            animate: {
                enter: 'animated lightSpeedIn',
                exit: 'animated lightSpeedOut'
            }
        });
        gc_apply_click++;
        $('#gc_apply').attr("disabled",false).html("Apply");
    }
    else
    {

            var gc_data = { 'gc_serial_number': gc_serial_number, 'total': parseFloat($("#amountPayable_ship").attr("data-amount"))   };

        // if($("#UserCaptcha").is(":visible") && $("#UserCaptcha").val()!='') 
        // {
        //     var gc_data = { 'gc_serial_number': gc_serial_number, 'total': $("#amountPayable_ship").attr("data-amount"), 'gc_captcha':$("#UserCaptcha").val()   };
        // }
        $.ajax({
            url: BASE_PATH + "/api/getGiftserialBalance",
            type: "post",
            async: false,
            data: gc_data,
            success: function(result) {
                setTimeout(function(){ $('#gc_apply').attr("disabled",false).html("Apply"); },1200);
                if($(".creload").is(":visible"))
                {
                    $(".creload:visible").trigger("click");
                    $("#UserCaptcha").val("");
                }
                var obj = jQuery.parseJSON(result);

                if (obj.status == 0) 
                {
                    $(".gc_error").html(obj.message);
                    gc_apply_click++;
                    paybtn();
                }
                else if(obj.status==1)
                {
                    if($("#click_to_pay_ar_payment_portal").val()==1){                  
                        if($(".pay_late_amt_due").length > 0){
                            $(".pay_late_amt_due").css('display','none');
                        }
                        if($(".gc_discount_amt_due").length >0){
                            $(".gc_discount_amt_due").css('display','none');
                        }
                        var str_html = '';
                        str_html += "<div class='panel panel-default'>";
                        str_html += "<div class='panel-heading'>";                        
                        str_html += "<div class='row gc_disc' id='gc_discount' data-amount='"+obj.total_gc_price+"'>";
                        str_html += "<div class='col-lg-10 RM_PLR15'>";
                        str_html += "<strong>Gift Certificate</strong>";
                        str_html += "</div>";
                        str_html += "<div class='col-lg-2 RM_PLR15'  style='text-align:right'>";
                        str_html +=  obj.total_gc_price_label;
                        str_html += "</div></div>";
                        str_html += "<div class='row gc_discount_amt_due' id='gc_discount' data-amount='"+obj.total_gc_price+"'>";
                        str_html += "<div class='col-lg-10 RM_PLR15'>";
                        str_html += "<strong>Amount Due</strong>";
                        str_html += "</div>";
                        str_html += "<div class='col-lg-2 RM_PLR15 amt_due'  style='text-align:right'>";
                        str_html +=  obj.total_label;
                        str_html += "</div></div>";
                        str_html += "</div>";
                        str_html += "</div>";
                        //console.log('pay_late length',$(".pay_late_lable").length);
                        //console.log('gift card length',$("#gc_discount").length);
                        //console.log('gc_disc',$(".gc_disc").length);
                        if($(".pay_late_lable").length >0 && $(".gc_disc").length >0){
                            $(".gc_disc").parent().remove();
                            //console.log("gift card exist");
                        }
                        else if($(".pay_late_lable").length >0){
                            //console.log("pay later exist");
                        }
                        else if($("#gc_discount").length>0)
                        {
                            console.log("pay later not exist and gift card exist");
                            $("#gc_discount").parent().parent().remove();
                        }
                        if($("#cannot_proceed_to_checkout_when_paying_with_a_gift_card").length>0 && $("#cannot_proceed_to_checkout_when_paying_with_a_gift_card").val()==1){
                            if(parseFloat(obj.total)==0 && paypal_flag==1){
                                if(old_act_url=="paypal_auth"){
                                    $("#PaypalCreditCardAuthForm").attr("action", "/checkout/direct_pay");
                                }
                                act_url = 'direct_pay';
                                if(paypal_flag==1){
                                    $("#btnSubmitPay").show();
                                }
                            } 
                        }
                        $("#amountPayable_ship").attr("data-amount",obj.total);
                        $(".costSummary").append(str_html);
                        var str = "<tr class='tx_gc "+gc_serial_number+"'><td>"+gc_serial_number+" <a  href='javascript:void(0);' class='remove_gc' data-gc='"+gc_serial_number+"'>Remove</a></td><td>"+obj.gc_price_applied_label+"</td></tr>";
                        $(".gc_serial_number_list").removeClass("hide").append(str);
                        $("#gc_serial_number").val('');
                        $(".gc_error").html(obj.message); //.fadeIn();
                    }else{
                        var str_html = '';
                        str_html += "<div class='panel panel-default'>";
                        str_html += "<div class='panel-heading'>";
                        str_html += "<div class='row' id='gc_discount' data-amount='"+obj.total_gc_price+"'>";
                        str_html += "<div class='col-lg-10 RM_PLR15'>";
                        str_html += "<strong>Gift Certificate</strong>";
                        str_html += "</div>";
                        str_html += "<div class='col-lg-2 RM_PLR15'  style='text-align:right'>";
                        str_html +=  obj.total_gc_price_label;
                        str_html += "</div></div>";
                        str_html += "<div class='row' id='gc_discount' data-amount='"+obj.total_gc_price+"'>";
                        str_html += "<div class='col-lg-10 RM_PLR15'>";
                        str_html += "<strong>Amount Due</strong>";
                        str_html += "</div>";
                        str_html += "<div class='col-lg-2 RM_PLR15'  style='text-align:right'>";
                        str_html +=  obj.total_label;
                        str_html += "</div></div>";
                        str_html += "</div>";
                        str_html += "</div>";
                        if($("#gc_discount").length>0)
                        {
                            $("#gc_discount").parent().parent().remove();
                        }
                       

                            if(parseFloat(obj.total)==0){
                                if(old_act_url=="world_pay_auth"){
                                    $("#WorldPayCreditCardAuthForm").attr("action", "/checkout/direct_pay");
                                } 
                                if($("#cannot_proceed_to_checkout_when_paying_with_a_gift_card").length>0 && $("#cannot_proceed_to_checkout_when_paying_with_a_gift_card").val()==1){
                                    if(old_act_url=="paypal_auth"){
                                        $("#PaypalCreditCardAuthForm").attr("action", "/checkout/direct_pay");
                                    } 
                                }
                               
                               act_url = 'direct_pay';

                               if(paypal_flag==1){
                                    $("#btnSubmitPay").show();
                                }

                            }else{
                                act_url = old_act_url;
                                if(old_act_url=="world_pay_auth"){
                                    $("#WorldPayCreditCardAuthForm").attr("action", "/checkout/world_pay_auth");
                                } 
                                if(paypal_flag==1){
                                    $("#btnSubmitPay").hide();
                                    $("#paypal-button-container").html("");
                                    initPayPalButton();
                                }
                            }
                        
                        $("#amountPayable_ship").attr("data-amount",obj.total);
                        $(".costSummary").append(str_html);
                        var str = "<tr class='tx_gc "+gc_serial_number+"'><td>"+gc_serial_number+" <a  href='javascript:void(0);' class='remove_gc' data-gc='"+gc_serial_number+"'>Remove</a></td><td>"+obj.gc_price_applied_label+"</td></tr>";
                        $(".gc_serial_number_list").removeClass("hide").append(str);
                        $("#gc_serial_number").val('');
                        $(".gc_error").html(obj.message); //.fadeIn();
                    }
                    
                    if(obj.total==0)
                    {
                        $("#gc_serial_number").attr('readonly',true);
                        $("#gc_apply").attr('disabled',true);
                        
                        if($("#click_to_pay_ar_payment_portal").val()==1){
                                $("#card_pay").hide();
                                $('#credit').css('display','none');                 
                                $('#credit').prop('checked', false);
                                $('#credit').next('.pay_m').css('display','none');
                                $('#credit-handkey-exist').css('display','none');
                                $('.pay_m_type').css('display','none'); 
                                $('#save_vault').hide();
                            }else{                      
                            $('#credit-handkey').attr("disabled",true);
                            $('#credit-handkey-exist').attr("disabled",true);
                            $('#puchase_order').attr("disabled",true);                            
                            }
                        
                        $('#pay_by').attr("disabled",true);
                        paybtn();
                    }else{
                        $("#gc_serial_number").focus();
                        var emsg = "<p>The gift certificate you have entered don't have sufficient balance to complete the order. Enter an additional gift certificate or use credit card to pay the balance</p>";
                        var eclass = "gc_error";
                        paybtn(eclass,emsg);
                    }
                    gc_apply_click = 0;

                }
            }
        });
    }
});
$(document).on('click', '#pay_by ', function() {
    $('#btnSubmitPay').attr("disabled", false);
        if($("#button_state").val()==0){
            $('#btnSubmitPay').attr("disabled", true);
        }
    
    var action = $(this).attr("data-action");
    if(action=="gc")
    { 
        $('#worldpay_redirect_txt').css('display','none');
        if(paypal_flag==1){
            $(this).attr("data-action",'cc').html('<i class="fa fa-credit-card"></i> Pay by Paypal');
        }else{
            $(this).attr("data-action",'cc').html('<i class="fa fa-credit-card"></i> Pay by Credit Card');
        }
        $("#gc_pay").removeClass("hide");
        $("#card_pay").addClass("hide");
        $(".pay_m").html('Gift Certificate');
        paybtn();

        $(".gc_error").html("");
        $("#gc_serial_number").parent().parent().parent().removeClass("hide");
        $(".gc_captcha").addClass("hide");
        $("#gc_serial_number").focus();
        gc_apply_click = 0;
        if($(".gc_serial_number_list").find('tr').length>1)
        {
            $(".gc_serial_number_list").removeClass("hide");
        }
        if(parseFloat($("#amountPayable_ship").attr("data-amount"))>0 && $(".gc_serial_number_list").find('tr').length>1)
        {
            var err_msg = "<p>The gift certificate you have entered don't have sufficient balance to complete the order. Enter an additional gift certificate or use credit card to pay the balance</p>";
            $(".gc_error").html(err_msg);
        }

    }
    else
    {   $('#worldpay_redirect_txt').css('display','block');
        $(this).attr("data-action",'gc').html('<i class="fa fa-gift"></i> Pay by Gift Certificate');
        $("#gc_pay").addClass("hide");
        $("#card_pay").removeClass("hide");
        if(paypal_flag==1){
            $(".pay_m").html('Paypal');
            $("#paypal-button-container").html("");
            initPayPalButton();
        }else{
            $(".pay_m").html('Credit Card');
        }

        $('#btnSubmitPay').attr("disabled", false);
            if($("#button_state").val()==0){
                $('#btnSubmitPay').attr("disabled", true);
            }
        
    }
});

function paybtn(eclass='',emsg='')
{
    if($("#CreditCardCardNumber").length>0){
        var cccn = $("#CreditCardCardNumber").val();
    }else
    {
        var cccn = $("#CreditCardCardNumber").val();
    }
    var cccv = $("#CreditCardCvv").val();
    var cce = $("#CreditCardExpiry").val();
    var ccn = $("#CreditCardName").val();
    var amountPayable_ship = parseFloat($("#amountPayable_ship").attr("data-amount"));
    if( (cccn=='' || cccv=='' || cce=='' || ccn=='' || $("#WorldPayCreditCardAuthForm").length) && amountPayable_ship>0 )
    {
        $('#btnSubmitPay').attr("disabled", true);    
    }
    else
    {
        $('#btnSubmitPay').attr("disabled", false);
    }
    if(emsg!='')
    {
        $('#btnSubmitPay').attr("disabled", true);
        $("."+eclass).append(emsg);  
    }
    
    if($("#click_to_pay_ar_payment_portal").val()==1){  
        $('#btnSubmitPay').attr("disabled", false);
    }
}
$(document).on('click', '.return_to_cart', function(){
    window.location = BASE_PATH+"/cart";
    return false;
});




if (CONTROLL == "checkout") {
    jQuery(document).ready(function($) 
    {
        if("#back" == location.hash){
            window.location = BASE_PATH+"/cart";
            return false;
        }
        if (window.history && window.history.pushState) 
        {
            $(window).on('popstate', function() {
                var hashLocation = location.hash;
                if(hashLocation!='')
                {
                    var hashSplit = hashLocation.split("#!/");
                    var hashName = hashSplit[1];
                    if (hashName !== '') {
                        var hash = window.location.hash;
                        if (hash === '') {
                            //alert('Back button was pressed.');
                            //window.location = 'www.example.com';
                            return false;
                        }
                    }
                }
            });
            window.history.pushState('forward', null, '#back');
        }
    });
}

if (CONTROLL == "checkout" && ACTION == "payment" )
{
    var tx = 0;
    $(window.parent.window).on('popstate', function () {               
        tx++;
        if(tx%2==1 && tx>3 )
        {
            window.location = BASE_PATH+"/cart";
            return false;
        }
        else if(tx%2==0 && tx>4 )
        {
            window.location = BASE_PATH+"/cart";
            return false;
        }

    });
}


    $(document).on('change', '#CustomerInfoCountry, #CreditCardCountry', function () {
        if($("#storefront_not_accept_state_abbrevations_for_australia").length>0 && $("#storefront_not_accept_state_abbrevations_for_australia").val()==1)//FeatureTag
        {
            if($(this).val()!="US" && $(this).val()!="CA" && $(this).val()!="AU")
            {
                $(".dive_states").addClass("hide");
                $(".dive_states1").removeClass("hide");                    
            }else{
                $(".dive_states").removeClass("hide");
                if($(".dive_states1").val()==''){
                    $(".dive_states1").val($("#target option:first").val());
                }
                $(".dive_states1").addClass("hide");
            }
        }else{
            if($(this).val()!="US" && $(this).val()!="CA")
            {
                $(".dive_states").addClass("hide");
                $(".dive_states1").removeClass("hide");                    
            }else{
                $(".dive_states").removeClass("hide");
                if($(".dive_states1").val()==''){
                    $(".dive_states1").val($("#target option:first").val());
                }
                $(".dive_states1").addClass("hide");
            }
        }    
    });
    
    
$(document).on('click', '#pay_later_apply', function() {
    // $('#pay_later_apply').attr("disabled",true).html("<img src='"+BASE_PATH +"/img/loading1.gif'>");
    
    // $('#btnSubmitPay').attr("disabled", false);
    var pay_later_amt = $.trim($("#pay_later_amt").val());
    if(pay_later_amt=='' || pay_later_amt == 0)
    {
        $(".pl_error").html("Pay Later Amount should not be empty!");                    
    }
    else if(parseFloat($("#pay_later_amt").val()) >= parseFloat($("#amountPayable_ship").attr("data-amount"))){
        $(".pl_error").html("Pay Later Amount should be less than the amount due!");        
    }
    else
    {
        $.ajax({
            url: BASE_PATH + "/site/check_paylater_limit",
            type: "post",
            async: false,
            data: {
                total: parseFloat($("#pay_later_amt").val()),
                payable_total: parseFloat($("#amountPayable_ship").attr("data-amount")),
                is_partial:1
            },
            success: function(result) {
                
                // if($(".creload").is(":visible"))
                // {
                //     $(".creload:visible").trigger("click");
                //     $("#UserCaptcha").val("");
                // }
                
                var obj = jQuery.parseJSON(result);          
                obj.pay_later =   
                $(".pl_error").html('');
                if($(".gc_discount_amt_due").length >0){
                    $(".gc_discount_amt_due").css('display','none');
                }
                var str_html = '';
                var payable_total='';
                str_html += "<div class='panel panel-default'>";
                str_html += "<div class='panel-heading'>";
                str_html += "<div class='row pay_rm pay_late_lable' id='gc_discount' data-amount='"+obj.pay_later+"'>";
                str_html += "<div class='col-lg-10 RM_PLR15'>";
                str_html += "<strong>Pay Later</strong>";
                str_html += "</div>";
                str_html += "<div class='col-lg-2 RM_PLR15'  style='text-align:right'>";
                str_html +=  "-"+obj.pay_later_lable;
                str_html += "</div></div>";
                str_html += "<div class='row pay_late_amt_due pay_rm gc_discount_amt_due' id='gc_discount' data-amount='"+obj.pay_later_total+"'>";
                str_html += "<div class='col-lg-10 RM_PLR15'>";
                str_html += "<strong>Amount Due</strong>";
                str_html += "</div>";
                str_html += "<div class='col-lg-2 RM_PLR15 amt_due' id='pay_late_amt_disp'  style='text-align:right'>";
                str_html +=  obj.pay_later_total_lable;
                str_html += "</div></div>";
                str_html += "</div>";
                str_html += "</div>";
                
                
                $("#amountPayable_ship").attr("data-amount",obj.pay_later_total);
                $(".costSummary").append(str_html);                    
                var str = "<tr class='pay_late_error'><td> <a  href='javascript:void(0);' class='remove_pay_later' data-gc='pay_late_rm'>Remove</a></td><td>"+obj.pay_later_lable+"</td></tr>";                    
                $(".pay_late_list").removeClass("hide").append(str);
                $("#pay_later_amt").addClass("hide");
                $("#pay_later_apply").addClass("hide");
                $("#pay_later").attr("disabled",true);
                $("#pat_typ_full").attr("disabled",true);
                $("input:checked + .slider").css("background-color","grey");
            }
        });
    }
});
$(document).on('click', '.remove_pay_later ', function() {
// $('.remove_pay_later,#pat_typ_full,#pay_later').click(function() {
    $("#gc_serial_number").attr('readonly',false);
    $('#pay_by').attr("disabled",false);
    
    $(".pay_late_error").html("");
    var pay_late_rm = $(this).attr('data-gc');
    $("tr." +pay_late_rm).remove();    
    $(".pay_late_list").addClass("hide");  
    $(".pay_late_lable").remove();
    $("#pay_later_amt").removeClass("hide");
    $("#pay_later_apply").removeClass("hide");          
    $('#credit-handkey').attr("disabled",false);
    $('#credit-handkey-exist').attr("disabled",false);
    console.log('pay_later',parseFloat($("#pay_later_amt").val()));
    console.log('amountPayable_ship',parseFloat($("#amountPayable_ship").attr("data-amount")));
    var amountPayable_ship_rm = parseFloat($("#amountPayable_ship").attr("data-amount"))+parseFloat($("#pay_later_amt").val());
    console.log('amountPayable_ship_rm',amountPayable_ship_rm);
    $("#amountPayable_ship").attr("data-amount",amountPayable_ship_rm);
    $(".pay_late_amt_due").attr("data-amount",amountPayable_ship_rm);
    $.ajax({
        url: BASE_PATH + "/site/set_currency_symb",
        type: "post",
        async: false,
        data: {
            total: amountPayable_ship_rm,
        },
        success: function(result) {           
            var obj = jQuery.parseJSON(result);console.log(obj);
            if (obj.status == 1) 
            {
                $("#pay_late_amt_disp").html(obj.total);
                $(".amt_due").html(obj.total); 
            }
        }
    });
     
    $("#pay_later").attr("disabled",false);
    $("#pat_typ_full").attr("disabled",false); 
    $("input:checked + .slider").css("background-color","#2AB934"); 
    $("#pay_later_amt").val('');
    if(parseFloat($("#amountPayable_ship").attr("data-amount"))>0){
        $("#card_pay").show();
        $('#credit').css('display','inline');                   
        $('#credit').prop('checked', true);
        $('#credit').next('.pay_m').css('display','inline');
        $('#credit-handkey-exist').css('display','inline');
        $('.pay_m_type').css('display','inline');
        $('#save_vault').show();            
        $("#exist_card_pay").hide();
        $('#credit-handkey-exist').show();
        $('#credit-handkey-exist').next("span").show();
        $('#credit-handkey').show();
        $('#credit-handkey').next("span").show();   
    }
});




    