﻿/* --- Funções para actualizar o carrinho através de pedidos AJAX (utilizado pelos produtos) --- */
function addProductToCart(prodId)
{

    var xhr = new createXHR();
    xhr.open('GET', '../Handlers/AddProductToShopCart.ashx?prodId='+prodId, true);
    xhr.onreadystatechange = function ()
        {
            if (xhr.readyState == 4 && xhr.status == 200)
            {
                if (xhr.responseText=="") return;
                
                var newProdInfo = eval("("+xhr.responseText+")");
                
                // Actualizar carrinho.
                refreshShopCart(newProdInfo.typeHtmlId, newProdInfo.prodHtmlId, newProdInfo.prodName, newProdInfo.prodPrice);
                
                // actualizar preço.
                refreshPrice(FIRST_YEAR_MONTHLY_TOTAL_ID, newProdInfo.monthlyFirstYearTotal);
                refreshPrice(NEXT_YEARS_MONTHLY_TOTAL_ID, newProdInfo.monthlyNextYearsTotal);
            }
        };
    xhr.setRequestHeader('If-Modified-Since', 'Thu, 1 Jan 1970 00:00:00 GMT');
    xhr.setRequestHeader('Cache-Control', 'no-cache');
    xhr.send(null);
}

// Indirect indica se a escolha da promoção foi indirecta, ou seja, se foram escolhidos os produtos que 
// faziam parte da promoção. A diferença é que neste caso é necessário remover do carrinho
// os produtos que faziam parte da promoção, porque o que vai ser guardado agora é a promoção.
function addPromotionToCart(promId)
{
    var xhr = new createXHR();
    xhr.open('GET', '../Handlers/AddPromotionToShopCart.ashx?promId='+promId, true);
    xhr.onreadystatechange = function ()
        {
            if (xhr.readyState == 4 && xhr.status == 200)
            {
                if (xhr.responseText=="") return;
                
                var newPromInfo = eval("("+xhr.responseText+")");
                
                refreshShopCart(newPromInfo.typeHtmlId, newPromInfo.prodHtmlId, newPromInfo.prodName, newPromInfo.prodPrice);
                
                refreshPrice(FIRST_YEAR_MONTHLY_TOTAL_ID, newPromInfo.monthlyFirstYearTotal);
                refreshPrice(NEXT_YEARS_MONTHLY_TOTAL_ID, newPromInfo.monthlyNextYearsTotal);
                
                for (var i = 0; i < newPromInfo.products.length; ++i)
                    removeProdFromCart(newPromInfo.products[i], newPromInfo.typeHtmlId);
            }
        };
    xhr.setRequestHeader('If-Modified-Since', 'Thu, 1 Jan 1970 00:00:00 GMT');
    xhr.setRequestHeader('Cache-Control', 'no-cache');
    xhr.send(null);
}

function removeProductFromCart(prodId)
{
    var xhr = new createXHR();
    xhr.open('GET', '../Handlers/RemoveProductFromShopCart.ashx?prodId='+prodId, true);
    xhr.onreadystatechange = function ()
        {
            if (xhr.readyState == 4 && xhr.status == 200)
            {
                if (xhr.responseText=="") return;
                
                var prodInfo = eval("("+xhr.responseText+")");
                
                // remover prodInfo do html shopping cart!!
                removeProdFromCart(prodInfo.prodHtmlId, prodInfo.typeHtmlId);
                
                removeForcedEquipments(prodInfo.equipsToRemove);
                
                // actualizar preço.
                refreshPrice(FIRST_YEAR_MONTHLY_TOTAL_ID, prodInfo.monthlyFirstYearTotal);
                refreshPrice(NEXT_YEARS_MONTHLY_TOTAL_ID, prodInfo.monthlyNextYearsTotal);
                refreshPrice(INTERVENTIONS_TOTAL_ID, prodInfo.interventionsTotal);
            }
        };
    xhr.setRequestHeader('If-Modified-Since', 'Thu, 1 Jan 1970 00:00:00 GMT');
    xhr.setRequestHeader('Cache-Control', 'no-cache');
    xhr.send(null);
}

