var notic_total_links;

function abrePopup(foto, titulo) {
  
  window.open('foto.htm?'+foto, '', 'width=100, height=100, status=no');
}

/*
    SUBMITIMAGE
    INLCUI UMA IMAGEM EM UMA GALERIA
*/
function submitImage ( acao )
{
    // REMOVE O ELEMENTO DE "SEM IMAGENS"
    teste = document.getElementById('caixas').innerHTML ;
    indice = teste.indexOf('Nenhuma imagem localizada', 0) ;
    if ( indice > 0 )
    {
        registro = document.getElementById('sem_registros') ;
        document.getElementById('caixas').removeChild(registro) ;
    }    
    //CRIA E INSERE O NOVO ELEMENTO PARA ABRIGAR O THUMB
    newLi      = document.createElement( 'li' ) ;
    newBot     = document.createElement( 'div' ) ;
    newAmpliar = document.createElement( 'a' ) ;
    newRemover = document.createElement( 'a' ) ;
    newFoto    = document.createElement( 'div' ) ;
    
    //CONTA A QUANTIDADE NÓS
    comp = document.getElementById('caixas').childNodes.length;
    var nos = 0;
    for ( i=0; i < comp; i++ )
    {
        var child = document.getElementById('caixas').childNodes[i];
        if (child.nodeType === 1) {
            nos ++;
        }
    }
    no = nos + 1;
    
    newLi.setAttribute( 'id', 'li'+no ) ;
    newFoto.setAttribute( 'id', 'foto'+no ) ;
    
    newBot.setAttribute( 'id', 'botao'+no ) ;
    newBot.setAttribute( 'class', 'bot' ) ;
    newBot.className = 'bot' ;
    
    newAmpliar.setAttribute( 'href', 'javascript:void(0);' ) ;
    newAmpliar.setAttribute( 'class', 'link_galer' ) ;
    newAmpliar.className = 'link_galer' ;
    
    newAmpliar.appendChild( document.createTextNode( 'ampliar' ) ) ;
    newBot.appendChild( newAmpliar ) ;
    newBot.appendChild( document.createTextNode(' | ') ) ;
    newRemover.setAttribute( 'href', 'javascript:void(0);' ) ;
    newRemover.setAttribute( 'class', 'link_galer' ) ;
    newRemover.className = 'link_galer' ;
    newRemover.appendChild( document.createTextNode( 'remover' ) ) ;
    newBot.appendChild( newRemover ) ;
    newLi.appendChild( newBot ) ;
    newLi.appendChild( newFoto ) ;
    
    teste = document.getElementById( 'caixas' ).insertBefore( newLi, null ) ;
    
    //SETA OS VALORES PARA OS INPUTS E AJUSTA O TARGET E ACTION DO FORM PARA SUBMITAR PARA O IFRAME
    document.f1.action     = '_ajax_imagens.php' ;
    document.f1.target     = 'upImagens' ;
    document.f1.acao.value = 'carregar' ;
    
    //DESABILITA OS BOTOES E INPUTS QUE NÃO PODEM SER CLICADOS ENQUANTO O UPLOAD NÃO FOR CONCLUÍDO
    document.getElementById( 'bot_cancelar' ).disabled = 'true';
    document.getElementById( 'bot_reset' ).disabled = 'true';
    document.getElementById( 'bot_salvar' ).disabled = 'true';
    
    //SUBMITA OS DADOS E DESABILITA O INPUT DA IMAGEM
    document.f1.submit ( ) ;
    document.getElementById('galer_imagem').disabled = true;
}

