﻿/***************************/
/*        PainelBOL        */
/***************************/

//substituir o alerta normal do 
if(document.getElementById) {
  window.alert = function(txt) {
    Painel('<div class="Alerta">'+txt+'</div>',null,1,null,null,'Prosseguir');
  }
}
$(window).resize(function() {
     $('.PainelFundo')
            .css('height',document.documentElement.scrollHeight)
            .css('width',document.documentElement.scrollWidth); 
     $('.PainelConteudo').center();
});

if (window!=window.top) {  window.top.location.href = window.location.href };

//Para que cada painel tenha um idUnico.
var numeroUnicoPainel = 0;

//Butoens: 1-Apenas fechar, 2-Cancelar,Ok
function Painel(conteudo,titulo, botoes,callbackFechar,callbackProsseguir,nomeBotaoFechar,nomeBotaoProsseguir)
{
    
    var numeroPainelCurrente = numeroUnicoPainel;
    //aumentamos o numero do painel usado
    numeroUnicoPainel++;
    var callbackInternoFechar = function()
                                {
                                    if (VerificarSeBrowserIE6())
                                        MostrarSelects(true);
                                        
                                    $('#PainelFundo'+numeroPainelCurrente).remove();
                                };
   
    //construimos o painel
    $(document.body).append('<div id=\'PainelFundo'+numeroPainelCurrente+'\' class=\'PainelFundo\' ></div>');
    $('#PainelFundo'+numeroPainelCurrente)
            .css('height',document.documentElement.scrollHeight)
            .css('width',document.documentElement.scrollWidth); 
    //Excepções ie6
    if (VerificarSeBrowserIE6())
    {
        MostrarSelects(false);
        $('#PainelFundo'+numeroPainelCurrente)
            .css('backgroundImage','url(/imagens/imagensDefault/internet/layout/Fundo_Prompt_IE6.gif)')
            .css('backgroundColor','transparent');
    } 
    
    //constroimos o conteudo
    $('#PainelFundo'+numeroPainelCurrente).append('<div id=\'PainelConteudo'+numeroPainelCurrente+'\'class=\'PainelConteudo\' ></div>');
    if (VerificarSeBrowserIE6())
    {
        $('#PainelConteudo'+numeroPainelCurrente)
            .css('top',document.documentElement.scrollTop)
            .css('position','absolute');
    }
    
    //construimos o titulo
    if(titulo==null)
        titulo = 'BilheteiraOnline';
    
    $('#PainelConteudo'+numeroPainelCurrente).append($('<h1>').text(titulo));
    
    var botaoFechar = $('<a>').addClass('Close').text('');
    
    if(callbackFechar!=null)
        botaoFechar.click(callbackFechar)
    
    botaoFechar.click(callbackInternoFechar);
    
    $('#PainelConteudo'+numeroPainelCurrente).append(botaoFechar);
    
    //Adicionamos o conteudo
    $('#PainelConteudo'+numeroPainelCurrente).append('<div id=\'PainelGeral'+numeroPainelCurrente+'\' class=\'PainelGeral\'></div>');
    $('#PainelGeral'+numeroPainelCurrente).append(conteudo);
    
    //Adicionamos os butoes
    $('#PainelConteudo'+numeroPainelCurrente).append('<div id=\'PainelBotoes'+numeroPainelCurrente+'\' class=\'PainelBotoes\'></div>');
    if(botoes == null || botoes == 1)
    {
        if(nomeBotaoFechar==null)
            nomeBotaoFechar = 'Fechar';
            
        //adicionamos o botao fechar
        $('#PainelBotoes'+numeroPainelCurrente).append('<a id=\'BtnFechar' + numeroPainelCurrente +'\'class=\'LinkBtnNormal\'>'+nomeBotaoFechar+' »</a>');

        if(callbackFechar!=null)
            $('#BtnFechar'+numeroPainelCurrente).click(callbackFechar);
        
        $('#BtnFechar'+numeroPainelCurrente).click(callbackInternoFechar);
        
        $('#BtnFechar'+numeroPainelCurrente).focus();
   }
   else if(botoes == 2)
   {
         if(nomeBotaoFechar==null)
            nomeBotaoFechar = 'Cancelar';
         if(nomeBotaoProsseguir==null) 
            nomeBotaoProsseguir = 'Prosseguir';
 
        $('#PainelBotoes'+numeroPainelCurrente).append('<a id=\'BtnFechar' + numeroPainelCurrente +'\'class=\'LinkBtnNormal\'>« '+nomeBotaoFechar+'</a>');
        
        $('#PainelBotoes'+numeroPainelCurrente).append('&nbsp;&nbsp;|&nbsp;&nbsp;');
        
        $('#PainelBotoes'+numeroPainelCurrente).append('<a id=\'BtnProsseguir' + numeroPainelCurrente +'\'class=\'LinkBtnNormal\'>'+nomeBotaoProsseguir+' »</a>');
                
        if(callbackFechar!=null)
            $('#BtnFechar'+numeroPainelCurrente).click(callbackFechar);
            
        if(callbackProsseguir!=null)
            $('#BtnProsseguir'+numeroPainelCurrente).click(callbackProsseguir);
        
          $('#PainelBotoes'+numeroPainelCurrente+' a').click(callbackInternoFechar);
    
   }
         
   return $('#PainelConteudo'+numeroPainelCurrente).center();                     
}

