//---------------------------------------------------------------------------------------------------------------------------
//---------------------------FUNÇÕES PARA GERAR O ACORDEÃO DE NAVEGAÇÃO EM CAMPANHAS------------------------------------------
/* Autor: Rui Carvalho
   Modified by:	Miguel Caires */
var campanhas, acordeoes;
function loadAccordions(cria_acordeoes, cmp, sep, caminho_sep) {
        /* **************************  ACORDEÃO DE CAMPANHAS  ******************************* */
        try{
            campanhas = new accordion('container_campanhas', {
                    classNames : {
                        toggle       : 'campanhas_toggle',
                        toggleActive : 'campanhas_toggle_active',
                        content      : 'campanhas_content'
                    }
                }
            );
        }
        catch(err){ alert('ERRO Acordeao: ' + err.description); }
        /* ********************************** Sub Níveis *********************************** */
        acordeoes = new Object();
        for(var i=0; i<cria_acordeoes.length; i++){
            for(var j=0; j<cria_acordeoes[i].length; j++){
                var nome_container = 'container_c_' + cria_acordeoes[i][j] + '_sub_' + (i+1);
                var cria = new accordion(nome_container, {
                    classNames : {
                        toggle       : 'campanhas_toggle_sub_' + (i+1),
                        toggleActive : 'campanhas_toggle_active_sub_' + (i+1),
                        content      : 'campanhas_content_sub_' + (i+1)
                    }
                });
                var assoc_name = cria_acordeoes[i][j].toString();
                if(acordeoes['c_'+assoc_name] == undefined){
                    acordeoes['c_'+assoc_name] = new Object();
                }
                // CRIAMOS UM ARRAY DE ACORDEÕES INDEXADOS ASSOCIATIVAMENTE NA 1a POSIÇÃO PELO ID_CAMPANHA, E INDEXADOS NA 2a
                // POSIÇÃO À PROFUNDIDADE DO ACORDEÃO (SUB-NÍVEL) ===> acordeao[c_17][p_2]: acordeao da campanha 17, sub-nível 2
                acordeoes['c_'+assoc_name]['p_'+(i+1)] = cria;
            }
        }
        /* ****************************  FECHAMOS OS ACORDEOES ANTES DE ABRIR NO SEPARADOR CERTO ******************************* */
        fechaAccordions();
        /* ****************************  ABRIR NO SEPARADOR CERTO ******************************* */
        abrirAccordion(cmp, sep, caminho_sep);
}


/* **************  FUNÇÃO PARA FAZER O LOAD DO ACORDEÃO COM OS TABS FECHADOS  ************ */
function fechaAccordions(){
     // You can hide the accordions on page load like this, it maintains accessibility
     var verticalAccordions = $$('.campanhas_toggle');
     verticalAccordions.each(function(accordion) {
          $(accordion.next(0)).setStyle(
              {
                height: '0px'
              }
          );
        }
     );
}


/* **************  FUNÇÃO PARA ABRIR O ACORDEÃO NUM DADO SEPARADOR  ************ */
function abrirAccordion(cmp, sep, caminho_sep){
    //1-Começamos por mostrar o nível dos primeiros separadores da campanha
    campanhas.activate($('acrd_c_'+cmp));

    //2-Mostramos cada um dos sub-acordeões até surgir o separador escolhido no acordeão
    for(i=1; i<caminho_sep.length;i++){
        var id = caminho_sep[i];
        acordeoes['c_'+cmp]['p_'+i].activate($('acrd_sep_'+id));
    }
}
//---------------------------------------------------------------------------------------------------------------------------
//                                                            |
//                                                            |
//                                                            |
//                                                            |
//---------------------------------------------------------------------------------------------------------------------------
//--------------------------------------VALIDAÇÃO DE FORMULÁRIOS NO FRONT-OFFICE---------------------------------------------
/* Autor: Rui Carvalho
   Modified by:	Miguel Caires */