function removePromotionFromCart(promId){
    var xhr = new createXHR();
    xhr.open('GET', '../Handlers/RemovePromotionFromShopCart.ashx?promId='+promId, true);
    xhr.onreadystatechange = function ()
        {
            if (xhr.readyState == 4 && xhr.status == 200)
            {
                if (xhr.responseText=="") return;
                
                var promInfo = eval("("+xhr.responseText+")");
                
                // remover promInfo do html shopping cart!!
                removeProdFromCart(promInfo.prodHtmlId, promInfo.typeHtmlId);
                
                removeForcedEquipments(promInfo.equipsToRemove);
                
                // actualizar preço.
                refreshPrice(FIRST_YEAR_MONTHLY_TOTAL_ID, promInfo.monthlyFirstYearTotal);
                refreshPrice(NEXT_YEARS_MONTHLY_TOTAL_ID, promInfo.monthlyNextYearsTotal);
                refreshPrice(INTERVENTIONS_TOTAL_ID, promInfo.interventionsTotal);
            }
        };
    xhr.setRequestHeader('If-Modified-Since', 'Thu, 1 Jan 1970 00:00:00 GMT');
    xhr.setRequestHeader('Cache-Control', 'no-cache');
    xhr.send(null);
}

// Altera a forma de pagamento de um equipamento.
function changeEquipmentOrder(equipId, changeTo)
{
    var xhr = new createXHR();
    xhr.open('GET', '../Handlers/ChangeEquipmentOrder.ashx?equipId='+equipId+'&changeTo='+changeTo, true);
    xhr.onreadystatechange = function ()
        {
            if (xhr.readyState == 4 && xhr.status == 200)
            {
                if (xhr.responseText=="") return;
                                
                var equipInfo = eval("("+xhr.responseText+")");
                
                removeProdFromCart(equipInfo.Remove.equipmentId, equipInfo.Remove.divId);
                refreshShopCart(equipInfo.Add.divId, equipInfo.Add.equipmentId, equipInfo.Add.equipmentName, equipInfo.Add.equipmentPrice);
                
                refreshActivationRates(equipInfo.ActivationRates);
                
                refreshPrice(FIRST_YEAR_MONTHLY_TOTAL_ID, equipInfo.monthlyFirstYearTotal);
                refreshPrice(NEXT_YEARS_MONTHLY_TOTAL_ID, equipInfo.monthlyNextYearsTotal);
                refreshPrice(INTERVENTIONS_TOTAL_ID, equipInfo.interventionsTotal);
            }
        };
    xhr.setRequestHeader('If-Modified-Since', 'Thu, 1 Jan 1970 00:00:00 GMT');
    xhr.setRequestHeader('Cache-Control', 'no-cache');
    xhr.send(null);
}

// Indica o número de operações assincronas a decorrer para os equipamentos...
var equipmentAssyncOperations = 0;

// Retorna true se houver alguma operação assyncrona para equipamentos a decorrer.
// Utilizado pelas páginas que contêm equipamentos mandatórios para evitar selecções enquanto
// ainda se valida a anterior.
function existsEquipmentAssyncOperation()
{
    return equipmentAssyncOperations > 0;
}

// Adiciona um equipamento ao carrinho.
function addEquipment(equipId, operation, forced)
{

    ++equipmentAssyncOperations;
    
    var xhr = new createXHR();
    xhr.open('GET', '../Handlers/AddEquipment.ashx?equipId='+equipId+'&operation='+operation+'&forced='+forced, true);
    xhr.onreadystatechange = function ()
        {
            if (xhr.readyState == 4)
            {
                if (xhr.status == 200)
                {
                    if (xhr.responseText != "")
                    {          
                        var equipsInfo = eval("("+xhr.responseText+")");

                        refreshShopCart(equipsInfo.newEquipInfo.divId, 
                                        equipsInfo.newEquipInfo.equipmentId, 
                                        equipsInfo.newEquipInfo.equipmentName, 
                                        equipsInfo.newEquipInfo.equipmentPrice);
                                        
                        var toRemove = equipsInfo.equipsToRemove;
                        
                        for (var i = 0; i < toRemove.length; ++i)
                        {
                            removeProdFromCart(toRemove[i].equipHtmlId, toRemove[i].divId);
                            removeEquipmentSelection(toRemove[i].equipId);
                        }
                        
                        refreshActivationRates(equipsInfo.ActivationRates);
                        
                        refreshPrice(FIRST_YEAR_MONTHLY_TOTAL_ID, equipsInfo.monthlyFirstYearTotal);
                        refreshPrice(NEXT_YEARS_MONTHLY_TOTAL_ID, equipsInfo.monthlyNextYearsTotal);
                        refreshPrice(INTERVENTIONS_TOTAL_ID, equipsInfo.interventionsTotal);
                        
                    }
                }
                --equipmentAssyncOperations;
            }
        };
    xhr.setRequestHeader('If-Modified-Since', 'Thu, 1 Jan 1970 00:00:00 GMT');
    xhr.setRequestHeader('Cache-Control', 'no-cache');
    xhr.send(null);
}

