

/* Resource 3044 */

;$(function(){
    
    $($('#shoppingLists').parent()).on('click', 'li a', function(){//".dropdown-menu"
        
        if($('#shoppingLists option:contains('+$(this).text()+')').val() === '-1'){
            $('#new_list_name').removeClass('inactive');
            $('#AddProductToList').attr('listId','-1');
        }else{
            $('#new_list_name input').val('');
            $('#AddProductToList').attr('listId',$('#shoppingLists option:contains('+$(this).text()+')').val());
            	
        	$('#new_list_name').addClass('inactive');
        }
        
   	});    

    $.ajax({
        url: "/ActionInvokerGenericAPI.ashx?input=dyn-post&output=json&ActionID=6711",
        type: "post",
        data: 'shoppingLists=1',
        success: function(response, textStatus, jqXHR) {  
             
            var listsNames = '';

            listsNames += '<option value="-1">Numa Nova Lista</option>'; //##New_ShoppingList##            
            
            response.data.forEach(function(ObjectList){
            	listsNames += '<option value="'+ObjectList.id+'">'+ObjectList.listname+'</option>';
            });
            
            $('#shoppingLists').append(listsNames);
            $('#shoppingLists').selectpicker('refresh');
                                    
        },
        error: function(jqXHR, textStatus, errorThrown) {
            if(console.log) console.log("The following error occured: " + textStatus, errorThrown);
            //$("#rmv_"+ref).html(HTMLfromCOLrmv);
        }
    }); 
    
    $('#popup_add_shopping_list').on('show.bs.modal', function(e) {
        //var $modal = $(this);
        var data = JSON.parse(e.relatedTarget.id);
        
        $('#shopping_qty').val($('#input_qtd_'+data.Ref).val());
        $('#shopping_qty').attr('multi',$('#input_qtd_'+data.Ref).attr('multi'));
        
        //$('#AddProductToList').attr('multi',data.Multi);
        
        $('#AddProductToList').attr('ProductId',data.Id);
        $('#AddProductToList').attr('ProductRef',data.Ref);
        $('#AddProductToList').attr('ProductRefAlt',data.RefAlt);
        
    });  
    
    $('#CancelAddToList').on('click',function(){
        $('#error_exists').addClass('hidden'); 
        //$('#new_list_name span').css('border-color','black');
        //$('#new_list_name input').css('border-color','black');  
        $('#new_list_name span').removeAttr('style');
        $('#new_list_name input').removeAttr('style');
        $('#new_list_name input').val('');
        //
        //$('#shoppingLists').parent().find('.selectpicker li').attr('class','');
        //$('#shoppingLists').parent().find('.selectpicker li:first').attr('class','selected');
        //$('#shoppingLists').parent().find('.selectpicker > span:first').text('Seleccione');    
        //$('#shoppingLists').parent().find('button.selectpicker').attr('title','Seleccione')
        $('#AddProductToList').attr('listId','Seleccione');
        $('#shoppingLists option').prop('selected', function() {
            return this.defaultSelected;
        });
        $('#shoppingLists').selectpicker('refresh');        
        // 
        
    });
    
});

    
function isDivisibleByMultiplier(n,multiplier){
    if((n.replace(",",".") % multiplier.toString().replace(",",".")) != 0){
        return false;
    }
    else{
        return true;
    }
}