function check_form(frm, campos){//frm é a form que queremos verificar (passada usando 'this' na tag <form>)
  for(var i=0; i<campos.length; i++){
      if(!check_preenchimento_campo(frm, campos[i][0])) {
          alert("O campo de e-mail tem que estar preenchido.");
          return false;
      }
      if(!check_email(frm.elements[campos[i][0]].value)){
          alert("O e-mail introduzido não é válido! Volte a introduzir o e-mail.");
          frm.elements[campos[i][0]].focus();
          if(document.all || document.getElementByID){ frm.elements[campos[i][0]].style.background = "orange"; } //change the color of text field
          return false; //Não submetemos a form
      }
  }
  return true; //Se chegarmos aqui é porque está tudo ok na form
}
function check_preenchimento_campo(frm, inpt_name){
    if(frm.elements[inpt_name].value.length < 1){
      frm.elements[inpt_name].focus(); //Damos o focus ao campo
      //Mudamos a cor ao campo para realçar q nao esta preenchido
      if(document.all || document.getElementByID){ frm.elements[inpt_name].style.background = "orange"; }
      return false; //Não submetemos a form
    }
    return true; //Se chegarmos aqui é pq está tudo bem
}
//----------Verificações específicas----------------------------
function check_email(emailStr) {
    var re = /^.+@[^\.].*\.[a-z]{2,}$/; //   var re = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return re.test(emailStr);
}
function check_email_OLD(emailStr) {
    //Verificamos existência de caracteres permitidos apenas
    okChars = "1234567890qwertyuiop[]asdfghjklzxcvbnm.@-_QWERTYUIOPASDFGHJKLZXCVBNM";
    for(i=0; i < emailStr.length ;i++){
      if(okChars.indexOf(emailStr.charAt(i))<0){ return false; }
    }
    var emailRegExp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;
    return emailRegExp.test(emailStr);
}