function retImagem ( id_imagem, id_galeria, status )
{
    
    //CONTA A QUANTIDADE NÓS
    comp = parent.document.getElementById('caixas').childNodes.length;
    var nos = 0;
    for ( i=0; i < comp; i++ )
    {
        var child = parent.document.getElementById('caixas').childNodes[i];
        if (child.nodeType === 1) {
            nos ++;
        }
    }
    
    if ( status !== 'carregado' )
    {
        //REMOVE O ELEMENTO TEMPORÁRIO CRIADO PARA ABRIGAR O THUMB
        lista = parent.document.getElementById( 'li'+nos ) ;
        lista.parentNode.removeChild(lista) ;
        
        //SETA OS VALORES PARA OS INPUTS E REAJUSTA O TARGET E ACTION DO FORM
        parent.document.f1.action = 'adm_galerias.php' ;
        parent.document.f1.target = '_self' ;
        parent.document.f1.galer_tmp_id.value = id_galeria ;
        
        //HABILITA NOVAMENTE OS BOTOES E INPUTS
        parent.document.getElementById('bot_cancelar').disabled = false;
        parent.document.getElementById('bot_reset').disabled = false;
        parent.document.getElementById('bot_salvar').disabled = false;
        parent.document.getElementById('galer_imagem').disabled = false;
    }
    else
    {
        //CARREGA PARA UMA VARIÁVEL O ELEMENTO TEMPORÁRIO CRIADO PRA ABRIGAR O THUMB
        lista = parent.document.getElementById( 'li'+nos ) ;
        foto  = lista.childNodes[1] ;
        
        //CRIA OS ELEMENTOS QUE FALTAVAM DENTRO DO ELEMENTO QUE ABRIGA O THUMB
        lista.childNodes[0].innerHTML = '<a href="javascript:void(0);" onclick="javascript:abrePopup(\'../galer/' + id_galeria + '/grande_' + id_imagem + '.jpg\');" class="link_galer">ampliar</a> | <a href="javascript:void(0);" onclick="excImagem( ' + id_imagem + ', ' + id_galeria + ', '+ nos +' )" class="link_galer">remover</a>' ; 
        
        lista.setAttribute ( 'id', 'li'+nos ) ;
        ldFoto = parent.document.createElement( 'img' ) ;
        
        ldFoto.setAttribute( 'src', '../galer/'+ id_galeria +'/thumb_'+ id_imagem +'.jpg' ) ;
        ldFoto.setAttribute( 'alt', '' ) ;
        foto.appendChild( ldFoto ) ;
        
        //SETA OS VALORES PARA OS INPUTS E REAJUSTA O TARGET E ACTION DO FORM
        parent.document.f1.galer_tmp_id.value = id_galeria ;
        parent.document.f1.galer_ult_imagem.value = id_imagem ;
        parent.document.f1.action = 'adm_galerias.php' ;
        parent.document.f1.target = '_self' ;
        
        //HABILITA NOVAMENTE OS BOTOES E INPUTS
        parent.document.getElementById('bot_cancelar').disabled = false;
        parent.document.getElementById('bot_reset').disabled = false;
        parent.document.getElementById('bot_salvar').disabled = false;
        parent.document.getElementById('galer_imagem').disabled = false;
    }
}


/*
    EXCIMAGEM
    EXCLUI UMA IMAGEM DE UMA GALERIA
*/
function excImagem ( imagem_id, galer_id, no_id )
{
    poststr  = 'gimag_id='+ escape(encodeURI( imagem_id ));
    poststr += '&acao=excluir';
    poststr += '&galer_id='+ escape(encodeURI( galer_id ));;
    
    loadXMLPOST( '_ajax_imagens.php', poststr );
    
    req.onreadystatechange = function() 
    {
        // SE A REQUISIÇÃO FOI FINALIZADA
        if ( req.readyState == 4 )
        {
            // SE O SERVIDOR RETORNOU "OK"
            if ( req.status == 200 )
            {
                boxes = parent.document.getElementById( 'caixas' );
                lista = document.getElementById( 'li'+no_id );
                boxes.removeChild( lista );
                document.getElementById('bot_cancelar').disabled = false;
                document.getElementById('bot_reset').disabled = false;
                document.getElementById('bot_salvar').disabled = false;
            }
        }
        else
        {
            document.getElementById('bot_cancelar').disabled = true;
            document.getElementById('bot_reset').disabled = true;
            document.getElementById('bot_salvar').disabled = true;
        }
    }
}