function ConfirmacaoLinkButton(txt, sender)
{
    var id = $(sender).attr('id');
    
    var callbackFunction = function(){window.location = $('#'+id).attr('href');};
        
    Painel(txt,null,2,null,callbackFunction);

    return false;
}

/***************************/
/*        COUNTDOWN        */
/***************************/

var _countDowncontainer=0;
var _currentSeconds=0;

function ActivateCountDown(initialValue) {
	
	SetCountdownText(initialValue);
	CountDownTick();
}

function CountDownTick() {
	if (_currentSeconds <= 0) {
        var frmToSubmit = document.getElementById("aspnetForm");
	    frmToSubmit.submit();
		return;
	}
	
	SetCountdownText(_currentSeconds-1);
	window.setTimeout("CountDownTick()", 1000);
}

function SetCountdownText(seconds) {
	//store:
	_currentSeconds = seconds;
	
	//get minutes:
	var minutes=parseInt(seconds/60);
	
	//shrink:
	seconds = (seconds%60);
	
	//shrink:
	minutes = (minutes%60);
	
	//build text:
	var strText = AddZero(minutes) + AddZero(seconds);

	//apply:
        $("#watch").html('')
                .append($('<span>').addClass("R-"+strText.substring(0,1)))
                .append($('<span>').addClass("R-"+strText.substring(1,2)))
                .append($('<span>').addClass("R-S"))
                .append($('<span>').addClass("R-"+strText.substring(2,3)))
                .append($('<span>').addClass("R-"+strText.substring(3,4)));
         
    
}

function AddZero(num) {
	return ((num >= 0)&&(num < 10))?"0"+num:num+"";
}
/***************************/
/*      FIM COUNTDOWN      */
/***************************/

