var estadoDiv='fechado';

function findObj(theObj, theDoc)
{
  var p, i, foundObj;
  
  if(!theDoc) theDoc = document;
  if( (p = theObj.indexOf("?")) > 0 && parent.frames.length)
  {
    theDoc = parent.frames[theObj.substring(p+1)].document;
    theObj = theObj.substring(0,p);
  }
  if(!(foundObj = theDoc[theObj]) && theDoc.all) foundObj = theDoc.all[theObj];
  for (i=0; !foundObj && i < theDoc.forms.length; i++) 
    foundObj = theDoc.forms[i][theObj];
  for(i=0; !foundObj && theDoc.layers && i < theDoc.layers.length; i++) 
    foundObj = findObj(theObj,theDoc.layers[i].document);
  if(!foundObj && document.getElementById) foundObj = document.getElementById(theObj);
  
  return foundObj;
}


function launchSplashWin(contentType, windowId, contentString, base_width, base_height, left, top, autoCloseTime, scroll, resizable) 
{
	var status_offset = 40;
	
	if(base_height == -1 || base_width == -1)
	{
		w_proportion = 800 / 1024;
		h_proportion = 700 / 768;
		
		x = screen.width;
		y = screen.height;
		
		width = x * w_proportion;
		height = y * h_proportion;
	}
	else
	{
		width = base_width;
		height = base_height+status_offset;
	}
	
	var w = window.screen.width;
	var h = window.screen.height;
	var l = (left != null) ? left : (w-width)/2;
	var t = (top != null) ? top : (h-height)/2;
	
	var uri = (contentType.toLowerCase() == "uri") ? contentString : "";
	
	splashWin = window.open(uri, windowId, 'width='+width+',height='+height+',top='+t+',left='+l+',fullscreen=0,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars='+scroll+',resizable='+resizable);
	splashWin.opener = this;
}

function showHide(id)
{
    if( document.getElementById(id).style.display == ''){
     document.getElementById(id).style.display="none";
    } else {
     document.getElementById(id).style.display='';
    }
}

function hideAll(id1, id2, id3, id4, id5, id6, id7, id8, id9)
{
    try{
					document.getElementById(id1).style.display="none";
					document.getElementById(id2).style.display="none";
					document.getElementById(id3).style.display="none";
					document.getElementById(id4).style.display="none";
					document.getElementById(id5).style.display="none";
					document.getElementById(id6).style.display="none";
					document.getElementById(id7).style.display="none";
					document.getElementById(id8).style.display="none";
					document.getElementById(id9).style.display="none";
    } catch (e){
    }
}

function showHideDestaque(destaque)
{
    //alert('new: '+destaque+" old: "+destaqueSel);
    if(destaque != destaqueSel)
    {
        //ShowHideDiv(destaque+"DIV", "");
        //ShowHideDiv(destaqueSel+"DIV", "none");
        
        ShowHideDiv(destaque+"IMG", "");
        ShowHideDiv(destaqueSel+"IMG", "none");
     
        tab_new = document.getElementById(destaque+"TAB");
        tab_new.className = "homeTabOn txtBlack2";
     
        tab_old = document.getElementById(destaqueSel+"TAB");
        tab_old.className = "homeTabOff txtBlack2";
     
        destaqueSel = destaque;
    }
}

//Actualiza a iframe para os wizards na area pessal
function UpdateWizardIframe(url, height)
{
   var iframe = document.getElementById("WizardFrame");
   iframe.src = url;
   iframe.style.height = height;
}

function ShowHideDiv(name, option)
{
    el = document.getElementById(name);
    el.style.display = option;
}

function ValidateCheckBox(sender, args)
{   
    var el;
    
    if(FindControl('conhecimento_chb'))
        el = FindControl('conhecimento_chb');
    else if(FindControl('conhecimento2_chb'))
        el = FindControl('conhecimento2_chb');    
        
    args.IsValid = el.checked;
}

function validaModalidadesEducational(sender, args)
{   
    var el;
    
   if(FindControl('modalidadePremium_ddl').selectedIndex > 0)
        el  = true;
   else if(FindControl('modalidadePublicacao_ddl').selectedIndex > 0)
        el = true;
   else if( FindControl('modalidadeAmbas_ddl').selectedIndex > 0)
        el = true;
   else
        el = false;

    args.IsValid = el;
}

