var actWindow = true;
var setupdate = true;
var showhideblocks = true;
document.addEventListener("visibilitychange", function() {
    //console.log('visibilitychange 1',document.visibilityState);
    console.log('visibilitychange 2',document.hidden);
    actWindow = !document.hidden;
   
});

function getDataFrom1C(arts,callback,update_amount=false){

        req = {};
        if (update_amount) req.update = 'Y';
        $.post('/cml1c/data/?action=get_amount&sku='+arts,req,function(resp){
            callback(resp);
        })

}
function getDataFrom1Cid(where,idlist,callback,update_amount=false){

    req = {};
    if (update_amount) req.update = 'Y';
    $.post('/cml1c/data/?action=get_amount&'+ where +'='+idlist,req,function(resp){
        callback(resp);
    })

}
function rerenderSkuOutOffProduct(){
        $('.skuoutof').css('display','none');
         if ($('input[name="sku_id"]:checked').length>0){
             $('[data-id-sku-outof="'+ $('input[name="sku_id"]:checked').val() +'"]').css('display','block');
         }
         if ($('input[name="sku_id"][type="hidden"]').length==1){
            $('[data-id-sku-outof="'+ $('input[name="sku_id"][type="hidden"]').val() +'"]').css('display','block');
         }
}

 
function rerenderSkuAmountProduct(){
         console.log('rerenderSkuAmountProduct');
         rerenderSkuOutOffProduct();

         
         if ($('input[name="sku_id"]:checked').length>0 ){

            if (parseInt($('input[name="sku_id"]:checked').attr('data-amount'))==$('input[name="sku_id"]:checked').attr('data-amount')){
                if (parseInt($('input[name="sku_id"]:checked').attr('data-amount'))>0){
                   $('#cart-form [type="submit"], #cart-form-dialog [type="submit"]').prop('disabled',false);
                   $('#cart-form .buy_buttons').css({"display":"block"});
                   $('.plugin_arrived-button').css('display','none');
                   if (parseInt($('input[name="sku_id"]:checked').attr('data-amount'))<criticalAmountSkus){
                       $('.stocks').html('<span class="stock-critical"><i class="fa fa-check-circle fa-lg"></i> '+ CMLT.instock_cr +': '+ $('input[name="sku_id"]:checked').attr('data-amount') +'</span>');
                   }else{
                       $('.stocks').html('<span class="stock-high"><i class="fa fa-check-circle fa-lg"></i> '+ CMLT.instock +'</span>');
                   }
                   
                }else{
                    console.log('am e 1');
                    
                   $('#cart-form [type="submit"], #cart-form-dialog [type="submit"]').prop('disabled',true).attr('disabled','disabled');
                   $('#cart-form .buy_buttons').css({"display":"none"});
                   $('.plugin_arrived-button').css('display','inline');
                   $('.stocks').html('<span class="stock-none"><i class="fa fa-times-circle fa-lg"></i> '+ CMLT.no_stock +'</span>');
                }
            }else{
               console.log('am e 2');
            }
         }
         
         if ($('input[name="sku_id"][type="hidden"]').length==1){
            if (parseInt($('input[name="sku_id"][type="hidden"]').attr('data-amount'))>0){
               $('#cart-form [type="submit"], #cart-form-dialog [type="submit"]').prop('disabled',false);
               $('.plugin_arrived-button').css('display','none');
               if (parseInt($('input[name="sku_id"]:checked').attr('data-amount'))<criticalAmountSkus){
                    $('.stocks').html('<span class="stock-critical"><i class="fa fa-check-circle fa-lg"></i> '+ CMLT.instock_cr +': '+$('input[name="sku_id"]:checked').attr('data-amount')+'</span>');
                }else{
                    $('.stocks').html('<span class="stock-high"><i class="fa fa-check-circle fa-lg"></i> '+ CMLT.instock +'</span>');
                }
            }else{
               $('#cart-form [type="submit"], #cart-form-dialog [type="submit"]').prop('disabled',true).attr('disabled','disabled');
               $('.plugin_arrived-button').css('display','inline');
               $('.stocks').html('<span class="stock-none"><i class="fa fa-times-circle fa-lg"></i> '+ CMLT.no_stock +'</span>');
            }
        }
}
function getAmountProductUnblockForm(){
    $('#cart-form [type="submit"]').css('visibility','visible');
    $('.stocks').addClass('waitloaddata');
    $('#amoload').remove();
    $('.card_wait').addClass('card_wait_show');
    $('.card_wait_status').remove();
}
function getAmountProductBlockForm(){
    if (showhideblocks){
        $('#amoload').remove();
        $('#cart-form [type="submit"]').css('visibility','hidden').before('<span style="font-size:80%; opacity:.5" id="amoload">'+ CMLT.wait_amount +'</span>');
        $('.stocks').removeClass('waitloaddata')
    }
    
}
var getAmountProductTimeout = (60000*3);
var getAmountProductFirstLoad = true;
//add2cart
function getAmountProduct(){

    

    console.log('get amount','init',getAmountProductTimeout);
    
        //$('.card_wait').addClass('card_wait_show');
    
        id_list = [];
        getAmountProductBlockForm();
        
        $('input[name="sku_id"]').each(function(){
           
            id_list.push($(this).val());
            
        }).promise().done( function(){ 

            if (getAmountProductFirstLoad){
                $('.cart-form').addClass('cart-form-loading');
                getAmountProductFirstLoad = false;
            }
            
            if (id_list.length>0){
                setTimeout(function(){
                    getAmountProductUnblockForm();
                },5000);
                console.log('get amount','get data');
                getDataFrom1Cid('sku_ids',id_list.join(','),function(data){

                    $('.cart-form-loading').removeClass('cart-form-loading');

                    console.log('get amount','ok',data);
                    showhideblocks = false;
                    getAmountProductUnblockForm();
                    minCount = 500;
                    for (art in data){

                            sku = data[art];

                            if (typeof(sku.total_amount)!='undefined'){

                                sku.total_amount = parseInt(sku.total_amount);
                                input = $('input[name="sku_id"][value="'+ sku.sku_id +'"]');
                                stock_block = $('.sku-'+ sku.sku_id +'-stock');
                                $(input).attr('onchange','rerenderSkuAmountProduct();');
                                if ($(input).length>0){
                                    $(input).attr('data-amount',sku.total_amount);
                                    if (sku.total_amount>0){
                                        if (sku.total_amount<10 && sku.total_amount<minCount){
                                            minCount = sku.total_amount;
                                            //getAmountProductTimeout = 10000;
                                        }else if (sku.total_amount<100 && sku.total_amount<minCount){
                                            minCount = sku.total_amount;
                                            //getAmountProductTimeout = 30000;
                                        }else{
                                            minCount = sku.total_amount;
                                            //getAmountProductTimeout = 60000;
                                        }
                                    }else{ 
                                        //getAmountProductTimeout = 80000;
                                    }
                                    
                                    console.log('sku',sku.sku_id,sku.total_amount);
                                    
                                    if (sku.total_amount<=0){

                                        $(input).attr('data-disabled','1'); 
                                        $(stock_block).html('<span class="stock-none"><i class="fa fa-times-circle fa-lg"></i> '+ CMLT.no_stock +'</span>');
                                        $('.stocks').html('<span class="stock-none"><i class="fa fa-times-circle fa-lg"></i> '+ CMLT.no_stock +'</span>');
                                    
                                    }else if(sku.total_amount<=criticalAmountSkus){
        
                                        $(input).removeAttr('data-disabled'); 
                                        $(stock_block).html('<span class="stock-critical"><i class="fa fa-check-circle fa-lg"></i> '+ CMLT.instock_cr +': '+ sku.total_amount +'</span>');
                                        $('.stocks').html('<span class="stock-critical"><i class="fa fa-check-circle fa-lg"></i> '+ CMLT.instock_cr +': '+sku.total_amount+'</span>');
        
                                    }else{
        
                                        $(input).removeAttr('data-disabled'); 
                                        $(stock_block).html('<span class="stock-high"><i class="fa fa-check-circle fa-lg"></i> '+ CMLT.instock +'</span>');
                                        $('.stocks').html('<span class="stock-high"><i class="fa fa-check-circle fa-lg"></i> '+ CMLT.instock +'</span>');
                                    }

                                }
                             
                        }else{
                            console.log('not data 1C');
                            
                        }    
                    }
                    rerenderSkuAmountProduct();
                    setTimeout('getAmountProduct()',getAmountProductTimeout);
                },setupdate);
            }
            

         } )
   
}
var getAmountCardTa = null;
function getAmountCard(first){
    
    
    if (getAmountCardTa!=null) clearTimeout(getAmountCardTa);
    if (first){
        $('[name^="quantity["]').each(function(){
            name = $(this).attr('name');
            b = name.split('quantity[');
            id = null;
            if (typeof(b[1])!='undefined') id = parseInt(b[1]);
            if (typeof(id)=='number'){
                $(this).attr('data-cart-item-id',id);
                
            }
        });
    }
    if (!actWindow) {

        getAmountCardTa = setTimeout('getAmountCard()',60000);
        console.log('getAmountCard','skip');
        return false;
    }
    console.log('getAmountCard','load');
    getDataFrom1Cid('cards','y',function(data){
        getAmountCardTa = setTimeout('getAmountCard()',60000);
        for (i in data){
            sku = data[i];

            if (typeof(sku.total_amount)!='undefined' && sku.total_amount==parseInt(sku.total_amount)){

                sku.total_amount = parseInt(sku.total_amount);
                input = $('input[data-cart-item-id='+ sku.card_id +']');
               // console.log('input',input);
                
                if ($(input).length>0){

                        if (sku.total_amount<=0){

                            $(input).css('color','red').attr('title',CMLT.itemend).addClass('error');

                        }else{

                            $(input).css('color','b').attr('title','').removeClass('error');

                        }

                }


            }

            
        }
    },setupdate);
    
}
$(document)
.on('click','button.plus,button.minus',function(){

    if (getAmountCardTa!=null) clearTimeout(getAmountCardTa);
    getAmountCardTa = setTimeout('getAmountCard()',3000);

})
.ready(function(){
    getAmountCard(true);
    rerenderSkuOutOffProduct();
})
.on('change','[name="sku_id"]',function(){
    rerenderSkuOutOffProduct();
})