function add_article_to_shoppingList(){
    var qtdMultiplier=1;
    if($('#shopping_qty').attr("multi").length>0)
        qtdMultiplier = $('#shopping_qty').attr("multi");
    
    if(checkValueByMultiplier == '1' && !isDivisibleByMultiplier($('#shopping_qty').val(),qtdMultiplier)){
        $("#popup_message .message").html(incorrect_incomplete_data+"<br>Só pode inserir multiplos de "+qtdMultiplier);
        $("#popup_message").modal();
    }
    else{
        
        //criar nova lista e adicionar produto a essa lista
        
        if($('#AddProductToList').attr('listId').indexOf('Seleccione') == -1){
            
            
            if($('#new_list_name input').val().length>0){
                
                $('#lists_shoppingList').addClass('inactive');
                $('#qtyprod_shoppingList').addClass('inactive');
                $('#new_list_name').addClass('inactive');
                $('#AddProductToList').addClass('inactive');
                $('#CancelAddToList').addClass('inactive');
                
                
                $('#error_exists').addClass('hidden'); 
                //$('#new_list_name span').css('border-color','black');
                //$('#new_list_name input').css('border-color','black'); 
                $('#new_list_name span').removeAttr('style');
                $('#new_list_name input').removeAttr('style');
                //criar a nova lista primeiro
                
                $.ajax({
                    url: "/ActionInvokerGenericAPI.ashx?input=dyn-post&output=json&ActionID=6711",
                    type: "post",
                    data: 'createList=1&listName='+$('#new_list_name input').val(),
                    success: function(response, textStatus, jqXHR) {
                        
                        var DocId = response.data[0].docId;
                        if(DocId == '-1'){
                            
                            //$('#new_list_name input').val('Já criou uma lista com este nome');
                            $('#lists_shoppingList').removeClass('inactive');
                            $('#qtyprod_shoppingList').removeClass('inactive');
                            $('#AddProductToList').removeClass('inactive');
                            $('#CancelAddToList').removeClass('inactive');
                            $('#new_list_name').removeClass('inactive');
                            
                            $('#error_exists.hidden').removeClass('hidden');
                            $('#new_list_name span').css('border-color','red');
                            $('#new_list_name input').css('border-color','red');
                            //alterar para meter com o botao vermelho usar o validationEngine
                            
                        }else{
                            
                            //apartir daqui já confirmou que o nome da lista é valido logo deixa de ser necessario o popup permaneser visivel
                            $('#popup_add_shopping_list').modal('hide');
                            //
                            
                            var inputData = 'ref=' + $('#AddProductToList').attr('ProductRef')
                                +'&refAlt=' + $('#AddProductToList').attr('ProductRefAlt')
                                +'&DocumentAction=' + 1 
                                +'&DocumentType=' + 53
                                +'&ColorID='
                                +'&ColorName='
                                +'&Packsid='
                                +'&totalQuantity=' + $('#shopping_qty').val()
                                +'&Quantity=' + $('#shopping_qty').val()
                                +'&LogisticUnitTypeID=' 
                                +'&extraData='
                                +'&isB2C='+isB2C
                                +'&pricetype=' + pricetype
                                +'&continueOnlyIfLogged='+continueOnlyIfLogged
                                +'&docIDList='+DocId
                                $.ajax({
                                    url: "/ActionInvokerGenericAPI.ashx?input=dyn-post&output=string&ActionID=4885",
                                    type: "post",
                                    data: inputData,
                                    success: function(response, textStatus, jqXHR) {            
                                        
                                        $.ajax({
                                            url: "/ActionInvokerGenericAPI.ashx?input=dyn-post&output=json&ActionID=6711",
                                            type: "post",
                                            data: 'updateDocumentList=1&documentId='+DocId,
                                            success: function(response, textStatus, jqXHR) { 
                                                
                                                
                                                $('#listNumber').text(response.data[0].numberShoppingLists);
                                                //console.log('criado com sucesso tudo trocar por um popup ');  
                                                
                                                $.ajax({
                                                    url: "/ActionInvokerGenericAPI.ashx?input=dyn-post&output=json&ActionID=6711",
                                                    type: "post",
                                                    data: 'shoppingLists=1',
                                                    success: function(response, textStatus, jqXHR) {  
                                                        
                                                        $('#new_list_name input').val('');
                                                        
                                                        $('#shoppingLists option').slice(1).remove();
                                                        var listsNames = '';
                                                        
                                                        listsNames += '<option value="-1">Numa Nova Lista</option>'; //##New_ShoppingList##                                        
                                                        
                                                        response.data.forEach(function(ObjectList){
                                                            listsNames += '<option value="'+ObjectList.id+'">'+ObjectList.listname+'</option>';
                                                        });
                                                        
                                                        $('#lists_shoppingList').removeClass('inactive');
                                                        $('#qtyprod_shoppingList').removeClass('inactive');
                                                        $('#AddProductToList').removeClass('inactive');
                                                        $('#CancelAddToList').removeClass('inactive');
                                                        
                                                        $('#new_list_name').addClass('inactive');
                                                        $('#shoppingLists').append(listsNames);
                                                        //$('#shoppingLists').selectpicker('refresh');  
                                                        
                                                        //
                                                        //$('#shoppingLists').parent().find('.selectpicker li').attr('class','');
                                                        //$('#shoppingLists').parent().find('.selectpicker li:first').attr('class','selected');
                                                        //$('#shoppingLists').parent().find('.selectpicker > span:first').text('Seleccione');    
                                                        //$('#shoppingLists').parent().find('button.selectpicker').attr('title','Seleccione')
                                                        $('#AddProductToList').attr('listId','Seleccione');
                                                        $('#shoppingLists option').prop('selected', function() {
                                                            return this.defaultSelected;
                                                        });
                                                        $('#shoppingLists').selectpicker('refresh');        
                                                        // 
                                                        
                                                        $('#popup_sucess_addedToShoppingList').modal('show');
                                                        setTimeout(function(){
                                                            $('#popup_sucess_addedToShoppingList').modal('hide');
                                                        }, 2000); 
                                                        
                                                    },
                                                    error: function(jqXHR, textStatus, errorThrown) {
                                                        if(console.log) console.log("The following error occured: " + textStatus, errorThrown);
                                                        //$("#rmv_"+ref).html(HTMLfromCOLrmv);
                                                    }
                                                });                                 
                                                
                                            },
                                            error: function(jqXHR, textStatus, errorThrown) {
                                                if(console.log) console.log("The following error occured: " + textStatus, errorThrown);
                                                if (DocType == 29)
                                                    $("#popup_message .message").html(currently_unable_update_shopping_cart+". "+sorry_inconvenience+".");
                                                else
                                                    $("#popup_message .message").html(not_perform_action+". "+sorry_inconvenience+".");
                                            }
                                        });                             
                                        
                                        
                                    },
                                    error: function(jqXHR, textStatus, errorThrown) {
                                        if(console.log) console.log("The following error occured: " + textStatus, errorThrown);
                                        if (DocType == 29)
                                            $("#popup_message .message").html(currently_unable_update_shopping_cart+". "+sorry_inconvenience+".");
                                        else
                                            $("#popup_message .message").html(not_perform_action+". "+sorry_inconvenience+".");
                                    }
                                });                           
                            
                        }    
                        
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        $('#popup_add_shopping_list').modal('hide');
                        if(console.log) console.log("The following error occured: " + textStatus, errorThrown);
                        if (DocType == 29)
                            $("#popup_message .message").html(currently_unable_update_shopping_cart+". "+sorry_inconvenience+".");
                        else
                            $("#popup_message .message").html(not_perform_action+". "+sorry_inconvenience+".");
                    }
                });           
                
                
                
                
            }else{
                //adicionar produto a um lista preexistente 
                $('#lists_shoppingList').addClass('inactive');
                $('#qtyprod_shoppingList').addClass('inactive');
                $('#new_list_name').addClass('inactive');
                $('#AddProductToList').addClass('inactive');
                $('#CancelAddToList').addClass('inactive');
                
                //@docIDList@
                //@userEntityId@
                var inputData = 'ref=' + $('#AddProductToList').attr('ProductRef')
                    +'&refAlt=' + $('#AddProductToList').attr('ProductRefAlt')
                    +'&DocumentAction=' + 1 
                    +'&DocumentType=' + 53
                    +'&ColorID='
                    +'&ColorName='
                    +'&Packsid='
                    +'&totalQuantity=' + $('#shopping_qty').val()
                    +'&Quantity=' + $('#shopping_qty').val()
                    +'&LogisticUnitTypeID=' 
                    +'&extraData='
                    +'&isB2C='+isB2C
                    +'&pricetype=' + pricetype
                    +'&continueOnlyIfLogged='+continueOnlyIfLogged
                    +'&docIDList='+$('#AddProductToList').attr('listId');
                $.ajax({
                    url: "/ActionInvokerGenericAPI.ashx?input=dyn-post&output=string&ActionID=4885",
                    type: "post",
                    data: inputData,
                    success: function(response, textStatus, jqXHR) { 
                        
                        
                        $.ajax({
                            url: "/ActionInvokerGenericAPI.ashx?input=dyn-post&output=json&ActionID=6711",
                            type: "post",
                            data: 'updateDocumentList=1&documentId='+$('#AddProductToList').attr('listId'),
                            success: function(response, textStatus, jqXHR) { 
                                
                                $('#listNumber').text(response.data[0].numberShoppingLists);
                                //console.log('criado com sucesso tudo trocar por um popup ');
                                
                                $('#popup_add_shopping_list').modal('hide');
                                
                                $('#lists_shoppingList').removeClass('inactive');
                                $('#qtyprod_shoppingList').removeClass('inactive');
                                $('#AddProductToList').removeClass('inactive');
                                $('#CancelAddToList').removeClass('inactive');
                                
                                //
                                //$('#shoppingLists').parent().find('.selectpicker li').attr('class','');
                                //$('#shoppingLists').parent().find('.selectpicker li:first').attr('class','selected');
                                //$('#shoppingLists').parent().find('.selectpicker > span:first').text('Seleccione');    
                                //$('#shoppingLists').parent().find('button.selectpicker').attr('title','Seleccione')
                                $('#AddProductToList').attr('listId','Seleccione');
                                $('#shoppingLists option').prop('selected', function() {
                                    return this.defaultSelected;
                                });
                                $('#shoppingLists').selectpicker('refresh');        
                                //                        
                                
                                $('#popup_sucess_addedToShoppingList').modal('show');
                                setTimeout(function(){
                                    $('#popup_sucess_addedToShoppingList').modal('hide');
                                }, 2000);                        
                                
                                
                            },
                            error: function(jqXHR, textStatus, errorThrown) {
                                $('#popup_add_shopping_list').modal('hide');
                                if(console.log) console.log("The following error occured: " + textStatus, errorThrown);
                                if (DocType == 29)
                                    $("#popup_message .message").html(currently_unable_update_shopping_cart+". "+sorry_inconvenience+".");
                                else
                                    $("#popup_message .message").html(not_perform_action+". "+sorry_inconvenience+".");
                            }
                        });                
                        /*
if (response == '1'){
console && console.log("Success");
if (DocType == 29){
$("#popup_message .message").html(added_shopping_successfully);   
GetStateShoppingCart(); 
setTimeout(function() {     
$('#popup_message').modal('hide');}, 1000);
}else{$("#popup_message .message").html(added_successfully);
setTimeout(function() {	 
$('#popup_message').modal('hide');}, 1000);}
}else if (response == '2'){
if (DocType == 29){
$("#popup_message .message").html(shopping_updated_success+".");  
GetStateShoppingCart();  
setTimeout(function() {	 
$('#popup_message').modal('hide');}, 1000);
}else{$("#popup_message .message").html(updated_successfully);}
}else if (response == '3'){
$("#popup_message .message").html(login_required+".");
}else if (response == '5'){
if (DocType == 31)$("#popup_message .message").html(comparator_full+".");
else
console && console.log("Não devia estar aqui.");
}else{
if (DocType == 29)
$("#popup_message .message").html(currently_unable_update_shopping_cart+". "+sorry_inconvenience+".");
else
$("#popup_message .message").html(not_perform_action+". "+sorry_inconvenience+".");
}
*/
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        $('#popup_add_shopping_list').modal('hide');
                        if(console.log) console.log("The following error occured: " + textStatus, errorThrown);
                        if (DocType == 29)
                            $("#popup_message .message").html(currently_unable_update_shopping_cart+". "+sorry_inconvenience+".");
                        else
                            $("#popup_message .message").html(not_perform_action+". "+sorry_inconvenience+".");
                    }
                });          
                
                
            }
        }
        
    }
}