function ValidateRadioButtons(sender, args)
{   
  var el = FindControl(sender.IdToValidate);
  args.IsValid = el.checked;
}

function CompareRadioButtons(sender, args)
{   
    var controlo2 = "";
    
    if(sender.IdToValidate.indexOf("1") > -1)
        controlo2 =  sender.IdToValidate.replace("1","2");
    else
        controlo2 = sender.IdToValidate.replace("2","1"); 

    var el = FindControl(sender.IdToValidate);
    var el2 = FindControl(controlo2); 
      

    args.IsValid = (el.checked || el2.checked);

}

function validaTipoPublicacao(sender, args)
{   
    var controlo2 = "";
    
    var textBoxId = 'nomeeditora_txb';
    var dropdownlistId =  'editoras_ddl';
   

    var textBox = FindControl(textBoxId);
    var dropdownlist = FindControl(dropdownlistId); 
    
    //debug
    // alert(textBox.value.length);
    // alert(dropdownlist.selectedIndex); 
    
    if(textBox.value.length > 0 || dropdownlist.selectedIndex > 0)
        args.IsValid  = true;
   else
        args.IsValid  = false;
}

function verificaInstituicao(sender, args)
{   
    var dropdownlistId =  'instituicao_ddl';
    
    var dropdownlist = FindControl(dropdownlistId); 
    
    //debug
    //alert(dropdownlist.selectedIndex); 
    
    if(dropdownlist.selectedIndex > 0)
        args.IsValid  = true;
   else
        args.IsValid  = false;
}

function verificaTipoPublicacoes(sender, args)
{
    var array = document.getElementByName("radioButtonPublicacoes"); 
    
    for(i=0; i < array.length; i++)
    {
        alert(array[i].checked);
    }
    
    args.IsValid  = false;
    
}

///////////////////////////////////FUNCOES AJAX //////////////////////////////

function actualizaFilhosCDU(id)
{
    actualizaCDU.Actualiza(id, actualizaFilhosCDU_Callback);
}

function actualizaFilhosCDU_Callback(response)
{
        //alert(response.value);
        
        var lista = new Array();
        lista = response.value;
        
        try
        { 
            var combo = document.getElementById('filhos_ddl');
            
            for(j=0; j < combo.options.length; j++)
            {
                combo.options[j] = null;
            } 
            
            var seleccionado = "";
                
            if(FindControl("cduSeleccionado_hd").value.length > 0)
            {
                seleccionado = FindControl("cduSeleccionado_hd").value;
            }
            else
                seleccionado = "-5";
            
            if(lista)
            {
                var indice = 0;
                var indexSeleccionado = 0;
                
                for(indice=0; indice < lista.length; indice++)
                {
                    if(seleccionado == lista[indice][0])
                    {
                        indexSeleccionado = indice;
                    }
                    
                    combo.options[indice] = new Option(lista[indice][1],lista[indice][0]);
                }
                
                if(indexSeleccionado > 0)
                    combo.options.selectedIndex = indexSeleccionado;
            }
        }
        catch (e){}
}

function ActualizaVotoCl(voto, idUser, idProduto, tipoProduto, urlEstrela, imageEl)
{
    response = ActualizaVoto.ActualizaVotoProduto(voto, idUser, idProduto, tipoProduto, urlEstrela);
    nvotos = numeroDeVotos(response.value);
    
    for(i=0; i < response.value.length; i++)
    {
        el = document.getElementById(imageEl.id.replace(/\d*$/, "") + i);
        el.src = response.value[i];
        el.onmouseout = function dummy() { resetEstrelas(nvotos, response.value.length, imageEl.id.replace(/\d*$/, "")); };        
    }
}

function numeroDeVotos(response)
{
    count = 0;
    
    for(i = 0; i < response.length; i++)
    {
        if(response[i].indexOf("Off") == -1)
            count++;
    }
    
    return count;
}