function validaFormCompraPopUp(nomeForm, idProduto){
    var objQtdd = $(nomeForm).elements['quantidade_' + idProduto];
    var quant = objQtdd.value;
    var tamanho = $('IDProduto_'+idProduto).value;

    //Validamos a quantidade
    if( isNaN(quant) ){
        alert('Introduza um valor numérico inteiro para a quantidade.');
        return false;
    }
    else if(parseInt(quant) != quant){
        alert('Introduza um valor inteiro.');
        return false;
    }
    else if(quant <= 0){
        alert('Introduza uma quantidade positiva.');
        return false;
    }
    /*
    else if(quant > stock){
        alert('Quantidade não disponível. Apenas disponíveis ' + stock + ' unidades.');
        return false;
    }
*/
    //Validamos o tamanho
    if(tamanho == 0){
        alert('Tem de escolher um tamanho.');
        return false;
    }

    return true;
}
//---------------------------------------------------------------------------------------------------------------------------
//                                                            |
//                                                            |
//                                                            |
//                                                            |
//---------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------FUNÇÕES PARA O CARRINHO DE COMPRAS----------------------------------------------
function mostraMensagemEncomenda(){
    var divMensagem = document.getElementById('mensagem_encomenda_1');
    divMensagem.style.display = '';
}
function escondeMensagemEncomenda(){
    var divMensagem = document.getElementById('mensagem_encomenda_1');
    divMensagem.style.display = 'none';
    divMensagem = document.getElementById('mensagem_encomenda_2');
    divMensagem.style.display = 'none';
}
function clicaEntregaMoradaPrincipal(morada, cod_postal, cod_rua, localidade, pais){
  escondeMensagemEncomenda();
  document.forms['frm_carrinho_passo_2'].morada_enc.value     = morada;
  document.forms['frm_carrinho_passo_2'].cod_postal_enc.value = cod_postal;
  document.forms['frm_carrinho_passo_2'].cod_rua_enc.value    = cod_rua;
  document.forms['frm_carrinho_passo_2'].localidade_enc.value = localidade;
  document.forms['frm_carrinho_passo_2'].pais_enc.value       = pais;
  
  document.forms['frm_carrinho_passo_2'].morada_enc.removeAttribute('disabled');
  document.forms['frm_carrinho_passo_2'].cod_postal_enc.removeAttribute('disabled');
  document.forms['frm_carrinho_passo_2'].cod_rua_enc.removeAttribute('disabled');
  document.forms['frm_carrinho_passo_2'].localidade_enc.removeAttribute('disabled');
  document.forms['frm_carrinho_passo_2'].pais_enc.removeAttribute('disabled');

  escondeCamposAmigo();
}
function clicaEntregaMoradaPontual(){
  escondeMensagemEncomenda();
  document.forms['frm_carrinho_passo_2'].morada_enc.value     = '';
  document.forms['frm_carrinho_passo_2'].cod_postal_enc.value = '';
  document.forms['frm_carrinho_passo_2'].cod_rua_enc.value    = '';
  document.forms['frm_carrinho_passo_2'].localidade_enc.value = '';
  document.forms['frm_carrinho_passo_2'].pais_enc.value = '';
  
  document.forms['frm_carrinho_passo_2'].morada_enc.removeAttribute('disabled');
  document.forms['frm_carrinho_passo_2'].cod_postal_enc.removeAttribute('disabled');
  document.forms['frm_carrinho_passo_2'].cod_rua_enc.removeAttribute('disabled');
  document.forms['frm_carrinho_passo_2'].localidade_enc.removeAttribute('disabled');
  document.forms['frm_carrinho_passo_2'].pais_enc.removeAttribute('disabled');

  escondeCamposAmigo();
}
function clicaRecolhaShowroom(morada, cod_postal, cod_rua, localidade, pais){
  escondeMensagemEncomenda();
  document.forms['frm_carrinho_passo_2'].morada_enc.value     = morada;
  document.forms['frm_carrinho_passo_2'].cod_postal_enc.value = cod_postal;
  document.forms['frm_carrinho_passo_2'].cod_rua_enc.value    = cod_rua;
  document.forms['frm_carrinho_passo_2'].localidade_enc.value = localidade;
  document.forms['frm_carrinho_passo_2'].pais_enc.value       = pais;

  document.forms['frm_carrinho_passo_2'].morada_enc.setAttribute('disabled','disabled');
  document.forms['frm_carrinho_passo_2'].cod_postal_enc.setAttribute('disabled','disabled');
  document.forms['frm_carrinho_passo_2'].cod_rua_enc.setAttribute('disabled','disabled');
  document.forms['frm_carrinho_passo_2'].localidade_enc.setAttribute('disabled','disabled');
  document.forms['frm_carrinho_passo_2'].pais_enc.setAttribute('disabled','disabled');

  escondeCamposAmigo();
}
function clicaOfertaAmigo(){
  mostraMensagemEncomenda();
  document.forms['frm_carrinho_passo_2'].morada_enc.value     = '';
  document.forms['frm_carrinho_passo_2'].cod_postal_enc.value = '';
  document.forms['frm_carrinho_passo_2'].cod_rua_enc.value    = '';
  document.forms['frm_carrinho_passo_2'].localidade_enc.value = '';
  document.forms['frm_carrinho_passo_2'].pais_enc.value       = '';
  document.forms['frm_carrinho_passo_2'].telefone_enc.value       = '';

  document.forms['frm_carrinho_passo_2'].morada_enc.removeAttribute('disabled');
  document.forms['frm_carrinho_passo_2'].cod_postal_enc.removeAttribute('disabled');
  document.forms['frm_carrinho_passo_2'].cod_rua_enc.removeAttribute('disabled');
  document.forms['frm_carrinho_passo_2'].localidade_enc.removeAttribute('disabled');
  document.forms['frm_carrinho_passo_2'].pais_enc.removeAttribute('disabled');
  document.forms['frm_carrinho_passo_2'].telefone_enc.removeAttribute('disabled');

  mostraCamposAmigo();
}
function mostraCamposAmigo(){
    $('amigo_nome').style.display        = '';
    $('amigo_morada').style.display      = '';
    $('amigo_cod_postal').style.display  = '';
    $('amigo_pais').style.display        = '';
    $('amigo_telefone').style.display    = '';
    $('amigo_num_contrib').style.display = '';
}
function escondeCamposAmigo(){
    $('amigo_nome').style.display        = 'none';
    $('amigo_morada').style.display      = 'none';
    $('amigo_cod_postal').style.display  = 'none';
    $('amigo_pais').style.display        = 'none';
    $('amigo_telefone').style.display    = 'none';
    $('amigo_num_contrib').style.display = 'none';
}
function mostra_pagamento_cartao_credito(){
    document.getElementById('dados_cartao_credito').style.display = '';
    document.getElementById('dados_multibanco').style.display     = 'none';
    document.getElementById('dados_psc').style.display     = 'none';
}
function mostra_pagamento_multibanco(){
    document.getElementById('dados_cartao_credito').style.display = 'none';
    document.getElementById('dados_multibanco').style.display     = '';
    document.getElementById('dados_psc').style.display     = 'none';
}
function mostra_pagamento_psc(){
    document.getElementById('dados_cartao_credito').style.display = 'none';
    document.getElementById('dados_multibanco').style.display     = 'none';
    document.getElementById('dados_psc').style.display     = '';
}
//---------------------------------------------------------------------------------------------------------------------------
//                                                            |
//                                                            |
//                                                            |
//                                                            |
//---------------------------------------------------------------------------------------------------------------------------
//---------------------------------------------SCROLL DE FRASES FANTÁSTICAS--------------------------------------------------
/* Autor: Rui Carvalho
   Modified by:	Miguel Caires */