function ordGalerias( id, pagina, acao, ativa)
{
    filtroAtiva = document.getElementById('galer_ativa').value;
    alertOrdenar(filtroAtiva);
    
    
    loadXML('_ajax_ordemGaler.php?'+id+'&'+pagina+'&'+acao+'&', ativa );
    
    req.onreadystatechange = function() 
    {
        // SE A REQUISIÇÃO FOI FINALIZADA
        if ( req.readyState == 4 )
        {
            // SE O SERVIDOR RETORNOU "OK"
            if ( req.status == 200 )
            {
                if ( req.responseText != 'erro' )
                {
                    // REMOVE O TBODY INTEIRO
                    tabela = document.getElementById ( 'tab_galerias' );
                    tbody = document.getElementById ( 'tbody_galerias' );
                    tabela.removeChild ( tbody );
                    
                    // CRIA UM NOVO TBODY
                    tbody = document.createElement ( 'tbody' );
                    tbody.setAttribute ( 'id', 'tbody_galerias' );
                    
                    // QUEBRA A RESPOSTA PARA MONTAR O HTML
                    ret = req.responseText.split( "</tr><tr>" )
                    
                    // FAZ O LOOP PELAS LINHAS DA TABELA
                    for ( i = 0; i < ret.length; i++ )
                    {
                        classLinha = 'tab_linha' + ( 1 + i%2 );
                        tr = document.createElement ( 'tr' );
                        
                        tr.setAttribute ( 'class', classLinha );
                        tr.className = classLinha;
                        tr.setAttribute ( 'onmouseover', "className='tab_linha_over'" );
                        tr.setAttribute ( 'onmouseout', "className='"+classLinha+"'" );
                        
                        td1 = document.createElement ( 'td' );
                        td2 = document.createElement ( 'td' );
                        td3 = document.createElement ( 'td' );
                        
                        linha = ret[i].split ( "[[quebra]]" );
                        
                        td1.onMouseOver = td1.style.cursor = 'pointer';
                        td1.onClick = "document.location.href='adm_galerias.php?" + linha[1] + "&amp;alt'";
                        td1.setAttribute ( 'onmouseover', 'style.cursor="pointer"' );
                        td1.setAttribute ( 'onclick', "document.location.href='adm_galerias.php?" + linha[1] + "&amp;alt'" );
                        td1.setAttribute ( 'class', 'tab_texto tab_borda' + linha[2] )
                        td1.className = 'tab_texto tab_borda' + linha [2];
                        td1.innerHTML = linha[0];
                        
                        td2.setAttribute ( 'align', 'center' );
                        td2.setAttribute ( 'class', 'tab_texto tab_borda' );
                        td2.className = 'tab_texto tab_borda';
                        td2.innerHTML = '<span class="bot_link_altera"><a href="adm_galerias.php?' + linha[1] + '&amp;alt" class="link1">Alterar</a></span>\
                                    <span class="bot_link_exclui"><a href="adm_galerias.php?' + linha[1] + '&amp;exc" class="link1">Excluir</a></span>\
                                    <span class="bot_link_conteudo"><a href="view_galerias.php?' + linha[1] + '&amp;show" class="link1">Ver</a></span>';
                        
                        td3.setAttribute ( 'class', 'tab_texto tab_borda' );
                        td3.className = 'tab_texto tab_borda';
                        td3.setAttribute ( 'align', 'center' );
                        td3.innerHTML = '<span class="bot_link_sobe"><a href="javascript:void(0);" onclick="ordGalerias( ' + linha[1] + ', ' + linha[4] + ', \'subir\', \'' + linha[3] + '\' );" class="link1">Subir</a></span>\
                                    <span class="bot_link_desce"><a href="javascript:void(0);" onclick="ordGalerias( ' + linha[1] + ', ' + linha[4] + ', \'descer\', \'' + linha[3] + '\' );" class="link1">Descer</a></span>';
                        
                        tr.appendChild ( td1 );
                        tr.appendChild ( td2 );
                        tr.appendChild ( td3 );
                        
                        tbody.appendChild ( tr );
                    }
                    
                    tabela.appendChild ( tbody );
                }
            }
        }
    }
}