// Remove (se possivel) um equipamento do carrinho.
// O parâmetro oldCb tem uma referência para a combobox anteriormente seleccionada,
// para caso não possa ser removida voltar-se a seleccionar.
function removeEquipment(equipId, oldCb)
{
    ++equipmentAssyncOperations;
    
    var xhr = new createXHR();
    xhr.open('GET', '../Handlers/RemoveEquipment.ashx?equipId='+equipId, true);
    xhr.onreadystatechange = function ()
        {
            if (xhr.readyState == 4)
            {
                if (xhr.status == 200)
                {
                    if (xhr.responseText=="") 
                    {
                        // Equipamento impossivel de remover ... existe
                        // um produto que o tem como obrigatório e está
                        // seleccionado.
                        
                        // Toca a voltar a colocá-lo como checked.
                        oldCb.checked = true;
                    }
                    else
                    {               
                        var equipInfo = eval("("+xhr.responseText+")");
                    
                        removeProdFromCart(equipInfo.equipmentId, equipInfo.divId);
                    
                        refreshActivationRates(equipInfo.ActivationRates);
                    
                        refreshPrice(FIRST_YEAR_MONTHLY_TOTAL_ID, equipInfo.monthlyFirstYearTotal);
                        refreshPrice(NEXT_YEARS_MONTHLY_TOTAL_ID, equipInfo.monthlyNextYearsTotal);
                        refreshPrice(INTERVENTIONS_TOTAL_ID, equipInfo.interventionsTotal);
                    }
                }
                --equipmentAssyncOperations;
            }
        };
    xhr.setRequestHeader('If-Modified-Since', 'Thu, 1 Jan 1970 00:00:00 GMT');
    xhr.setRequestHeader('Cache-Control', 'no-cache');
    xhr.send(null);
}

// Altera a instalação escolhida.
function setInstalation(installId)
{
    var xhr = new createXHR();
    xhr.open('GET', '../Handlers/SetInstalation.ashx?installId='+installId, true);
    xhr.onreadystatechange = function ()
        {
            if (xhr.readyState == 4 && xhr.status == 200)
            {
                if (xhr.responseText=="") return;
                                
                var installInfo = eval("("+xhr.responseText+")");
                
                removeProdFromCart(installInfo.installId, installInfo.divId);
                refreshShopCart(installInfo.divId, installInfo.installId, installInfo.name, installInfo.price);
                refreshPrice(INTERVENTIONS_TOTAL_ID, installInfo.interventionsTotal);
            }
        };
    xhr.setRequestHeader('If-Modified-Since', 'Thu, 1 Jan 1970 00:00:00 GMT');
    xhr.setRequestHeader('Cache-Control', 'no-cache');
    xhr.send(null);
}

/* --------------------------------------------------------------------------------------------- */
/* --- Funções para actualizar o carrinho apenas através de JS (utilizado pelos packs) --- */

// variável que vai fazendo as contas para se saber o total a pagar. (utilizada na página de packs...)
var _monthlyTotal = 0;

// Renincia o shopping cart...
function restartShopCart()
{
    // Apagar todos os produtos e esconder divs com titulo do tipo.
    for(var i = 0; i < shopTypes.length; ++i)
    {
        var typeTitle = document.getElementById(TYPE_ID_PREFIX + shopTypes[i].id);
        var typeParent = typeTitle.parentNode;
        while(typeParent.nodeType == 3)
        {
            typeParent = typeParent.nextSibling;
        }
        while (typeTitle.nextSibling != undefined && typeTitle.nextSibling.nodeName.toLowerCase() != 'div')
        {
            typeParent.removeChild(typeTitle.nextSibling);
        }
        typeParent.style.display = 'none';
    }    
     
    var interventionsTitle = document.getElementById(INTERVENTIONS_ID);
    var interventionsParent = interventionsTitle.parentNode;
    while (interventionsTitle.nextSibling != undefined)
    {
        interventionsParent.removeChild(interventionsTitle.nextSibling);
    } 
    
    refreshPrice(FIRST_YEAR_MONTHLY_TOTAL_ID, 0);
    refreshPrice(NEXT_YEARS_MONTHLY_TOTAL_ID, 0);
    refreshPrice(INTERVENTIONS_TOTAL_ID, 0);
    DONE_DISCOUNTS = "";
    _monthlyTotal = 0;
    cleanDiscount();
    
    // Se estamos a fazer restart é porque se vai reninciar o processo de selecção, logo,
    // esconde-se as intervenções.
    hideInterventions();
}