//Event.observe(window, 'load', function(){ if($('frase_rotativa') != null){ loop_texto(frases, 2000);} }); -- redefinia o load de window...foi para o fns_output.php (linha 205)
var frase_counter=0;
function loop_texto(frases, tempo){
    var call_mostra_texto = function(){ mostra_texto(frases); };
    setInterval(call_mostra_texto , tempo);
}
function mostra_texto(frases){
  if(frase_counter>=frases.length) frase_counter=0;
  $('frase_rotativa').innerHTML = frases[frase_counter];
  frase_counter++;
}
//---------------------------------------------------------------------------------------------------------------------------
//                                                            |
//                                                            |
//                                                            |
//                                                            |
//---------------------------------------------------------------------------------------------------------------------------
//---------------------------------------RELOGIOS DE COUNTDOWN DAS CAMPANHAS-------------------------------------------------
/* Author:Robert Hashemian (http://www.hashemian.com/)
   Modified by:	Munsifali Rashid (http://www.munit.co.uk/), Tilesh Khatri, Rui Carvalho */
function StartCountDown(targetDiv,myTargetDate){
  var dataFinal	 = new Date(myTargetDate);
  var dataActual = new Date();
  diferencaDatas = new Date(dataFinal-dataActual);
  numSegundos    = Math.floor(diferencaDatas.valueOf()/1000);
  CountBack(targetDiv,numSegundos);
}
function Calcage(secs, num1, num2){
  s = ((Math.floor(secs/num1))%num2).toString();
  if (s.length < 2){
    s = "0" + s;
  }
  return (s);
}
function CountBack(target_div, secs){
  var DisplayStr;
  var DisplayFormat = "%%D%% Dias %%H%%h %%M%%m %%S%%s";
  DisplayStr = DisplayFormat.replace(/%%D%%/g, Calcage(secs,86400,100000));
  DisplayStr = DisplayStr.replace(/%%H%%/g,    Calcage(secs,3600,24));
  DisplayStr = DisplayStr.replace(/%%M%%/g,    Calcage(secs,60,60));
  DisplayStr = DisplayStr.replace(/%%S%%/g,    Calcage(secs,1,60));
  if(secs > 0){
    document.getElementById(target_div).innerHTML = DisplayStr;
    setTimeout("CountBack('" + target_div + "'," + (secs-1) + ");", 990);
  }
  else{
    document.getElementById(target_div).innerHTML = "Campanha Terminada!";
    var id = target_div.substring(11);
    document.getElementById('banner_da_campanha_'+id).appendChild( document.getElementById('img_banner_da_campanha_'+id) );
    document.getElementById('botoes_campanha_'+id).style.display= 'none';
  }
}
//---------------------------------------------------------------------------------------------------------------------------
//                                                            |
//                                                            |
//                                                            |
//                                                            |
//---------------------------------------------------------------------------------------------------------------------------
//------------------------------------UTILIDADES VÁRIAS PARA O FRONT-OFFICE--------------------------------------------------
/* Autor: Rui Carvalho
   Modified by:	Miguel Caires */

