

/* Resource 2915 */

;function setFav(ref){
        var favHTML = $("#favButton_"+ref).html();
        
        $("#favButton_"+ref).html('<img src="/images/loader.gif">');
        $.ajax({
            //ação 4877 adiciona e remove items ao documento 28 (favorito)
            url: "/ActionInvokerGenericAPI.ashx?input=dyn-post&output=string&ActionID=4877",
            type: "post",
            data: 'ref=' + ref,
            success: function(response, textStatus, jqXHR) {
                //if(console.log) console.log(ref+"-result: " + response + " / " + textStatus);
                if (response == '0'){
                    $("#favPopText_"+ref).html(removedToFav);
                    callTooltip("#favPopText_"+ref);
                    $("#favButton_"+ref).html(favHTML);
                    $("#favButton_"+ref).attr("class","btn");
                    $("#favButton_"+ref+" span").attr("class","fa fa-star-o");
                    if($("#favNumberUserArea").length>0){
                    	$("#favNumberUserArea").html((parseInt($("#favNumberUserArea").text())-1).toString());
                    }
                }
                else if (response == '1'){
                    $("#favPopText_"+ref).html(addedToFav);
                    callTooltip("#favPopText_"+ref);
                    $("#favButton_"+ref).html(favHTML);
                    $("#favButton_"+ref).attr("class","btn active");
                    $("#favButton_"+ref+" span").attr("class","fa fa-star");
                    if($("#favNumberUserArea").length>0){
                    	$("#favNumberUserArea").html((parseInt($("#favNumberUserArea").text())+1).toString());
                    }
                }
                else if (response == '2'){
                    $("#favButton_"+ref).html(favHTML); 
                    $("#popup_message .message").html(loginRequired_fav);
                    $("#popup_message").modal();
                    if (sessExpRedirect == 1){
                        setTimeout(function() {	 
                            $('#popup_message').modal('hide');
                            window.location.href = "/session-expired";
                        }, 2500);
                    }
                }
                else
                    $("#favButton_"+ref).html(favHTML); 
            },
            error: function(jqXHR, textStatus, errorThrown) {
                $("#favButton_"+ref).html(favHTML);
            }
        });    
    }

function callTooltip(ref){
    $(ref).parent().fadeIn("fast", function(){setTimeout(function(){ $(ref).parent().fadeOut("slow")},800)});
}