// Prepara o shopping cart para ser utilizado pela página de packs.
// A preparação consiste em criar os tipos todos e deixá-los com display = none.
// Se isToHideInterventions esconde-se toda a informação associada a uma intervenção.
function initHtmlShopCart(types, isToHideInterventions)
{

    // Se o carrinho já vier com o nó dos descontos, utiliza-se esse nó como referência para a inserção de novos nós.
    // Caso contrário utiliza-se o nó do total.
    // Util quando se volta à pagina de packs com 1 pack seleccionado para se ajustar a sua posição.
    var nodeToInsertBefore = document.getElementById(FIRST_MONTH_DISCOUNT_ID).parentNode;
    //Podem haver nós de texto!!!
    while(nodeToInsertBefore.nodeType == 3)
    {
        nodeToInsertBefore = nodeToInsertBefore.previousSibling;
    }
    var nodeToInsertBeforeParent = nodeToInsertBefore.parentNode;
      for(var i = 0; i < types.length; ++i)
    {
        if ( types[i].name=="NETCABO ADSL")	
        {
        var aux= true;
        break;
        }
        else
        var aux=false;
        	
    }

    for(var i = 0; i < types.length; ++i)
    {
        var titleId = TYPE_ID_PREFIX + types[i].id;
        
        // Se o carrinho já vier com algum produto deste tipo preenchido, remove-se o div e adiciona-se de novo.
        // Util quando se volta à pagina de packs com 1 pack seleccionado para se ajustar a sua posição.
        var spanTitle = document.getElementById(titleId);
        if(spanTitle)
        {
            var spanTitleParent = spanTitle.parentNode;
            spanTitleParent.parentNode.removeChild(spanTitleParent);
            
            nodeToInsertBeforeParent.insertBefore(spanTitleParent, nodeToInsertBefore);
        }
        else
        {
     
            var div = document.createElement('div');
            div.className = 'resum-block';
            div.style.display = 'none';
            div.style.clear = 'left';
            
            spanTitle = document.createElement('label');
            spanTitle.id = titleId;
            spanTitle.className = 'shopTypeTitle';
            spanTitle.setAttribute('style', 'text-align:left;');
            spanTitle.style.width = "170px";
            
            if ( types[i].name=="NETCABO ADSL")		
                spanTitle.innerHTML = "NET MOBILE"
            else
                 if ( types[i].name=="NETCABO")		
                spanTitle.innerHTML = "NET"
            else
                if (types[i].name=="TVCABO" && aux==true)
                    spanTitle.innerHTML = "TV"
            else
                spanTitle.innerHTML = types[i].name;
            
            var divClear = document.createElement('div');
            divClear.className= 'clear';
            
            div.appendChild(spanTitle);
            div.appendChild(divClear);
            
            nodeToInsertBeforeParent.insertBefore(div, nodeToInsertBefore);
        }
    }
    
    if (isToHideInterventions) hideInterventions();
}

function hideInterventions()
{
    // Toca a esconder a intervenções e tudo relacionado com elas!
    var interventionBlock = document.getElementById(INTERVENTIONS_BLOCK);
    while (interventionBlock != undefined)
    {
        if (interventionBlock.nodeType == 3)
        {
            interventionBlock = interventionBlock.nextSibling;
            continue;
        }
        interventionBlock.style.display = 'none';
        interventionBlock = interventionBlock.nextSibling;
    }
}