function CheckEmails(sender, args)
{  
    var _idToValidate = "";
    
    if(!sender.IdToValidate)
        _idToValidate = emailNameToCheck;
    else
        _idToValidate = sender.IdToValidate;
        
   var lista = retornaEmails.retornaOsEmails().value!=null?retornaEmails.retornaOsEmails().value:" ";
   var emailToValidate = FindControl(_idToValidate).value!=null?FindControl(_idToValidate).value:" ";
   args.IsValid = !(lista.indexOf(emailToValidate) > -1);
}

function actualizaCarrinho(idLivro, tipoProduto, livroArtigo, conjunto)
{
    if(livroArtigo)
    {
        if(conjunto)
            ActualizaCarrinho.Actualiza(idLivro, tipoProduto,livroArtigo, conjunto, actualizaCarrinho_Callback);
        else
            ActualizaCarrinho.Actualiza(idLivro, tipoProduto,livroArtigo, false, actualizaCarrinho_Callback);
    }
    else
    {
        if(conjunto)
            ActualizaCarrinho.Actualiza(idLivro, tipoProduto,'livro', conjunto, actualizaCarrinho_Callback);
       else
            ActualizaCarrinho.Actualiza(idLivro, tipoProduto,'livro', false, actualizaCarrinho_Callback);
    }
    
}

function actualizaCarrinho_Callback(response)
{
    // 0 - Genero
    // 1 - Nome Autor
    // 2 - Nome Produto
    // 3 - Url
    // 4 - NumItems
    // 5 - PrecoTotal 
    var lista = response.value; 
   
   document.getElementById('compra1Container').style.display='';
   document.getElementById('ultimoLivroGenero_div').innerHTML = lista[0];
   document.getElementById('ultimoLivroNomeP_div').innerHTML = lista[2];
   document.getElementById('ultimoLivroNomeA_div').innerHTML = lista[1];
   document.getElementById('ultimoLivroUrl_div').src = lista[3].replace('~','..');
   document.getElementById('totalItems_span').innerHTML = lista[4];
   document.getElementById('totalPreco_span').innerHTML = lista[5];
   

   if(estadoDiv=='fechado')
    slider('compra1Container',''); 
    
    
    //Redirecciona para a pagina do carrinho
    var urlAntigo = document.location.href;
    document.location.href = FindControl("CarrinhoUrl_hdf").value+"?LastPage="+urlAntigo;
    //alert("teste");
   
  
}

function actualizaCarrinhoConjunto(idLivro1, idLivro2)
{
        //ActualizaCarrinho.ActualizaCarrinhoConjunto(idLivro1, idLivro2, actualizaCarrinho_Callback);
        actualizaCarrinho(idLivro1, 'papel', 'livro', true);
        actualizaCarrinho(idLivro2, 'papel', 'livro', true)
    
}

//Checks if a password field and it's validation field have the same value
function CheckPassword(sender, args)
{
    newp = FindControl('novapass_txb');    
    args.IsValid = (newp.value == args.Value);
}

// Finds in the current page, the control that contains the given string. If the control is found, returns the control, else returns null
function FindControl(control_name)
{    
    // TODO: Adicionar suporte para ffox
	for(var i=0; i < document.forms[0].elements.length; i++)
	{
		 current_id = document.forms[0].elements[i].id;
		 
		 if(current_id.indexOf(control_name) != -1)
			return document.forms[0].elements[i];
	}
	
	return null;
}

//Enables or disables an html text input depending on the text contents of another input
function EnableDisableOnEmptyText(text_holder, target_enabled)
{    
    el_holder = FindControl(text_holder);
    el_target = FindControl(target_enabled);
    
    if(el_holder.value == '')
    {        
        el_target.disabled = true; 
        el_target.value = '';
        el_target.className = 'txtBoxDisabled';
    }
    else
    {
        el_target.disabled = false;
        el_target.className = 'txtBox';
    }
}

//Esconde ou amostra todos os Selects da pagina
function HideShowSelects(status)
{
    var elems = document.getElementsByTagName("SELECT");
    var n_elems = elems.length;
    for (i = 0; i < n_elems; i++)
    {
        if(elems[i].name.indexOf("pais_ddl") == -1)
            elems[i].style.display=status;
     }
}

