

/* Resource 2933 */

;



/* Resource 1351 */

;$(document).ready(function(){      
	if ($("#"+id_banner_gallery+" .carousel-inner").children(".item").length < 2){
    	$("#"+id_banner_gallery+" .carousel-indicators, #"+id_banner_gallery+" .carousel-control").addClass("hidden");
        $("#"+id_banner_gallery).attr("data-interval","false");
    }    
});

/* Resource 1370 */

;$(function(){
    $("#wnewsletterform").validationEngine({ scroll: false });
    
	$("#wnewsletter").click(function(){
        //alert($.validateEmail($("#wnemail").val()));
		//if($.validateEmail($("#wnemail").val())){
        if($("#wnewsletterform").validationEngine('validate')){
			$("#wnewsletter").fadeOut("fast");
			$.ajax({
				type: "POST",
				url: "/ActionInvokerGenericAPI.ashx",
				data: { input: 'json-post', output: 'string', ActionID: '3960', ActionTokens: '{"email":"'+$("#wnemail").val()+'","field1":"","field2":"","field3":""}' }
			}).done(function(rsp) {
  				//$("#newsletterField").addClass("hasError");
                $("#popup_news_subscription").modal('hide');
                    if(rsp == 1){
            			$("#popup_message .message").html(successRegisteredEmailLabel);
            			$("#popup_message").modal();  
                        sendNewslettermail(sendEmailTo,'');
                       
                        $.ajax({
                            url: "/ActionInvokerGenericAPI.ashx?input=dyn-post&output=string&ActionID=6758",
                            type: "post",
                            data: 'UserID=0&ActionType=1,&email='+$('#wnemail').val(),
                            success: function(response, textStatus, jqXHR) { 
                            }
                        });   
                        
                   	}
                    else{                        
                        $("#popup_message .message").html(existentEmailLabel);
            			$("#popup_message").modal(); 
                    }
					$("#wnewsletter").fadeIn();
            }).fail(function() { 
                $("#popup_message .message").html(notRegisteredEmailLabel);
                $("#popup_message").modal(); 
            });
		}
        return false;
	});
});

function sendNewslettermail(mail, upFile){
    if (typeof sendGeneralEmail == 'function') { 
        sendGeneralEmail('1', '', '{"email":"'+$("#wnemail").val()+'"}',encodeURIComponent(mail),'','','','FormNewsletterEmail','','Newsletter - Email registado','','','', '', '', '', '', '', '', '', '', '','FormNewsletterEmail');
        sendGeneralEmail('1', '', '{"email":"'+$("#wnemail").val()+'"}',encodeURIComponent($("#wnemail").val()),'','','','FormNewsletterEmailThanks','','Newsletter - Email registado Agradecimentos','','','', '', '', '', '', '', '', '', '', '','FormNewsletterEmailThanks');

    }else{
        var body =
            "<span color='#333333'>E-mail:</span> " + $("#wnemail").val() + "<br>";
        
        var subject = "Newsletter - Email registado";
        
        var srequest = 'emailTo=' + encodeURIComponent(mail) + '&body=' + encodeURIComponent(body) + '&subject=' + encodeURIComponent(subject);
        
        $.ajax({
            type: "POST",
            url: "/ActionInvokerGenericAPI.ashx?input=dyn-post&ActionID=4005",
            data: srequest
        }).done(function(rsp) {
            //console.log("sucesso."+mail);
        }).fail(function() {
            //console.log("Erro.");
        });
    }
}

/* Resource 2241 */