function alertOrdenar ( filtro )
{
    if ( filtro == 0 )
        alert ( 'As galerias ativas serão incluídas na ordenação.\nPara vizualizar a ordenação corretamente, altere o filtro "Ativa/Inativa" para "Ambas".' );
    else if ( filtro == 1 )
        alert ( 'As galerias inativas serão incluídas na ordenação.\nPara vizualizar a ordenação corretamente, altere o filtro "Ativa/Inativa" para "Ambas".' );
}

function changeCampoBusca ()
{
    var tipo_busca = document.getElementById('tipo_busca')
    var busca = document.getElementById('busca')
    if ( tipo_busca.value=='fone' )
    {
        busca.maxLength=14
        busca.value=busca.value.substring(0,14)
    }
    else busca.maxLength=255
}

function add_link ( )
{
    notic_total_links++;
    elDiv = document.getElementById('div_links');
	nDiv = document.createElement( 'div' );
	nDiv.setAttribute( 'class', 'label' );
	nDiv.className = 'label';
	nDiv.innerHTML = '<label class="label4" for="nlink_nome'+notic_total_links+'">Nome: <input type="text" name="nlink_nome[]" id="nlink_nome'+notic_total_links+'" value="" size="25" maxlength="100" class="input" onfocus="this.className=\'input_over\'" onblur="this.className=\'input\'" /></label>\
	                  <label class="label4" for="nlink_url'+notic_total_links+'">Link:  <input type="text" name="nlink_url[]" id="nlink_url'+notic_total_links+'" value="http://" size="50" maxlength="100" class="input" onfocus="this.className=\'input_over\'" onblur="this.className=\'input\'" /></label>';
    elDiv.appendChild( nDiv );
}

function CPFouCNPJ (tipo)
{
    radioCPF = document.getElementById('tipo_cpf');
    radioCNPJ = document.getElementById('tipo_cnpj');
    textCPF = document.getElementById('clien_cpf');
    textCNPJ = document.getElementById('clien_cnpj');
    
    if ( tipo == 'cpf' )
    {
        textCPF.disabled = false;
        textCNPJ.disabled = true;
        textCPF.style.display = '';
        textCNPJ.style.display = 'none';
    }
    if ( tipo == 'cnpj' )
    {
        textCPF.disabled = true;
        textCNPJ.disabled = false;
        textCPF.style.display = 'none';
        textCNPJ.style.display = '';
    }
}

function navegaData (mes,ano)
{
    document.getElementById('oturn_mes').value=mes;
    document.getElementById('oturn_ano').value=ano;
    document.filtros.submit();
}

function SubmitDatas ( dataIni, dataFim )
{
    if ( ! ( VerificaData ( dataIni ) && VerificaData ( dataFim ) ) )
    {
        alert ( "Preencha as datas inicial e final" );
        return false;
    }
    else if ( ! ComparaData ( dataIni, dataFim ) )
    {
        alert ( "Data final deve ser igual ou posterior a data inicial" );
        return false;
    }
    else return true;
}

function ComparaData ( dataIni, dataFim )
{
    var dia_ini = dataIni.substr (0,2)
    var mes_ini = dataIni.substr (3,2)
    var ano_ini = dataIni.substr (6,4)
    
    var dia_fim = dataFim.substr (0,2)
    var mes_fim = dataFim.substr (3,2)
    var ano_fim = dataFim.substr (6,4)
    
    if ( ano_fim < ano_ini )
        return false;
    else if ( ( ano_fim == ano_ini ) && ( mes_fim < mes_ini ) )
        return false;
    else if ( ( ano_fim == ano_ini ) && ( mes_fim == mes_ini ) && ( dia_fim < dia_ini ) )
        return false;
    else return true;
    
}