// Selecciona Tab e mostra conteúdo repectivo
var tabActual="";
function mostraTabConteudo(tabId, variacao, last) {
	if (variacao == null){
		variacao = "";
	}
	
	if (last == null){
		last = 6;
	}
	nomeTab=findObj(tabId);
	nomeTabAnterior=findObj(tabActual);
	// Desselecciona Tab anterior
	if (tabActual!="") {
		nomeTabAnterior.className='tabNaoSeleccionado'+variacao;
		// esconde conteúdo anterior
		contTabAnterior=findObj(tabActual+'Cont');
		contTabAnterior.style.display='none';
	}
	// Selecciona Tab actual
	nomeTab.className='tabSeleccionado'+variacao;
	// mostra conteúdo actual
	contTabActual=findObj(tabId+'Cont');
	contTabActual.style.display='';
	tabActual=tabId;
	// muda cor da primeira TD
	if (tabId=='tab1') {
		if (variacao == "Brown"){
			findObj('tab0').style.backgroundColor='#B98456';
		} else {
			findObj('tab0').style.backgroundColor='#198CD9';
		}
	} else {
		if (variacao == "Brown"){
			findObj('tab0').style.backgroundColor='#F1E8C0';
		} else {
			findObj('tab0').style.backgroundColor='#B6D8F9';
		}
	}
	
	try{
		if (tabId=='tab'+(last-1)) {
			if (variacao == "Brown"){
				findObj('tab'+last).style.backgroundColor='#B98456';
			} else {
				findObj('tab'+last).style.backgroundColor='#198CD9';
			}
		} else {
			if (variacao == "Brown"){
				findObj('tab'+last).style.backgroundColor='#F1E8C0';
			} else {
				findObj('tab'+last).style.backgroundColor='#B6D8F9';
			}
		}
	} catch (e){}
}
// Mostra/Esconde Sublinks dos Tabs
var sublinkActual="";
function sublinkShow(sublinkId) {
	sublinkNome=findObj(sublinkId);
	sublinkAnterior=findObj(sublinkActual);
	if (sublinkActual!="") {
	sublinkAnterior.className='txtBlackSub';
	contSubAnterior=findObj(sublinkActual+'Cont');
	contSubAnterior.style.display='none';
	}
	sublinkNome.className='txtBlackSubOn';
	contSubActual=findObj(sublinkId+'Cont');
	contSubActual.style.display='';
	sublinkActual=sublinkId;
}

//Actualiza Informação na Span na area de Compras
function actualizaInfoNaSpan(controlo, idSpan, _valor)
{
    var quantidade = parseInt(controlo.value);
    var preco = parseFloat(_valor.replace(',','.'));
    if(isNaN(quantidade) || quantidade <= 0)
    {
        quantidade = 1;
        controlo.value = quantidade;
        
    }
       
    var valor = quantidade * preco;
    document.getElementById(idSpan).innerHTML = valor.toFixed(2);      
}

function ShowCreditPayment(idtable, valor)
{
    var controlo = FindControl('tipoCartao_ddl');
    var tabela = document.getElementById(idtable);
    
    if(valor == 0)
        tabela.style.display='';
    else
       tabela.style.display='none';
}

//Actualiza os radios buttons apenas para o registo premium
function actualizaRadios(id)
{
    var controlo = id;
    
    if(id.indexOf("ctl0_radio") > -1)
    {
        controlo = controlo.replace("ctl0_radio","ctl1_radio");
        document.getElementById(controlo).checked = false;
        controlo = controlo.replace("ctl1_radio","ctl2_radio");
        document.getElementById(controlo).checked = false;
    }
    if(id.indexOf("ctl1_radio") > -1)
    {
        controlo = controlo.replace("ctl1_radio","ctl0_radio");
        document.getElementById(controlo).checked = false;
        controlo = controlo.replace("ctl0_radio","ctl2_radio");
        document.getElementById(controlo).checked = false;
    }
    if(id.indexOf("ctl2_radio") > -1)
    {
        controlo = controlo.replace("ctl2_radio","ctl0_radio");
        document.getElementById(controlo).checked = false;
        controlo = controlo.replace("ctl0_radio","ctl1_radio");
        document.getElementById(controlo).checked = false;
    }
    
}