;function fb_login(user) {
    if(FB.getAuthResponse().userID == user.id) {
        var fbid = FB.getAuthResponse().userID;
        var fbtoken = FB.getAuthResponse().accessToken;
        $.ajax({
            url: "/ActionInvokerGenericAPI.ashx?input=dyn-post&output=string&ActionID=4408&t=" + new Date().getTime(),
            type: "post",
            data: "fbid=" + fbid + "&fbtoken=" + fbtoken,
            success: function(response, textStatus, jqXHR){
                if(response && typeof response == 'string') {
                    $.ajax({
                        url: "/ActionInvokerGenericAPI.ashx?input=dyn-post&output=string&ActionID=4186&t=" + new Date().getTime(),
                        type: "post",
                        data: "fbid=" + fbid,
                        success: function(response, textStatus, jqXHR){
                            console && console.log("Token do facebook actualizado");
                        },
                        error: function(jqXHR, textStatus, errorThrown){
                            console && console.log("FB access_token - The following error occurred: "+textStatus, errorThrown);
                        },
                        complete: function(jqXHR, textStatus){
                            window.location = window.location.pathname;
                        }
                    });
                } else {
                    console && console.log("Possível erro de login!");
                    
                    $.prettyPhoto.close();
                    $("#fail_popup_msg").html('Se ainda não tens conta, <a href="/registo" >regista-te!</a><br />Se já tens conta Mine! associa-a ao teu login facebook em <br />"Meus Dados" dentro da tua conta!');
                    setTimeout(showPopupLoginError,750);
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console && console.log("The following error occurred: " + textStatus, errorThrown);
                
                $.prettyPhoto.close();
                $("#fail_popup_msg").html('Se ainda não tens conta, <a href="/registo" >regista-te!</a>');
                setTimeout(showPopupLoginError,750);
            }
        });
	}
};
function login_via_facebook(){
    FB.login(
        function(response) {
            if(response.authResponse) {
                FB.api('/me?fields=id,name,email', fb_login);
            } else {
                console && console.log('User cancelled login or did not fully authorize.');
            }
        }
    );
};


function callPopupToAsk(entityID,cartID,extraInfo){
    $("#loginSubmit").html(submitBtnHtml);
    $("#error_login").html("").hide();
    $("#popup_message .modal-title").html(welcomeString);
    $("#popup_message .message").html(welcomeString+', '+extraInfo+'.<br/>'+welcomeClient+'!<br/>'+StillcorrentCart+'?');
    if (divOnButtons == 1)
    	$("#popup_message .modal-footer").html('<div><button type="button" class="btn btn-default" onclick="AssociateEntityToCart('+entityID+','+cartID+',\''+extraInfo+'\',1)">'+labelyes+'</button></div><div><button type="button" class="btn btn-default" onclick="AssociateEntityToCart('+entityID+','+cartID+',\''+extraInfo+'\',0)">'+labelno+'</button></div>');
    else
    	$("#popup_message .modal-footer").html('<button type="button" class="btn btn-default" onclick="AssociateEntityToCart('+entityID+','+cartID+',\''+extraInfo+'\',1)">'+labelyes+'</button><button type="button" class="btn btn-default" onclick="AssociateEntityToCart('+entityID+','+cartID+',\''+extraInfo+'\',0)">'+labelno+'</button>');
    $("#cancelLogin").click();
    $("#showMsgAlert").click();
    $('#popup_message').on('hidden.bs.modal', function (e) {
        if(flagToCallFunction == 0){
            AssociateEntityToCart(entityID,cartID,extraInfo,0);
        }else{
            setTimeout(function(){
                if( window.location.pathname.search(registerUrl)  != -1 || window.location.pathname.search(confirmRegisterUrl)  != -1 || backToHomepage == 1){
                    window.location = "/"+firstpagevarlog;
                }else{
                    window.location.reload();
                }
        }, 500);
        }
        
    });
}

function callPopupToAskQuotation(entityID,quotationID,extraInfo){
    $("#loginSubmit").html(submitBtnHtml);
    $("#error_login").html("").hide();
    $("#popup_message .modal-title").html(welcomeString);
    $("#popup_message .message").html(welcomeString+', '+extraInfo+'.<br/>'+welcomeClient+'!<br/>'+StillcorrentQuotationCart+'?');
    if (divOnButtons == 1)
    	$("#popup_message .modal-footer").html('<div><button type="button" class="btn btn-default" onclick="AssociateEntityToQuotation('+entityID+','+quotationID+',\''+extraInfo+'\',1)">'+labelyes+'</button></div><div><button type="button" class="btn btn-default" onclick="AssociateEntityToQuotation('+entityID+','+quotationID+',\''+extraInfo+'\',0)">'+labelno+'</button></div>');
    else
		$("#popup_message .modal-footer").html('<button type="button" class="btn btn-default" onclick="AssociateEntityToQuotation('+entityID+','+quotationID+',\''+extraInfo+'\',1)">'+labelyes+'</button><button type="button" class="btn btn-default" onclick="AssociateEntityToQuotation('+entityID+','+quotationID+',\''+extraInfo+'\',0)">'+labelno+'</button>'); 
    $("#cancelLogin").click();
    $("#showMsgAlert").click();
    $('#popup_message').on('hidden.bs.modal', function (e) {
        if(flagToCallFunctionQuotation == 0){
            AssociateEntityToQuotation(entityID,quotationID,extraInfo,0);
        }else{
            setTimeout(function(){
                if( window.location.pathname.search(registerUrl)  != -1 || window.location.pathname.search(confirmRegisterUrl)  != -1 || backToHomepage == 1){
                    window.location = "/"+firstpagevarlog;
                }else{
                    window.location.reload();
                }
        }, 500);
        }
        
    });
}

function callPopupToAskShopAndQuotation(entityID,cartID,quotationID,extraInfo){
    $("#loginSubmit").html(submitBtnHtml);
    $("#error_login").html("").hide();
    $("#popup_message .modal-title").html(welcomeString);
    $("#popup_message .message").html(welcomeString+', '+extraInfo+'.<br/>'+welcomeClient+'!<br/>'+StillcorrentShopAndQuotationCart+'?');
    if (divOnButtons == 1)
    	$("#popup_message .modal-footer").html('<div><button type="button" class="btn btn-default" onclick="AssociateEntityToCart('+entityID+','+cartID+',\''+extraInfo+'\',1);AssociateEntityToQuotation('+entityID+','+quotationID+',\''+extraInfo+'\',1);">'+labelyes+'</button></div><div><button type="button" class="btn btn-default" onclick="AssociateEntityToCart('+entityID+','+cartID+',\''+extraInfo+'\',1);AssociateEntityToQuotation('+entityID+','+quotationID+',\''+extraInfo+'\',0);">'+labelno+'</button></div>');
    else
		$("#popup_message .modal-footer").html('<button type="button" class="btn btn-default" onclick="AssociateEntityToCart('+entityID+','+cartID+',\''+extraInfo+'\',1);AssociateEntityToQuotation('+entityID+','+quotationID+',\''+extraInfo+'\',1);">'+labelyes+'</button><button type="button" class="btn btn-default" onclick="AssociateEntityToCart('+entityID+','+cartID+',\''+extraInfo+'\',1);AssociateEntityToQuotation('+entityID+','+quotationID+',\''+extraInfo+'\',0);">'+labelno+'</button>')
    $("#cancelLogin").click();
    $("#showMsgAlert").click();
    $('#popup_message').on('hidden.bs.modal', function (e) {
        if(flagToCallFunctionQuotation == 0){
            AssociateEntityToQuotation(entityID,quotationID,extraInfo,0);
            AssociateEntityToCart(entityID,cartID,extraInfo,0);
        }else{
            setTimeout(function(){
                if( window.location.pathname.search(registerUrl)  != -1 || window.location.pathname.search(confirmRegisterUrl)  != -1 || backToHomepage == 1){
                    window.location = "/"+firstpagevarlog;
                }else{
                    window.location.reload();
                }
        }, 500);
        }
        
    });
}

var flagToCallFunction = 0;
function AssociateEntityToCart(entityID,cartID,extraInfo,action){
    flagToCallFunction = 1;
    console && console.log('AssociateEntityToCart: '+action);
    $("#popup_message .message").html("<img src=\"/images/loader.gif\" title=\"A carregar\" alt=\"A carregar informação\">");
    $("#popup_message .modal-footer").html("<button type='button' class='btn btn-default' data-dismiss='modal'>Ok</button>");
    $("#popup_message").modal();    
    $.ajax({
        url: "/ActionInvokerGenericAPI.ashx?input=dyn-post&output=json&ActionID=5254",
        type: "post",
        data: "entityID="+entityID+"&cartID="+cartID+'&action='+action+'&sessionForced='+sessionForced,
        success: function(response, textStatus, jqXHR){
            if(response) {
                $("#loginSubmit").html(submitBtnHtml);
                $("#error_login").html("").hide();
                $("#popup_message .modal-title").html(welcomeString);
                $("#popup_message .message").html(welcomeString+', '+extraInfo+'.<br/>'+welcomeClient);
                $("#cancelLogin").click();
                $("#showMsgAlert").click();
            }
        },error: function(jqXHR, textStatus, errorThrown){  
            $("#loginSubmit").html(submitBtnHtml);
            $("#error_login").html(errorOcurred).show();
        },complete: function(){
            $("#loginSubmit").html(submitBtnHtml);
            setTimeout(function(){
                if( window.location.pathname.search(registerUrl)  != -1 || window.location.pathname.search(confirmRegisterUrl)  != -1 || backToHomepage == 1){
                    window.location = "/"+firstpagevarlog;
                }else{
                    window.location.reload();
                }
            }, 500); 
        }
    });
}

var flagToCallFunctionQuotation = 0;
function AssociateEntityToQuotation(entityID,quotationID,extraInfo,action){
    flagToCallFunctionQuotation = 1;
    console && console.log('AssociateEntityToQuotation: '+action);
    $("#popup_message .message").html("<img src=\"/images/loader.gif\" title=\"A carregar\" alt=\"A carregar informação\">");
    $("#popup_message .modal-footer").html("<button type='button' class='btn btn-default' data-dismiss='modal'>Ok</button>");
    $("#popup_message").modal();    
    $.ajax({
        url: "/ActionInvokerGenericAPI.ashx?input=dyn-post&output=json&ActionID=6634",
        type: "post",
        data: "entityID="+entityID+"&quotationID="+quotationID+'&action='+action+'&sessionForced='+sessionForced,
        success: function(response, textStatus, jqXHR){
            if(response) {
                $("#loginSubmit").html(submitBtnHtml);
                $("#error_login").html("").hide();
                $("#popup_message .modal-title").html(welcomeString);
                $("#popup_message .message").html(welcomeString+', '+extraInfo+'.<br/>'+welcomeClient);
                $("#cancelLogin").click();
                $("#showMsgAlert").click();
            }
        },error: function(jqXHR, textStatus, errorThrown){  
            $("#loginSubmit").html(submitBtnHtml);
            $("#error_login").html(errorOcurred).show();
        },complete: function(){
            $("#loginSubmit").html(submitBtnHtml);
            setTimeout(function(){
                if( window.location.pathname.search(registerUrl)  != -1 || window.location.pathname.search(confirmRegisterUrl)  != -1 || backToHomepage == 1){
                    window.location = "/"+firstpagevarlog;
                }else{
                    window.location.reload();
                }
            }, 500); 
        }
    });
}

var flagToCallFunctionComparator = 0;
function AssociateEntityToComparator(entityID,comparatorID,extraInfo,action){
    flagToCallFunctionComparator = 1;  
    $.ajax({
        url: "/ActionInvokerGenericAPI.ashx?input=dyn-post&output=json&ActionID=6634",
        type: "post",
        data: "entityID="+entityID+"&quotationID="+comparatorID+'&action='+action+'&sessionForced='+sessionForced,
		success: function(response, textStatus, jqXHR){
        },error: function(jqXHR, textStatus, errorThrown){  
        },complete: function(){
        }
    });
}

function SaveToAuditing(type,field1,field2,field3,field4){
    $.ajax({
        url: "/ActionInvokerGenericAPI.ashx?output=json&ActionID=5741",
        type: "post",
        data: "type="+type+"&field1="+field1+"&field2="+field2+"&field3="+field3+"&field4="+field4,
        success: function(response, textStatus, jqXHR){
            if(response) { 
                console && console.log('SaveToAuditing success');
            }
        },error: function(jqXHR, textStatus, errorThrown){  
            console && console.log('SaveToAuditing error');
        }
    });
}
var submitBtnHtml;
$(function(){  

    if( !(typeof window.location.pathname.split("/")[2] !== 'undefined') || (window.location.pathname.split("/")[2].indexOf(defaultadminpage) === -1 && window.location.pathname.split("/")[2].indexOf(orderalternativeurl) === -1) ){
        if(parseInt(EntityTypeID) === 39){
            window.location = "/"+defaultadminpage+"?id="+39+'&status='+979;
        }else if(parseInt(EntityTypeID) === 40){
            window.location = "/"+defaultadminpage+"?id="+40+'&status='+980;
        }
    }
    
    if(typeof GetURLParameter('id') != 'undefined' && typeof GetURLParameter('status') != 'undefined'){        
    	$('#ordersLink').attr('onclick',function(i,value){
            if(typeof value !== 'undefined'){
                return value.substring(0,value.length-1)+"?id="+GetURLParameter('id')+"&status="+GetURLParameter('status')+"'";
            }        	
        });
    }else if(typeof GetURLParameter('id') != 'undefined'){
    	$('#ordersLink').attr('onclick',function(i,value){
            if(typeof value !== 'undefined'){
                return value.substring(0,value.length-1)+"?id="+GetURLParameter('id')+"'";
            }        	
        });
    }    
    
   submitBtnHtml = $("#loginSubmit").html();
    $("#loginSubmit").click(function(event){
        $("#loginSubmit").html("<img src=\"/images/loader.gif\" title=\"A carregar\" alt=\"A carregar informação\">");
        var $form = $("#login"),
            $inputs = $form.find("input, select, button, textarea"),
            serializedData = $form.serialize();
        $inputs.attr("disabled", "disabled");
        $("#error_login").html("").hide();
        
        userLogin(serializedData,$("#num").val(),true);
            
        event.preventDefault();
        return false;
    });
    
    $('input[name=pw]').keyup(
        function(event){
            if(event.keyCode == 13 && ($('input[name=num]').val() != '' && $('input[name=pw]').val() != '')){
                $("#loginSubmit").click();
            }
            if(event.keyCode == 27){
                $(".button styled closePopup").click();
            }
        }
    );
    $('#popup_login,#popup_pw_recovery').on('hidden.bs.modal', function () {
        $("#error_login,#error_recup_pW").html("").hide(); 
    });
    $('#popup_login,#popup_pw_recovery').on('shown.bs.modal', function () {
        $("#num,#email_pw").focus();
    });
});

function userLogin(udata,usr,showWelcomeMsg,reloadpage){
    var $inputs = $("#login").find("input, select, button, textarea");
    if(typeof reloadpage === 'undefined'){
    	reloadpage = false;
    }
    //verifica ativação da conta do utilizador
    $.ajax({
            url: "/ActionInvokerGenericAPI.ashx?input=dyn-post&output=string&ActionID=4864",
            type: "post",
            data: "username="+usr,
            success: function(response, textStatus, jqXHR){
                if (response == 1){
                    $.ajax({
                        url: "/ActionInvokerGenericAPI.ashx?input=dyn-post&output=string&ActionID=3747",
                        type: "post",
                        data: udata,
                        success: function(response, textStatus, jqXHR){
                            if(response) {
                                if(saveLogin == 1){NewRow(true,5,'login',response);}
                                if(auditingLogin == 1){SaveToAuditing(3,response,userip,'','');}
                                $.ajax({
                                    url: "/ActionInvokerGenericAPI.ashx?input=dyn-post&output=json&ActionID=4827",
                                    type: "post",
                                    success: function(response, textStatus, jqXHR){
                                        if(response) {
                                            if(response.data[0].IsAdmin.indexOf('1')>-1){
                                                	$("#loginSubmit").html(submitBtnHtml);
                                                    $("#error_login").html("").hide();
                                                    $("#popup_message .modal-title").html(welcomeString);
                                                
                                                	if (showWelcomeMsg){                                                
                                            	   		if (showWelcomeFirstName == "1")
	                                                        $("#popup_message .message").html(welcomeString+' Administrador'+', '+response.data[0].firstName+'.<br/>'+welcomeClient);
	                                                    else
	                                                        $("#popup_message .message").html(welcomeString+' Administrador'+', '+response.data[0].name+'.<br/>'+welcomeClient);
                                                	}
                                                	
                                                	
                                                	$("#cancelLogin").click();
                                                	if (showWelcomeMsg){
                                                    	$("#showMsgAlert").click();
                                                    }
                                                
                                                	var status = response.data[0].status;
                                                
                                                    setTimeout(function(){
														window.location = "/"+defaultadminpage+"?id="+response.data[0].EntityTypeID+'&status='+status;
                                                    }, 500);
                                                
                                                	setTimeout(function(){$("#popup_message").modal("hide")},2000);
                                            }else{
                                                
                                                
                                                if(isB2C == '0' || ((isB2C == '1' && response.data[0].cart_ID == 0) && (isB2C == '1' && response.data[0].quotation_ID == 0))) {
                                                    
                                                    if(hasComparator == '1' && response.data[0].comparator_ID != '0'){
                                                        AssociateEntityToComparator(response.data[0].EntityID,response.data[0].comparator_ID,response.data[0].firstName,1);
                                                    }
                                                    $("#loginSubmit").html(submitBtnHtml);
                                                    $("#error_login").html("").hide();
                                                    $("#popup_message .modal-title").html(welcomeString);
                                                    
                                                    if (showWelcomeMsg){
                                                    	if (showWelcomeFirstName == "1")
	                                                        $("#popup_message .message").html(welcomeString+', '+response.data[0].firstName+'.<br/>'+welcomeClient);
    	                                                else
	                                                        $("#popup_message .message").html(welcomeString+', '+response.data[0].name+'.<br/>'+welcomeClient);
                                                    }
                                                    
                                                    $("#cancelLogin").click();
                                                    if (showWelcomeMsg){
                                                    	$("#showMsgAlert").click();
                                                    }
                                                    
                                                    if(reloadpage){
                                                    	$("#popup_message .message").html('Perdeu a sessão, a Autenticar-se...');
                                                        $("#popup_message").modal();
                                                    }
                                                    
                                                    setTimeout(function(){
                                                        if( window.location.pathname.search(registerUrl)  != -1 || window.location.pathname.search(confirmRegisterUrl)  != -1 || (backToHomepage == 1 && !reloadpage)){
                                                            window.location = "/"+firstpagevarlog;
                                                        }else{
                                                            window.location.reload();
                                                        }
                                                    }, 500);   
                                                    
                                                    setTimeout(function(){$("#popup_message").modal("hide")},2000);
                                                }else{
                                                    if(isB2C == '1' && response.data[0].cart_ID != 0 && response.data[0].quotation_ID == 0){
                                                    	if(askToUser=='0'){
                                                            if(hasComparator == '1' && response.data[0].comparator_ID != '0'){
                                                                AssociateEntityToComparator(response.data[0].EntityID,response.data[0].comparator_ID,response.data[0].firstName,1);
                                                                AssociateEntityToCart(response.data[0].EntityID,response.data[0].cart_ID,response.data[0].firstName,1);
                                                            }
                                                        	else
                                                                AssociateEntityToCart(response.data[0].EntityID,response.data[0].cart_ID,response.data[0].firstName,1);
                                                    	}else{
                                                            if(hasComparator == '1' && response.data[0].comparator_ID != '0'){
                                                                AssociateEntityToComparator(response.data[0].EntityID,response.data[0].comparator_ID,response.data[0].firstName,1);
                                                            	callPopupToAsk(response.data[0].EntityID,response.data[0].cart_ID,response.data[0].firstName);
                                                            }
                                                            else
                                                        		callPopupToAsk(response.data[0].EntityID,response.data[0].cart_ID,response.data[0].firstName);
                                                    	}
                                                    }
                                                    else if(isB2C == '1' && response.data[0].quotation_ID != 0 && response.data[0].cart_ID == 0){
                                                    	if(askToUser=='0'){
                                                            if(hasComparator == '1' && response.data[0].comparator_ID != '0'){
                                                                AssociateEntityToComparator(response.data[0].EntityID,response.data[0].comparator_ID,response.data[0].firstName,1);
                                                            	AssociateEntityToQuotation(response.data[0].EntityID,response.data[0].quotation_ID,response.data[0].firstName,1);
                                                            }
                                                            else
                                                        		AssociateEntityToQuotation(response.data[0].EntityID,response.data[0].quotation_ID,response.data[0].firstName,1);
                                                            
                                                    	}else{
                                                            if(hasComparator == '1' && response.data[0].comparator_ID != '0'){
                                                                AssociateEntityToComparator(response.data[0].EntityID,response.data[0].comparator_ID,response.data[0].firstName,1);
                                                            	callPopupToAskQuotation(response.data[0].EntityID,response.data[0].quotation_ID,response.data[0].firstName);
                                                            }
                                                            else
                                                        		callPopupToAskQuotation(response.data[0].EntityID,response.data[0].quotation_ID,response.data[0].firstName);
                                                    	}
                                                    }
                                                    
                                                    else if(isB2C == '1' && response.data[0].quotation_ID != 0 && response.data[0].cart_ID != 0){
                                                    	if(askToUser=='0'){
                                                            if(hasComparator == '1' && response.data[0].comparator_ID != '0'){
                                                             	AssociateEntityToComparator(response.data[0].EntityID,response.data[0].comparator_ID,response.data[0].firstName,1);
                                                                AssociateEntityToQuotation(response.data[0].EntityID,response.data[0].quotation_ID,response.data[0].firstName,1);
                                                                AssociateEntityToCart(response.data[0].EntityID,response.data[0].cart_ID,response.data[0].firstName,1);
                                                            }
                                                        	else{
                                                                AssociateEntityToQuotation(response.data[0].EntityID,response.data[0].quotation_ID,response.data[0].firstName,1);
                                                                AssociateEntityToCart(response.data[0].EntityID,response.data[0].cart_ID,response.data[0].firstName,1);
                                                            }
                                                    	}else{
                                                            if(hasComparator == '1' && response.data[0].comparator_ID != '0'){
                                                             	AssociateEntityToComparator(response.data[0].EntityID,response.data[0].comparator_ID,response.data[0].firstName,1);
                                                                callPopupToAskShopAndQuotation(response.data[0].EntityID,response.data[0].cart_ID,response.data[0].quotation_ID,response.data[0].firstName);
                                                            }
                                                        	else
                                                                callPopupToAskShopAndQuotation(response.data[0].EntityID,response.data[0].cart_ID,response.data[0].quotation_ID,response.data[0].firstName);
                                                    	}
                                                    }
                                                    
                                                }
                                            }
                                            //save to cookie
                                            if ($("#login input#memPass").is(":checked")){
                                                setCookie("memPass", udata, 5);
                                            }
                                        }
                                    },error: function(jqXHR, textStatus, errorThrown){  
                                        $("#loginSubmit").html(submitBtnHtml);
                                        $("#error_login").html(errorOcurred).show();
                                    },complete: function(){
                                        $("#loginSubmit").html(submitBtnHtml);
                                        $inputs.removeAttr("disabled");
                                    }
                                });
                            }else {
                                $("#loginSubmit").html(submitBtnHtml);
                                $("#error_login").html(incorrectData).show();
                                $inputs.removeAttr("disabled");
                                if(auditingLogin == 1){SaveToAuditing(4,'',userip,'','');}
                            }
                        },
                        error: function(jqXHR, textStatus, errorThrown){  
                            $("#loginSubmit").html(submitBtnHtml);
                            $("#error_login").html(errorOcurred).show();
                            $inputs.removeAttr("disabled");
                                if(auditingLogin == 1){SaveToAuditing(4,'',userip,'','');}
                        },
                        complete: function(){
                            $("#loginSubmit").html(submitBtnHtml);
                        }
                    });
                }else if (response == 0){
                    $("#loginSubmit").html(submitBtnHtml);
                    
                    if (passErrorWithPopup == 0)
                    	$("#error_login").html(errorOcurred + " " + activateAccount).show();
                    else {
                    	$("#loginSubmit").html(submitBtnHtml);
                    	$("#error_login").html("").hide();
                    	$("#popup_message .modal-title").html(errorOcurred);
						$("#popup_message .message").html(activateAccount);
                    	$("#cancelLogin").click();
                    	$("#showMsgAlert").click();
                    }
                    
                    if(auditingLogin == 1){SaveToAuditing(4,'',userip,'','');}

                }
                else{
                    $("#loginSubmit").html(submitBtnHtml);
                    $("#error_login").html(errorOcurred).show();
                    if(auditingLogin == 1){SaveToAuditing(4,'',userip,'','');}
                }
            },
            error: function(jqXHR, textStatus, errorThrown){  
                $("#loginSubmit").html(submitBtnHtml);
                $("#error_login").html(errorOcurred).show();
                if(auditingLogin == 1){SaveToAuditing(4,'',userip,'','');}
            },
            complete: function(){
                $inputs.removeAttr("disabled");
            }
        });
}
            

/* Resource 3054 */

;var ReferenceID = '';
var StockState=false;
var defaultImage = '';
var defaultStock = '';
var defaultPrice = 0;
var total_items = 0;

function initDetailsProduct(ref,referenceAlt){
    
    $('#qtd .form-control').val($('[id="input_qtd_'+ref+'"]').val());
    $('#qtd .form-control').attr("multi",$('[id="input_qtd_'+ref+'"]').attr("multi"));
    
    defaultImage = '/images/menus_images/no_image.jpg';
    ReferenceID = ref;
    $("#detail_loading").fadeIn();
    $.ajax({
        url: "/ActionInvokerGenericAPI.ashx?input=dyn-post&output=json&ActionID=4886",
        type: "post",
        data: 'ref=' + ref+'&PriceTypes='+PriceTypes+'&warehouseID='+warehouseID+"&showAccumulativeDiscounts="+showAccumulativeDiscounts,
        success: function(response, textStatus, jqXHR) {  
            console && console.log(response);
            if (response != ''){
                
                $('#add_product_to_cart_qtt').attr('onClick','add_to_cart_advance("'+response.data[0].productReference+'","'+response.data[0].ProductReferenceAlt+'")');
                $('#qtd .form-control').attr('id','input_pp_qtd_'+response.data[0].productReference+'');
                
                if(response.data[0].productStock != '' && response.data[0].productStock != null){
                    defaultStock = response.data[0].productStock;                    
                }
                
                if(response.data[0].productImage != '' && response.data[0].productImage != null){
                    defaultImage = "/resources/"+response.data[0].productImage;
                    $('#product_image').attr("src",'/resources/'+response.data[0].productImage);
                }
                
                if (onlyB2bIfEstabZero == '1' && response.data[0].IsEstabZero == '1'){                    
                	$('#price_total').text(response.data[0].PVR_Discounted+" €");
                	defaultPrice = response.data[0].PVR_Discounted;
                }
                else{
                    $('#price_total').text(response.data[0].defaultProductPVP+" €");
                	defaultPrice = response.data[0].defaultProductPVP;
                }
                
            }else{
                console && console.log("error - initDetailsProduct");

            } 
            $("#detail_loading").fadeOut();
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console && console.log("error");
            $("#popup_message .message").html(not_perform_action+". "+sorry_inconvenience+".");
            $("#popup_message").modal();
        }
    });  
}
function isDivisibleByMultiplier(n,multiplier){
    if((n.replace(",",".") % multiplier.toString().replace(",",".")) != 0){
        return false;
    }
    else{
        return true;
    }
}

function add_to_cart_advance(ref,referenceAlt){
    var qtd_pp = 1;  var qtdMultiplier = 1;
    var DocType =  29;
	qtd_pp = $('[id="input_pp_qtd_'+ref+'"]').val();    
    
    if($('#input_pp_qtd_'+ref).attr("multi") != undefined)
        qtdMultiplier = $('#input_pp_qtd_'+ref).attr("multi").replace(",",".");
    
    if(checkValueByMultiplier == '1' && !isDivisibleByMultiplier(qtd_pp,qtdMultiplier)){
        $("#popup_message .message").html(incorrect_incomplete_data+"<br>Só pode inserir multiplos de "+qtdMultiplier);
        $("#popup_message").modal();
    }
    else{        
        if(isIntAndSuperiorZero(qtd_pp)){
            $("#popup_message .message").html("<img src=\"/images/loader.gif\" title=\"A carregar\" alt=\"A carregar informação\">");
            $("#popup_message").modal();
            var validateStock = 0;
            if (validateStock == '1'){
                var inputData = 'ref=' + ref
                    +'&DocumentAction=' + 1 
                    +'&warehouseID=' + warehouseID                
                    +'&totalQuantity=' + qtd_pp;
                
                $.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_pp
                                    +'&Quantity=' + qtd_pp
                                    +'&LogisticUnitTypeID=' 
                                    +'&extraData='
                                    +'&isB2C='+isB2C
                                    +'&pricetype=' + pricetype
                                    +'&continueOnlyIfLogged='+continueOnlyIfLogged
                                    +"&showAccumulativeDiscounts="+showAccumulativeDiscounts;
                                $.ajax({
                                    url: "/ActionInvokerGenericAPI.ashx?input=dyn-post&output=string&ActionID=4885",
                                    type: "post",
                                    data: inputData,
                                    success: function(response, textStatus, jqXHR) { 
                                        $('#popup_add_product_to_cart').modal('hide');
                                        if (response == '1'){
                                            console && console.log("Success");
                                            if (DocType == 29){
                                                $("#popup_message .message").html(added_shopping_successfully);   
                                                GetStateShoppingCart();
                                                resetInfo();
                                                setTimeout(function() {   
                                                    $('#popup_message').modal('hide');}, 1000);
                                            }else{$("#popup_message .message").html(added_successfully);
                                                  resetInfo();
                                                  setTimeout(function() {	 
                                                      $('#popup_message').modal('hide');}, 1000);}
                                        }else if (response == '2'){
                                            if (DocType == 29){
                                                $("#popup_message .message").html(shopping_updated_success+".");  
                                                GetStateShoppingCart();
                                                resetInfo();
                                                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+".");
                                    }
                                });  
                                
                            }
                            $("#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_pp
                    +'&Quantity=' + qtd_pp
                    +'&LogisticUnitTypeID=' 
                    +'&extraData='
                    +'&isB2C='+isB2C
                    +'&pricetype=' + pricetype
                    +'&continueOnlyIfLogged='+continueOnlyIfLogged
                    +"&showAccumulativeDiscounts="+showAccumulativeDiscounts;
                $.ajax({
                    url: "/ActionInvokerGenericAPI.ashx?input=dyn-post&output=string&ActionID=4885",
                    type: "post",
                    data: inputData,
                    success: function(response, textStatus, jqXHR) { 
                        $('#popup_add_product_to_cart').modal('hide');
                        if (response == '1'){
                            console && console.log("Success");
                            if (DocType == 29){
                                $("#popup_message .message").html(added_shopping_successfully);   
                                GetStateShoppingCart();
                                resetInfo();
                                setTimeout(function() {
                                    $('#popup_message').modal('hide');}, 1000);
                            }else{
                                $("#popup_message .message").html(added_successfully);   
                 				GetStateShoppingCart();
                            resetInfo();
                            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 isIntAndSuperiorZero(n){
    return $.isNumeric(n) && n > 0  && parseFloat(n) == parseInt(n, 10) && !isNaN(n);
}
    
function resetInfo(){
	$('#qtd .form-control').val(1); 
}