function VerificaData(cData) {
    var data = cData;
    var tam = data.length;
    
    if (tam != 10) {
        return false;
    }
    
    var dia = data.substr (0,2)
    var mes = data.substr (3,2)
    var ano = data.substr (6,4)
    
    
    if (ano < 1980)    {
        return false;
    }
    
    if (ano > 2010)    {
        return false;
    }

    switch (mes) {
        case '01':
            if  (dia <= 31)
                return (true);
        break;
        case '02':
            if  (dia <= 29)
                return (true);
        break;
        case '03':
            if  (dia <= 31)
                return (true);
        break;
        case '04':
            if  (dia <= 30)
                return (true);
        break;
        case '05':
            if  (dia <= 31)
        return (true);
        break;
        case '06':
            if  (dia <= 30)
                return (true);
        break;
        case '07':
            if  (dia <= 31)
                return (true);
        break;
        case '08':
            if  (dia <= 31)
                return (true);
        break;
        case '09':
            if  (dia <= 30)
                return (true);
        break;
        case '10':
            if  (dia <= 31)
                return (true);
        break;
        case '11':
            if  (dia <= 30)
                return (true);
        break;
        case '12':
            if  (dia <= 31)
                return (true);
        break;
        default:
            return (false);
    }
    return true;
}

function carregaArquivo ( )
{
    botaoSubmit = parent.document.getElementById ( 'btn_submit' );

    botaoSubmit.value = 'Carregando...';
    botaoSubmit.disabled = true;
    
    document.f1.submit ( );
}

/*
    Função que dá o retorno do carregamento de arquivos
*/
function retCarregaArquivo ( status )
{
    if ( status == 'ok' )
    {
        mensagem = 'Dados carregados com sucesso!';
        alert ( mensagem );
        
        parent.reload(true);
    }
    else
    {
        botaoSubmit = parent.document.getElementById ( 'btn_submit' );
        
        botaoSubmit.value = 'Importar';
        botaoSubmit.disabled = false;
        
        mensagem = "Erro ao importar o arquivo";
        alert ( mensagem );
        
        parent.reload(true);
    }
}