$(document).ready(function(){
    if ($(".winsig_list_product_item")){
        $(".winsig_list_product_item").each(function(){
            if($(this).find(".stock").length == 1)
            {
                if (typeof stock !== 'undefined') {$(this).find(".stock").find("label").html(stock);}                
            }
        });
    }
    
    $('.product_link').bind('click', function() {return false;});
    
    if (typeof showBuyButtonOnlyIfLogin != undefined && showBuyButtonOnlyIfLogin == '1'){
        if(username == ""){
            $(".buy_btn").attr("style","display:none !important");
            $(".view_btn").removeClass("hidden"); 
        }else{$(".view_btn").attr("style","display:none !important");}
    }  
    
    if(dinamicWarehouseNumber == '1'){
        if(captionStyle.indexOf('height: 175px')>-1){
            var num=0;
            $('.winsig_product_item_list_grid .caption').each(function( index ) {
                var htmlObject = $( this ); 
                if(htmlObject.find('.stock').length>num){
                    num=htmlObject.find('.stock').length;
                }
            });
            
            $('.winsig_product_item_list_grid .caption').each(function( index ) {
                var heightDefault = 175;
                var htmlObject = $( this );
                if(num>2){
                    heightDefault = (num-2)*25+heightDefault;
                    htmlObject.innerHeight(heightDefault);
                }
                
            });
        }
    }    
    
	/*
    if(productsInfoDinamicAdapt.indexOf('1')>-1){
    	if(window.innerWidth>=992){
            var totalHeight = 0;
            var LastComponentChildMargin = 0;
            var AuxInteration = 0;
            $('.winsig_product_item_list_grid .caption').each(function(){
                
                if($(this).find('.price_two').length > 0 && $(this).find('.price_one').length > 0){
                    console.log($($(this).find('.price_two')).outerHeight(true));  
                    totalHeight = -$($(this).find('.price_two')).outerHeight(true);
                }                     
                
                var size = $(this).children().length-1;
                $(this).children().each(function(){
                          console.log($(this));
                    console.log('each child element:'+$(this).outerHeight(true));
                    totalHeight = totalHeight + $(this).outerHeight(true);
                    AuxInteration++; 
                    if(size==AuxInteration){
                        LastComponentChildMargin = $(this).outerHeight(true)-$(this).height();
                        console.log('LastComponentChildMargin:'+LastComponentChildMargin);
                    }
                    
                    
                });
                AuxInteration = 0;
                
                var marginTopBottom = $(this).outerHeight(true)-$(this).height(); 
                console.log('marginTopBottom:'+marginTopBottom);
                var FinalMarginTop = 0;
                var ListOfStyles = $(this).attr('style').split(';');
                var heightValue;
                for(var i=0; i<ListOfStyles.length; i++){
                    if(ListOfStyles[i].indexOf('height:') > -1){
                        heightValue = parseInt(ListOfStyles[i].substr(ListOfStyles[i].indexOf('height:')+7));
                    }
                }
                
                FinalMarginTop = (heightValue+LastComponentChildMargin)-(totalHeight+marginTopBottom);
                
                if(totalHeight<(heightValue-marginTopBottom)){
                    console.log(FinalMarginTop);
                    $($(this).find('.bottomContainer')).css('margin-top',FinalMarginTop);
                }
                
                FinalMarginTop = 0; 
                LastComponentChildMargin = 0;
                totalHeight = 0;
                heightValue = 0;
                
            });
            
		}else{
            $('.winsig_product_item_list_grid .caption').each(function(){
                var attr = $(this).attr('style');
                if(typeof attr !== 'undefined'){
                    $(this).removeAttr('style');
                    $($(this).find('.bottomContainer')).removeAttr('style');
                }        
            });        
        }
	}  
    */
    
});