//funcao usada no registo cooporate para actualizar a modalidade
function modalidade(ddlist)
{
    if(ddlist.options)
    {
        document.getElementById("utilizadoresEscolhidos_span").innerHTML = ddlist.options[ddlist.selectedIndex].text+" &nbsp; utilizadores";
        document.getElementById("precoFinal_span").innerHTML = ddlist.value +" &euro;";
    }
    else
    {       
        document.getElementById("utilizadoresEscolhidos_span").innerHTML = ddlist + " &nbsp; utilizadores";
        document.getElementById("precoFinal_span").innerHTML = ddlist + " &euro;";
    }
}

var premiumEducational;
var primeiroAnoEducational;
var ambosEducational;
var ultimo = -1;

//funcao usada no registo Educational para actualizar a modalidade
function modalidadeEducational(ddlist, num)
{          
           
           var controlo1 = FindControl('modalidadePremium_ddl');
           var controlo2 = FindControl('modalidadePublicacao_ddl');
           var controlo3 = FindControl('modalidadeAmbas_ddl');
           
            var valor1 = parseInt(controlo1.options[controlo1.selectedIndex].text);
            var valor2 = parseInt(controlo2.options[controlo2.selectedIndex].text);
            var valor3 = parseInt(controlo3.options[controlo3.selectedIndex].text);
            
            if(isNaN(valor1))
                valor1 = 0;
            if(isNaN(valor2))
                valor2 = 0;
             if(isNaN(valor3))
                valor3 = 0;

           document.getElementById("utilizadoresEscolhidos_span").innerHTML = valor1+ valor2 + valor3;
           document.getElementById("precoFinal_span").innerHTML =  valor1+ valor2 + valor3;

            
}

//funcao usada para esconder ou mostrar a recuperação da password
function recuperarPassword2()
{

    var controlo = document.getElementById('recuperarPassword_div');
    var estado = controlo.style.display;
    
    if(estado == '')
    {
        controlo.style.display='none';
    }
    else
    {
        controlo.style.display='';
    }
}
//funcao usada para esconder ou mostrar a recuperação da password(apos recuperação com sucesso)
function recuperarPassword(bol)
{
    var controlo = document.getElementById('recuperarPassword_div');
    
    if(bol)
        controlo.style.display='';
    else
     controlo.style.display='none';
}

function OpenClosePatrocinador(id,imagem)
{
    var controlo = document.getElementById(id);
    var estado = controlo.style.display;
    
     if(estado == '')
     { 
        //imagem.src = imagem.src.replace("Open","Close");
        controlo.style.display='none';
        imagem.src = '../UI/imagens/btMaisPatrocinadores.gif';
    }
    else
    {
        imagem.src = imagem.src.replace("Close","Open");
        controlo.style.display='';
        imagem.src = '../UI/imagens/btMenosPatrocinadores.gif';
    }
}

function turnFontBold(control)
{    
    el = document.getElementById(control);      
    el.style.fontWeight = "bold";
}

function CheckNIF(sender, args)
{    
    nif = args.Value;
    sum = 0;
    check_digit = -1;

	for(i = 1; i <= 8; i++)
	{
	    sum += (nif.charAt(i-1) * 1) * (10 - i);
	}

	switch(11 - (sum % 11))
	{
	    case 10:
		case 11:
		{
		    check_digit = 0;
			break;
		}
		default:
		{
		    check_digit = (11 - (sum % 11));
			break;
		}
	}	    
			
    args.IsValid = (check_digit == (nif.charAt(nif.length-1) * 1));
}

function showHideObj(objID)
{
	try
	{
		var obj = findObj( objID );
		(obj.style.display=="")?(obj.style.display="none"):(obj.style.display="");
	}
	catch (e)
	{
	}			
}

var slideInterval='';
var divObj='';
var btSlider='';

// Função que abre/fecha o conteúdo de um módulo
function slider(divId,sliderBt) {
	//btSlider=document.(sliderBt);
	divObj=document.getElementById(divId);
	slideInterval=setInterval("slide()",10);
}
function slide() {
	if (estadoDiv=='fechado') {
		divObj.style.display='';
		if (divObj.clientHeight>=divObj.scrollHeight) {
			estadoDiv='aberto';
			//btSlider.src='images/btUp.gif';
			clearInterval(slideInterval);
		}
		else {
			divObj.style.height=divObj.clientHeight+22;
		}
	}
	else {
		if (divObj.clientHeight<=22) {
			estadoDiv='fechado';
			//btSlider.src='images/btDown.gif';
			clearInterval(slideInterval);
			divObj.style.display='none';
			
		}
		else {
			divObj.style.height=divObj.clientHeight-22;
		}
	}
}