// Adiciona um produto ao shopping cart. 
function addProduct(prodId, typeId, prodName, prodPrice)
{

    var typeDiv = document.getElementById(TYPE_ID_PREFIX + typeId).parentNode;
    
    // Vamos "procurar" pelo nó que tem o <div class=clear> para se inserir o novo produto antes
    // por questões visuais.
    //CJD 2008_11_05: Devido ao facto de termos que lançar no carrinho o CANAL PREMIUM antes dos PACKS...
    //(isto é para que a pesquisa por um Pack Predifined funcione, identificando logo qual a diferença para outro que seja igual mas sem os CANAIS PREMIUM)
    //... não podemos ir adicionando os produtos no lastChild do Node. Isto faria com que o CANAL PREMIUM surgisse visualmente acima
    // do PACK. Vamos adicionando na segunda posição do Node (firstChild + nextSibling), para ir empurrando o CANAL PREMIUM para baixo.
    var nodeToInsertBefore = typeDiv.firstChild;
    var nodeToInsertBefore = nodeToInsertBefore.nextSibling;
        
//    var clr = document.createElement('br');
//    clr.style.clear = "both";
    var pProdName = document.createElement('p');
    pProdName.id = PRODUCTS_ID_PREFIX + prodId;
    pProdName.innerHTML = prodName;
    
    var spanPrice = document.createElement('span');
    spanPrice.innerHTML = '€' + prodPrice;
    
    //typeDiv.insertBefore(clr, nodeToInsertBefore);
    typeDiv.insertBefore(pProdName, nodeToInsertBefore);
    typeDiv.insertBefore(spanPrice, nodeToInsertBefore);
    
    typeDiv.style.display = 'block';
    
    _monthlyTotal += prodPrice;
    _monthlyTotal = roundNumber(_monthlyTotal, 2);
    
    document.getElementById(FIRST_YEAR_MONTHLY_TOTAL_ID).innerHTML = '€' + _monthlyTotal;
    document.getElementById(NEXT_YEARS_MONTHLY_TOTAL_ID).innerHTML = '€' + _monthlyTotal;
}

function removeProduct(prodId, prodPrice)
{
    var pProdName = document.getElementById(PRODUCTS_ID_PREFIX + prodId);
    var divType = pProdName.parentNode;
    divType.removeChild(pProdName.nextSibling);
    divType.removeChild(pProdName);
    _monthlyTotal -= prodPrice;
    _monthlyTotal = roundNumber(_monthlyTotal, 2);
    
    document.getElementById(FIRST_YEAR_MONTHLY_TOTAL_ID).innerHTML = '€' + _monthlyTotal;
    document.getElementById(NEXT_YEARS_MONTHLY_TOTAL_ID).innerHTML = '€' + _monthlyTotal;
    
    divType.style.display = 'none';
}

function removeHIDDENProduct(prodId, prodName, prodPrice)
{
    var pProdName = document.getElementById(PRODUCTS_ID_PREFIX + prodId);
    var divType = pProdName.parentNode;
    divType.removeChild(pProdName.nextSibling);
    divType.removeChild(pProdName);
    _monthlyTotal -= prodPrice;
    _monthlyTotal = roundNumber(_monthlyTotal, 2);
    
    document.getElementById(FIRST_YEAR_MONTHLY_TOTAL_ID).innerHTML = '€' + _monthlyTotal;
    document.getElementById(NEXT_YEARS_MONTHLY_TOTAL_ID).innerHTML = '€' + _monthlyTotal;
}

function removeForcedEquipments(equipments)
{
    for(var i = 0; i < equipments.length; ++i)
    {
        // Remover o equipamento do carrinho...
        removeProdFromCart(equipments[i].htmlId, equipments[i].divId);

        // Retirar o checked do equipamento.
        removeEquipmentSelection(equipments[i].id);
    }
}
/* --------------------------------------------------------------------------------------- */

// Coloca o desconto com o valor passado em discountValue e coloca o div com display=block.
function setFirstMonthDiscount(discount, discountEnds)
{
    //document.getElementById(DISCOUNT_NAME_ID).innerHTML = 'Desconto durante ' + discountEnds + (discountEnds > 1? ' meses' : ' mês');
    document.getElementById(DISCOUNT_NAME_ID).innerHTML = 'Desconto ' + ((discountEnds == 0) ? "válido enquanto mantiver o pacote" : ("durante " + discountEnds + (discountEnds > 1? ' meses' : ' mês')));

    var discountValue = document.getElementById(FIRST_MONTH_DISCOUNT_ID);
    discountValue.innerHTML = '€'+discount;
    if (discount != "0.00")
        discountValue.parentNode.style.display = 'block';
    else
        discountValue.parentNode.style.display = 'none';
//    var existsDiscount = false;
//    
//    var divDiscount = document.getElementById(DISCOUNTS_ID);
//    
//    for (var i = 0; i < packProducts.length; ++i)
//    {
//        if (packProducts[i].discount > 0)
//        {
//            var pProdName = document.createElement('p');
//            if (packProducts[i].discountDesc == " ")
//                pProdName.innerHTML = packProducts[i].name;
//            else
//                pProdName.innerHTML = packProducts[i].name + ' (' + packProducts[i].discountDesc + ')';
//            
//            var spanPrice = document.createElement('span');
//            spanPrice.innerHTML = '€'+packProducts[i].discount;
//            
//            var divClear = document.createElement('div');
//            
//            divDiscount.appendChild(pProdName);
//            divDiscount.appendChild(spanPrice);
//            
//            existsDiscount = true;
//        }
//    }
//    
//    if (existsDiscount)
//    {
//        divDiscount.style.display = 'block';
//    }
}