function mostraDivEscolhaTamQtdd(targetDiv){
    $(targetDiv).show();
}

function carregaMiniatura(id){
    var img_old = $('zona_imagem_produto').src;
    $('zona_imagem_produto').src = img_old.substr(0, img_old.length - 5) + id + '.jpg';
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
		while (obj = obj.offsetParent);
		return [curleft,curtop];
	}
}

function openWindow( pageToLoad, winName, width, height, center){
    xposition=0; yposition=0;
    if ((parseInt(navigator.appVersion) >= 4 ) && (center)){
        xposition = (screen.width - width) / 2;
        yposition = (screen.height - height) / 2;
    }
	//0 => no
	//1 => yes
    var args = "";
    	args += "width=" + width + "," + "height=" + height + ","
		+ "location=0,"
		+ "menubar=0,"
		+ "resizable=0,"
		+ "scrollbars=0,"
		+ "statusbar=false,dependent,alwaysraised,"
		+ "status=false,"
		+ "titlebar=no,"
		+ "toolbar=0,"
		+ "hotkeys=0,"
		+ "screenx=" + xposition + ","  //NN Only
		+ "screeny=" + yposition + ","  //NN Only
		+ "left=" + xposition + ","     //IE Only
		+ "top=" + yposition;           //IE Only
		//fullscreen=yes, add for full screen
    	var dmcaWin = window.open(pageToLoad,winName,args );
    	dmcaWin.focus();
    //window.showModalDialog(pageToLoad,"","dialogWidth:650px;dialogHeight:500px");

/*
Call the function as openWindow("yourfilenamehere","windownamehere",500,600,true);
500 => width, 600 => height, true => if you want to place the popup window in the center of the screen
*/
}
//---------------------------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------------------------
//                                                            |
//                                                            |
//                                                            |
//                                                            |
//---------------------------------------------------------------------------------------------------------------------------
//------------------------------------FUNÇÕES DREAMWEAVER PARA ROLLOVER DE IMAGENS-------------------------------------------

	function MM_preloadImages() { //v3.0
		var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    	var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    	if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
	}

	function MM_swapImgRestore() { //v3.0
		var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
	}

	function MM_findObj(n, d) { //v4.01
  		var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    		d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  		if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  		for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  		if(!x && d.getElementById) x=d.getElementById(n); return x;
	}

	function MM_swapImage() { //v3.0
  		var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   		if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
	}


function formpost_frame(in_form, url, target_div){
    form = $(in_form);
    params = form.serialize(true);
    var hash_params = $H(params);  //$H constroi um objecto tipo array associativo com metodos proprios como set, unset, get, each, etc. É construido com new Hash() ou $H(objecto)
    new Ajax.Updater(target_div, url,
        {
            method: 'post',
            parameters: hash_params,
            evalScripts: true
        }
    );
    new Effect.BlindDown(target_div, { duration: 0.5} );
    //new Effect.Appear(target_div, {duration:0.5, from:0.0, to:1.0});
}