function verificaCarrinho()
{
    if(document.getElementById('totalItems_span').innerHTML == "0")
     document.getElementById('compra1Container').style.display='none';
     else
     document.getElementById('compra1Container').style.display='';
}

/* Estrelas de votação */

function lightEstrelas(num, id)
{   
    for(i = 0; i <= num; i++)
    {
        el = document.getElementById(id + i);
        
        if(el.src.indexOf("Off.gif") > 0)
            el.src = el.src.substring(0, el.src.length - 7) + ".gif";
    }
}

function resetEstrelas(num, max, id)
{  
    for(i=max-1; i >= 0 ; i--)
    {   
        if(i > num-1)
        {
            el = document.getElementById(id + i);
            
            if(el.src.indexOf("Off.gif") == -1)
                el.src = el.src.substring(0, el.src.length - 4) + "Off.gif";
        }            
    }    
}


// actualiza a altura da iframe
function altura(nome) 
{
	idIf=MM_findObj(nome);
	
	if (nome=='mainIframe') 
	{
	    idIf.height=document.body.clientHeight-96;
	}
	else
	{
	    idIf.height=document.body.clientHeight-186;
	}
}

function loadFiles(nomeDiv, nomeHidden)
{
    var hiddenTxt = FindControl(nomeHidden);
    var div = document.getElementById(nomeDiv)
    splitString = hiddenTxt.value.split(";")
    
    div.innerHTML = '';
    
    for(var i=0; i < splitString.length; i++)
    {
        if(splitString[i] != '')
            div.innerHTML += '<div><span class="smallTxtBlack">'+splitString[i]+'</span><img style="cursor:pointer; z-index:1000" src="../../UI/imagens/btClose.gif"  onclick=\'alert("teste")\'   onmouseover=\'alert(top.focus());\'/></div>';
    }
    
    //alert(hiddenTxt);
}

function removeFile(fileName,nomeDiv, nomeHidden)
{
    alert('teste');
    var hiddenTxt = FindControl(nomeHidden);
    var splitString = hiddenTxt.value.split(';')
    var refreshedFiles = '';
    
     for(var i=0; i < splitString.length; i++)
    {
        if(splitString[i] != fileName)
            refreshedFiles += splitString[i]+';';
    }
    
    hiddenTxt.value = refreshedFiles;
    loadFiles(nomeDiv, nomeHidden);
}


function ShowHideRowRadioButton(id, estado)
{
    document.getElementById(id).style.display=estado;
}

function addBookmark(url, title) {
        if (window.sidebar) { // firefox
              window.sidebar.addPanel(title, url,"");
        } else if( document.all ) { //MSIE
                window.external.AddFavorite( url, title);
        } else {
               alert("Lamentamos, mas o seu browser não suporta esta funcionalidade.");
        }
}

function showHideRoundTab(tabToSelect)
{    
    if(tabToSelect != selectedTab)
    {  
        ShowHideDiv(tabToSelect, "");
        ShowHideDiv(selectedTab, "none");
     
        tab_new = document.getElementById(tabToSelect + "Head");
        tab_new.className = "roundTabSeleccionado";
     
        tab_old = document.getElementById(selectedTab + "Head");
        tab_old.className = "roundTabNaoSeleccionado";
     
        selectedTab = tabToSelect;
    }
}

function showHideSubRoundTab(subTabToSelect)
{    
    if(subTabToSelect != selectedSubTab)
    {  
        ShowHideDiv(subTabToSelect, "");
        ShowHideDiv(selectedSubTab, "none");
     
        tab_new = document.getElementById(subTabToSelect + "Head");
        tab_new.className = "subListSeleccionado";
     
        tab_old = document.getElementById(selectedSubTab + "Head");
        tab_old.className = "subListNaoSeleccionado";
     
        selectedSubTab = subTabToSelect;
    }
}