function isIntAndSuperiorZero(n){
    return $.isNumeric(n) && n > 0  && parseFloat(n) == parseInt(n, 10) && !isNaN(n);
}
function add_to_cart_Simple(DocType,if_show_qtd,ref,referenceAlt){
    var qtd = 1; var qtdMultiplier = 1;
    if(if_show_qtd != 'System.Object[]'){
        qtd = $('[id="input_qtd_'+ref+'"]').val();
        
         if($('#input_qtd_'+ref).attr("multi") != undefined)
        	qtdMultiplier = $('#input_qtd_'+ref).attr("multi").replace(",",".");
    }
    if(checkValueByMultiplier == '1' && !isDivisibleByMultiplier(qtd,qtdMultiplier)){
        $("#popup_message .message").html(incorrect_incomplete_data+"<br>Só pode inserir multiplos de "+qtdMultiplier);
        $("#popup_message").modal();
    }
    else{
        if(isIntAndSuperiorZero(qtd)){
            $("#popup_message .message").html("<img src=\"/images/loader.gif\" title=\"A carregar\" alt=\"A carregar informação\">");
            $("#popup_message").modal();
            
            if (validateStock == '1'){
                var inputData = 'ref=' + ref
                    +'&DocumentAction=' + 1 
                    +'&warehouseID=' + warehouseID                
                    +'&totalQuantity=' + qtd;
                
                $.ajax({
                    url: "/ActionInvokerGenericAPI.ashx?input=dyn-post&output=json&ActionID=6486",
                    type: "post",
                    data: inputData,
                    success: function(response, textStatus, jqXHR) {            
                        if (response != ''){
                            if (response.data[0].HasStockToOrder == '[]')
                            {
                                $("#popup_message .message").html("Stock insuficiente. <br>Apenas pode encomendar "+response.data[0].availableStock+" artigos.");
                            }
                            else{
                                var inputData = 'ref=' + ref
                                    +'&refAlt=' + referenceAlt
                                    +'&DocumentAction=' + 1 
                                    +'&DocumentType=' + DocType
                                    +'&ColorID='
                                    +'&ColorName='
                                    +'&Packsid='
                                    +'&totalQuantity=' + qtd
                                    +'&Quantity=' + qtd
                                    +'&LogisticUnitTypeID=' 
                                    +'&extraData='
                                    +'&isB2C='+isB2C
                                    +'&pricetype=' + pricetype
                                    +'&continueOnlyIfLogged='+continueOnlyIfLogged;
                                $.ajax({
                                    url: "/ActionInvokerGenericAPI.ashx?input=dyn-post&output=string&ActionID=4885",
                                    type: "post",
                                    data: inputData,
                                    success: function(response, textStatus, jqXHR) {            
                                        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) {
                                        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 if (response == 'fail'){
                            //    $("#popup_message .message").html(login_required+".");
                        }else{
                            $("#popup_message .message").html(not_perform_action+". "+sorry_inconvenience+".");
                        }
                        $("#detail_loading").fadeOut();
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        if(console.log) console.log("The following error occured: " + textStatus, errorThrown);
                        $("#popup_message .message").html(not_perform_action+". "+sorry_inconvenience+".");
                        $("#popup_message").modal();
                        $("#detail_loading").fadeOut();
                    }
                });
            }
            else{
                
                var inputData = 'ref=' + ref
                    +'&refAlt=' + referenceAlt
                    +'&DocumentAction=' + 1 
                    +'&DocumentType=' + DocType
                    +'&ColorID='
                    +'&ColorName='
                    +'&Packsid='
                    +'&totalQuantity=' + qtd
                    +'&Quantity=' + qtd
                    +'&LogisticUnitTypeID=' 
                    +'&extraData='
                    +'&isB2C='+isB2C
                    +'&pricetype=' + pricetype
                    +'&continueOnlyIfLogged='+continueOnlyIfLogged;
                $.ajax({
                    url: "/ActionInvokerGenericAPI.ashx?input=dyn-post&output=string&ActionID=4885",
                    type: "post",
                    data: inputData,
                    success: function(response, textStatus, jqXHR) {            
                        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);   
                 				GetStateShoppingCart();  
                            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) {
                    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{
        $("#popup_message .message").html(incorrect_incomplete_data+".");
        $("#popup_message").modal();
    }
}
    
}

function notify_when_stock(ref,qtt){
    $("#popup_message .message").html("<img src=\"/images/loader.gif\" title=\"A carregar\" alt=\"A carregar informação\">");
    $("#popup_message").modal();
    $.ajax({
        url: "/ActionInvokerGenericAPI.ashx?input=dyn-post&output=string&ActionID=5067",
        type: "post",
        data: 'reference='+ref+'&qtt='+qtt+'&notificationType=product_stock_becomes_available',
        success: function(response, textStatus, jqXHR) {            
            if (response == '1'){
                $("#popup_message .message").html(notified_email);
            }else if (response == '2'){
                $("#popup_message .message").html(notified_email);
            }else if (response == '3'){
                $("#popup_message .message").html(login_required+".");
            }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);
            $("#popup_message .message").html(not_perform_action+". "+sorry_inconvenience+".");
        },complete: function(jqXHR, textStatus, errorThrown) {
            if(NotificationEmail != '' && NotificationEmail != '0'){
                //var body = "<br>Produto requisitado: "+ref+
                  //  "<br>Quantidade pedida: "+qtt+
                    ////"<br>Pedido feito pelo utilizador: "+ username+"<br>";
                //var srequest = 'emailTo=' + encodeURIComponent(NotificationEmail) + '&body=' + encodeURIComponent(body) + '&subject=' + encodeURIComponent('Produto requisitado');
                //sendGeneralEmailOldWay(srequest);
                
                sendGeneralEmail(1, 0, '{"ref":"'+encodeURIComponent(ref)+'", "qtt":"'+encodeURIComponent(qtt)+'", "username":"'+encodeURIComponent(username)+'"}',encodeURIComponent(NotificationEmail),'','',0,'notifica-stock','',encodeURIComponent('Produto requisitado'),'','','', 0, 0, 2);
            }
        }
    });
}

function gotopage(n){window.location.href=n;}

$(function(){
	$('a').click(function(e) {
        if($(e.target).parent()[0].className.indexOf("input-group") !== -1){
            if($(e.target)[0].className.indexOf("form-control qtd") !== -1 || $(e.target)[0].className.indexOf("btn") !== -1){
                e.preventDefault();
            }
        }     
        
        
		if(typeof $(e.target).attr('data-toggle') != 'undefined' && $(e.target).attr('data-toggle').indexOf("modal") > -1){
            e.preventDefault();
        }
        
        
	});   
    
});

$(window).load(function(){
    var no_information_display = 'Sem informação para mostrar';
    var no_products_available = 'Não existem produtos disponíveis';
    if($($('#doc_table tr')[1]).find('td').text().indexOf(no_information_display)>-1){
    	$('.pagination').empty();
    }    
    if($('.winsig_content_detail .description').text().indexOf(no_products_available)>-1){
    	$('.pagination').empty();
    }
});

function add_to_cote_request_cart_Simple(DocType,if_show_qtd,ref,referenceAlt){
    var qtd = 1;
    if(if_show_qtd != 'System.Object[]')
        qtd = $('[id="input_qtd_'+ref+'"]').val();
    if(isIntAndSuperiorZero(qtd)){
        $("#popup_message .message").html("<img src=\"/images/loader.gif\" title=\"A carregar\" alt=\"A carregar informação\">");
        $("#popup_message").modal();
            var inputData = 'ref=' + ref
                +'&refAlt=' + referenceAlt
                +'&DocumentAction=' + 1 
                +'&DocumentType=' + DocType
                +'&ColorID='
                +'&ColorName='
                +'&Packsid='
                +'&totalQuantity=' + qtd
                +'&Quantity=' + qtd
                +'&LogisticUnitTypeID=' 
                +'&extraData='
                +'&isB2C='+isB2C
                +'&pricetype=' + pricetype
                +'&continueOnlyIfLogged='+continueOnlyIfLogged;
            $.ajax({
                url: "/ActionInvokerGenericAPI.ashx?input=dyn-post&output=string&ActionID=4885",
                type: "post",
                data: inputData,
                success: function(response, textStatus, jqXHR) {
                    if (response == '1'){
                        console && console.log("Success");
                        if (DocType == 52){
                            $("#popup_message .message").html(added_quotation_successfully);
                            GetStateQuotationCart();
                            setTimeout(function() { $('#popup_message').modal('hide');}, 1000);
                        }else{$("#popup_message .message").html(added_successfully);}
                    }else if (response == '2'){
                        if (DocType == 52){
                            $("#popup_message .message").html(quotation_updated_success+".");
                            GetStateQuotationCart();
                            setTimeout(function() { $('#popup_message').modal('hide');}, 1000);
                        }else{$("#popup_message .message").html(updated_successfully);
                              setTimeout(function() { $('#popup_message').modal('hide');}, 1000);}
                    }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 == 52)
                            $("#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 == 52)
                        $("#popup_message .message").html(currently_unable_update_shopping_cart+". "+sorry_inconvenience+".");
                    else
                        $("#popup_message .message").html(not_perform_action+". "+sorry_inconvenience+".");
                }
            });  
    }else{
        $("#popup_message .message").html(incorrect_incomplete_data+".");
        $("#popup_message").modal();
    }
}

$(window).load(function(){
    if($($('#doc_table tr')[1]).find('td').text().indexOf(no_information_display)>-1){
    	$('.pagination').not('.btns').empty();
    }
    
    if($('.winsig_content_detail .description').text().indexOf(no_products_available)>-1){
    	$('.pagination').not('.btns').empty();
    }
    
    /*
    if(productsInfoDinamicAdapt.indexOf('1')>-1){
    	if(window.innerWidth>=992){
            var totalHeight = 0;
            var LastComponentChildMargin = 0;
            var AuxInteration = 0;
            $('.winsig_product_item_list_grid .caption').each(function(){
                
                if($(this).find('.price_two').length > 0 && $(this).find('.price_one').length > 0){
                    //console.log($($(this).find('.price_two')).outerHeight(true));  
                    totalHeight = -$($(this).find('.price_two')).outerHeight(true);
                }                     
                
                var size = $(this).children().length-1;
                $(this).children().each(function(){
                          console.log($(this));
                    console.log('each child element:'+$(this).outerHeight(true));
                    totalHeight = totalHeight + $(this).outerHeight(true);
                    AuxInteration++; 
                    if(size==AuxInteration){
                        LastComponentChildMargin = $(this).outerHeight(true)-$(this).height();
                        console.log('LastComponentChildMargin:'+LastComponentChildMargin);
                    }
                    
                    
                });
                AuxInteration = 0;
                
                var marginTopBottom = $(this).outerHeight(true)-$(this).height(); 
                console.log('marginTopBottom:'+marginTopBottom);
                var FinalMarginTop = 0;
                var ListOfStyles = $(this).attr('style').split(';');
                var heightValue;
                for(var i=0; i<ListOfStyles.length; i++){
                    if(ListOfStyles[i].indexOf('height:') > -1){
                        heightValue = parseInt(ListOfStyles[i].substr(ListOfStyles[i].indexOf('height:')+7));
                    }
                }
                
                FinalMarginTop = (heightValue+LastComponentChildMargin)-(totalHeight+marginTopBottom);
                
                if(totalHeight<(heightValue-marginTopBottom)){
                    console.log(FinalMarginTop);
                    $($(this).find('.bottomContainer')).css('margin-top',FinalMarginTop);
                }
                
                FinalMarginTop = 0; 
                LastComponentChildMargin = 0;
                totalHeight = 0;
                heightValue = 0;
                
            });
            
		}else{
            $('.winsig_product_item_list_grid .caption').each(function(){
                var attr = $(this).attr('style');
                if(typeof attr !== 'undefined'){
                    $(this).removeAttr('style');
                    $($(this).find('.bottomContainer')).removeAttr('style');
                }        
            });        
        }
	}
    */
    
	
    
});



    
$(window).resize(function() {
    
    if(removeStyleProductInfo.indexOf('1')>-1){
        if(window.innerWidth<992){
            $('.winsig_product_item_list_grid .caption').each(function(){
                var attr = $(this).attr('style');
                if(typeof attr !== 'undefined'){
                    $(this).removeAttr('style');
                    $($(this).find('.bottomContainer')).removeAttr('style');
                }        
            });
        }else{
            
            var style = $($('.winsig_product_item_list_grid .caption')[0]).attr('style');
            
            if(typeof style === 'undefined' ){
                $('.winsig_product_item_list_grid .caption').each(function(){
                    $(this).attr('style',captionStyle);       
                });
                
                if($(this).find('.price_two').length > 0 && $(this).find('.price_one').length > 0){
                    //console.log($($(this).find('.price_two')).outerHeight(true));  
                    totalHeight = -$($(this).find('.price_two')).outerHeight(true);
                }            
                
                var totalHeight = 0;
                var LastComponentChildMargin = 0;
                var AuxInteration = 0;
                $('.winsig_product_item_list_grid .caption').each(function(){
                    
                    var size = $(this).children().length-1;
                    $(this).children().each(function(){
                        
                        
                        totalHeight = totalHeight + $(this).outerHeight(true);
                        AuxInteration++; 
                        if(size==AuxInteration){
                            LastComponentChildMargin = $(this).outerHeight(true)-$(this).height();
                        }
                        
                        
                    });
                    AuxInteration = 0;
                    
                    var marginTopBottom = $(this).outerHeight(true)-$(this).height();    
                    var FinalMarginTop = 0;
                    var ListOfStyles = $(this).attr('style').split(';');
                    var heightValue;
                    for(var i=0; i<ListOfStyles.length; i++){
                        if(ListOfStyles[i].indexOf('height:') > -1){
                            //console.log(ListOfStyles[i]);
                            heightValue = parseInt(ListOfStyles[i].substr(ListOfStyles[i].indexOf('height:')+7));
                        }
                    }
                    
                    FinalMarginTop = (heightValue+LastComponentChildMargin)-(totalHeight+marginTopBottom);
                    
                    if(totalHeight<(heightValue-marginTopBottom)){
                        $($(this).find('.bottomContainer')).css('margin-top',FinalMarginTop);
                    }
                    
                    FinalMarginTop = 0; 
                    LastComponentChildMargin = 0;
                    totalHeight = 0;
                    heightValue = 0;
                }); 
                
            }
            
        }
	}
    
});