// Coloca o div de descontos com display=none;
function cleanDiscount()
{
    document.getElementById(FIRST_MONTH_DISCOUNT_ID).parentNode.style.display = 'none';
//    var divDiscount = document.getElementById(DISCOUNTS_ID);
//    
//    var discountTitle = divDiscount.firstChild;
//    
//    while(discountTitle.nextSibling != null)
//    {
//        divDiscount.removeChild(discountTitle.nextSibling);
//    }
//    
//    divDiscount.style.display = 'none';
}

// Afecta o preço com o valor newPrice ... 
// ATENÇÃO: Não actualiza contador interno, util para quando é seleccionado um pack.
function setPackMonthlyForFirstYear(newPrice)
{
    var divPrice = document.getElementById(FIRST_YEAR_MONTHLY_TOTAL_ID);
    divPrice.innerHTML = '€' + newPrice;
}

function setPackMonthlyForNextYears(newPrice)
{
    var divPrice = document.getElementById(NEXT_YEARS_MONTHLY_TOTAL_ID);
    divPrice.innerHTML = '€' + newPrice;
}
//------------------------- Funções auxiliares -------------------------

// Actualiza o shop cart html. Adiciona o produto, o seu preço.
// NÃO ACTUALIZA O PREÇO MENSAL PARA PODER SER UTILIZADO PARA AS INTERVENÇÕES!
function refreshShopCart(typeHtmlId, prodHtmlId, prodName, prodPrice)
{            
    // referência para o div onde vai ser criado o novo produto.
    var divType = document.getElementById(typeHtmlId).parentNode;
    var nodeToInsertBefore = divType.lastChild;
    
    //Podem haver nós de texto!!!
    while(nodeToInsertBefore.nodeType == 3)
    {
        nodeToInsertBefore = nodeToInsertBefore.previousSibling;
    }
    
    
    // novo produto
    var name = document.createElement('p');
    name.id = prodHtmlId;
    name.innerHTML = prodName;
    
    var price = document.createElement('span');
    price.innerHTML = '€'+prodPrice;
    
    // adicionar novos filhos ao tipo.
    divType.insertBefore(name, nodeToInsertBefore);
    divType.insertBefore(price, name.nextSibling);
}

// Remove o nome do produto e o seu preço do shop cart html.
function removeProdFromCart(prodHtmlId, typeHtmlId)
{
    // referência para o elemento que contém o nome do produto a remover.
    var prodRef = document.getElementById(prodHtmlId);
    
    // ATENÇÃO PODE NÃO EXISTIR!
    if (prodRef != null)
    {
        // referência para o div que contém o produto.
        var divType = document.getElementById(typeHtmlId).parentNode;

        // remover preço
        divType.removeChild(prodRef.nextSibling);

        // remover nome
        divType.removeChild(prodRef);
    }
}

// Actualiza as taxas de activação presentes no carrinho.
function refreshActivationRates(activationRates)
{
    var activationsDiv = document.getElementById(ACTIVATION_RATES_ID);
    
    // Remover taxas actuais.
    while(activationsDiv.hasChildNodes())
    {
        activationsDiv.removeChild(activationsDiv.firstChild);
    }
    
    for (var i = 0; i < activationRates.length; ++i)
    {
        var name = document.createElement('p');
        name.innerHTML = activationRates[i].activationDesc;
    
        var price = document.createElement('span');
        price.innerHTML = '€'+activationRates[i].activationPrice;;
        
        activationsDiv.appendChild(name);
        activationsDiv.appendChild(price);
    }
}

// Actualiza o preço da mensalidade no shop cart html.
function refreshPrice(priceDiv, newPrice)
{
    document.getElementById(priceDiv).innerHTML = '€'+newPrice;
}

// Função auxiliar que arredonda um número (num) para dec casas decimais.
function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

//CJD 2008_11_05: Nova função para consulta o valor que está actualmente no carrinho
function getPrice(priceDiv)
{
    return document.getElementById(priceDiv).innerHTML;
}


//CJD 2008_11_05: Nova função para consulta do Pack que está seleccionado
function getPackId()
{
    return document.getElementById("_rSelected").value;
}