//Plugin centar
jQuery.fn.center = function () {
        if(this!= null && this && this != 'undefined' && this.offset())
        {   
            //a cada elemento no objecto: i>index; e>elemento
            this.each(function(i,e){
                //Transformo num objecto jQuery
                e = $(this);
                
         
                //Os calculos não correm bem com o objecto escondido por isso guardo o estado correcte e no final reverto-o;
                var d = e.css("display");
                e.css("display","block");
                //Vou buscar a distância ao topo actual
                var t = e.offset().top;
                //Se a distância actual for nula igualo-a a zero
                t = !t || t==null || t== 'undefined' || t=='' ? 0 : t;
                //Vou buscar a distância à esquerda actual
                var l = e.offset().left;
                //Se a distância actual for nula igualo-a a zero
                l = !l || l==null || l== 'undefined' || l=='' ? 0 : l;
                //Se o tamanho da janela for menor que o elemento que quero centrar e
                //a distância do scrool ao top for menor que a distancia do elemento ao topo ou se a distancia do elemento ao topo for zero 
                if($(window).height()<e.height() && ($(window).scrollTop()< t || t ==0))
                    //assim quando fazemos scroll para cima o elemento acompanha mas quando fazemos para baixo não acompanha.
                    //não pode acompanhar devido ao facto do elemento ser maior que a janela.
                    t =  $(window).scrollTop();
                    //senão se a altura da janela for maior que a altura do elemento
                else if($(window).height()>e.height())
                    //centramos o elemento verticalmente
                    t = ($(window).height() - e.height() ) / 2+$(window).scrollTop();

                //Mesma coisa para o alinhamento horizontal
                if($(window).width()<=e.width() && ($(window).scrollLeft()< l || l ==0))
                    l =  $(window).scrollLeft();
                else if($(window).width()>e.width())
                    l = ($(window).width() - e.width() ) / 2+$(window).scrollLeft();
                
                //Depois dos calculos associar ao elemento os valores e reverto a propriedade "display" (Nesta ordem!)
                e.offset({top:t, left: l});              
            });    
       }
       //Como em todas as funções jQuery devolvo o objecto trabalhado para outras funções trabalharem nele
       return this;
    };



function VerificarSeBrowserIE6()
{
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))
    { //test for MSIE x.x;
        var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
        if (ieversion<7)
            return true;
     }
     return false;
}

function MostrarSelects(mostrar)
{
    if (VerificarSeBrowserIE6())
    {
        var x = document.getElementsByTagName("select");

        for (i = 0; i < x.length; i++) 
        {
            if(mostrar)
                x[i].style.display = "";
            else
                x[i].style.display = "none";
        }
    }
}

/***************************/
/*     SCRIPTSGERAIS       */
/***************************/
function findPosX(obj)
{
    var curleft = 0;
    
    if(obj.offsetParent)
        while(1) 
        {
            curleft += obj.offsetLeft;
            if(!obj.offsetParent)
                break;
            obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;

    return curleft;
}

function findPosY(obj)
{
    var curtop = 0;
    
    if(obj.offsetParent)
        while(1)
        {
            curtop += obj.offsetTop;
            if(!obj.offsetParent)
                break;
            obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    
    return curtop;
}


/**Validações**/
function ValidarCartaoCidadao(sender, args){
    
    if(args.Value.length != 12)
    {
        args.IsValid = false;
        return args.IsValid;
    }
    var conversor = function(l){switch (l){
                case '0': return 0;
                case '1': return 1;
                case '2': return 2;
                case '3': return 3;
                case '4': return 4;
                case '5': return 5;
                case '6': return 6;
                case '7': return 7;
                case '8': return 8;
                case '9': return 9;
                case 'A': return 10;
                case 'B': return 11;
                case 'C': return 12;
                case 'D': return 13;
                case 'E': return 14;
                case 'F': return 15;
                case 'G': return 16;
                case 'H': return 17;
                case 'I': return 18;
                case 'J': return 19;
                case 'K': return 20;
                case 'L': return 21;
                case 'M': return 22;
                case 'N': return 23;
                case 'O': return 24;
                case 'P': return 25;
                case 'Q': return 26;
                case 'R': return 27;
                case 'S': return 28;
                case 'T': return 29;
                case 'U': return 30;
                case 'V': return 31;
                case 'W': return 32;
                case 'X': return 33;
                case 'Y': return 34;
                case 'Z': return 35;
                default: return -9; }};
                
    var sum = 0;
    var secondDigit = false;
    for (var i = args.Value.length - 1; i >= 0; --i)
    {
        var valor = conversor(args.Value[i].toUpperCase());
        if (valor == -9)
        {
            args.IsValid = false;
            return args.IsValid;
        }

        if (secondDigit)
        {
            valor *= 2;
            if (valor > 9)
            {
                valor -= 9;
            }
        }

        sum += valor;
        secondDigit = !secondDigit;
    }

    args.IsValid = (sum % 10) == 0;
    return args.IsValid;
    
}