/* Mascaras */
formataCampo = function ( tecla, obj, tipo ) {
  var key;
  var keyNum;
  if ( navigator.userAgent.indexOf( "MSIE" ) > 0 ) key = tecla.keyCode;
  if ( navigator.userAgent.indexOf( "Gecko" ) > 0 ) key = tecla.which;
  if ( ( key == 8 ) || ( key == 0 ) ) return true;
  keyNum = key;
  key = String.fromCharCode(key);
  
  if ( tipo == 'numero' )
    var erNum = /[0-9\,]/i;
  else
    var erNum = /[0-9]/i;

  if (erNum.test(key)) {
    /**** NÚMERO ****/
    if (tipo == 'numero') {
      if ( key == "," )
      {
        if ( strpos ( obj.value, ',') !== false )
          return false;
        else
          return true;
      }
      return true; }
      
    /**** CEP ****/
    if (tipo == 'cep') {
      if (obj.value.length == 4) { obj.value = obj.value + key + '-'; return false; }
      else return true;

    /**** CPF ****/
    } else if (tipo == 'cpf') {
      if ((obj.value.length == 2) || (obj.value.length == 6)) { obj.value = obj.value + key + '.'; return false; }
      else if (obj.value.length == 10) { obj.value = obj.value + key + '-'; return false; }
      else if (obj.value.length > 13) { return false }
      else return true;

    /**** Fone ****/
    } else if (tipo == 'fone') {
      if ((obj.value.length == 0)) { obj.value = '(' + key ; return false; }
      else if (obj.value.length == 2) { obj.value = obj.value + key + ') '; return false; }
      else if (obj.value.length == 8) { obj.value = obj.value + key + '-'; return false; }
      else return true;

    /**** CNPJ ****/
    } else if (tipo == 'cnpj') {
      if ((obj.value.length == 1) || (obj.value.length == 5)) { obj.value = obj.value + key + '.'; return false; }
      else if (obj.value.length == 9) { obj.value = obj.value + key + '/'; return false; }
      else if (obj.value.length == 14) { obj.value = obj.value + key + '-'; return false; }
      else return true;

    /**** MOEDA ****/
    } else if (tipo == 'moeda') {
        
        objTextBox = obj ;
        SeparadorMilesimo = '' ;
        SeparadorDecimal = '.' ;
        e = tecla ;
            //-----------------------------------------------------
            //Funcao: MascaraMoeda
            //Autor: Gabriel Fróes
            //-----------------------------------------------------
            var sep = 0;
            var key = '';
            var i = j = 0;
            var len = len2 = 0;
            var strCheck = '0123456789';
            var aux = aux2 = '';
            var whichCode = (window.Event) ? e.which : e.keyCode;
            if (whichCode == 13) return true;
            key = String.fromCharCode(whichCode); // Valor para o código da Chave
            if (strCheck.indexOf(key) == -1) return false; // Chave inválida
            len = objTextBox.value.length;
            for(i = 0; i < len; i++)
                if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
            aux = '';
            for(; i < len; i++)
                if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
            aux += key;
            len = aux.length;
            if (len == 0) objTextBox.value = '';
            if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
            if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;
            if (len > 2) {
                aux2 = '';
                for (j = 0, i = len - 3; i >= 0; i--) {
                    if (j == 3) {
                        aux2 += SeparadorMilesimo;
                        j = 0;
                    }
                    aux2 += aux.charAt(i);
                    j++;
                }
                objTextBox.value = '';
                len2 = aux2.length;
                for (i = len2 - 1; i >= 0; i--)
                objTextBox.value += aux2.charAt(i);
                objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
            }
            return false;        
        
    /**** DATA ****/
    } else if (tipo == 'data') {
      if ((obj.value.length == 1) || (obj.value.length == 4)) { obj.value = obj.value + key + '/'; return false; }
      else return true;

    /**** HORA ****/
    } else if (tipo == 'hora') {
      if (obj.value.length == 1) { obj.value = obj.value + key + ':'; return false; }
      else return true;

    } else { return false; }
  } else if ( keyNum == 13 ) {
    return true;
  }
  else return false;
}
/*
    LOADXML
    INSTANCIA O OBJETO XML E ENVIA AS VARIÁVEIS
*/
function loadXML ( url, valor )
{
    req = null;
    
    // PROCURA POR UM OBJETO NATIVO (MOZILLA/SAFARI)
    if ( window.XMLHttpRequest )
    {
        req = new XMLHttpRequest();
        req.open("GET", url+escape(valor), true);
        req.send(null);
    }
    // PROCURA POR UMA VERSAO ACTIVEX (IE)
    else if ( window.ActiveXObject )
    {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if ( req )
        {
            req.open("GET", url+escape(valor), true);
            req.send();
        }
    }
}

function loadXMLPOST ( url, param )
{
    req = null;
    // PROCURA POR UM OBJETO NATIVO (MOZILLA/SAFARI)
    if ( window.XMLHttpRequest )
        req = new XMLHttpRequest();
    // PROCURA POR UMA VERSAO ACTIVEX (IE)
    else if ( window.ActiveXObject )
        req = new ActiveXObject("Microsoft.XMLHTTP");
    else
        alert( 'Seu browser não suporta AJAX! Está página não funcionará corretamente.' )
    
    req.open('POST', url, true);
    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    req.setRequestHeader("Content-length", param.length);
    req.setRequestHeader("Connection", "close");
    req.send(param);
}
function strpos( haystack, needle, offset){
    // http://kevin.vanzonneveld.net
    // *     example 1: strpos('Kevin van Zonneveld', 'e', 5);
    // *     returns 1: 14
 
    var i = haystack.indexOf( needle, offset ); // returns -1
    return i >= 0 ? i : false;
}
