$(document).ready(function() {
  $('.frame_anterior, .frame_historico').hide();
  $.ajax({
    type: 'GET',
    url: '../js/data/news.json',
    dataType: 'text',
    success: function( response, textStatus ) {

      var data = eval( '('+response+')' );

      //if ( console != undefined ) console.debug( data );
      //return;
      var div = $('#lista_news');
      div.empty();
	  var select_ant = $('#content .frame_historico select.anos');
	  select_ant.attr('length', 0);

      var array_anos = []
	  for ( var ano in data ) array_anos.push( ano );
	  array_anos.sort(function(a, b) { return b - a; });
	  var array_anos_ant = array_anos.slice( 1 );

      var ultimoAno = null;
      var anosListaCount = 1; // Quantos anos serão diretamente impressos na lista
      for ( var chave in array_anos ) {
		var ano = array_anos[chave];
        if ( ultimoAno === null ) ultimoAno = ano;
        else anosListaCount -= 1;
        var ul = $.create('ul', {'class': 'hist_edi ano_'+ano});
        if ( anosListaCount < 0 ) ul.hide();
        for ( var k in data[ano] ) {
          var fn_opennews = function(noticia, ul_hist, ano_ed) {
            ul_hist.append( $.create('li')
              .append( $.create('p', {'class': 'data'}, noticia.mes+'/'+ano_ed) )
              .append( $.create('p', {'class': 'titulo'}, '| ' )
                .append( $.create('a', {'href': noticia.link, 'title': noticia.titulo}, noticia.titulo )
                  .bind( 'click', function() {
                    $('#content .frame_historico').hide();
          				  $('#content .frame_anterior').show()
            					.find('iframe').eq(0).attr('src', this.href).end().end()
            					.find('.data-edicao').text(noticia.mes+'/'+ano_ed);
                    return false;
                  } )
                )
              )
            );
          }
          fn_opennews( data[ano][k], ul, ano );
        }
        if ( ano != ultimoAno ) {
		  var tit = $.create('h4', {'class': 'tit_anterior ano_'+ano}, ano);
		  if ( anosListaCount < 0 ) tit.hide();
          div.append( tit );
		  select_ant.append( $.create('option', {'value': ano}, ano) );
        }
        div.append( ul );
      }
	  if ( anosListaCount < 0 ) {
	  select_ant.bind('change', function(evt) {
		var val = $(this).val();
		div.children('ul.hist_edi h4.tit_anterior').not('ul.ano_'+ultimoAno).hide()
		  .filter('h4.ano_'+val).show().end()
		  .filter('ul.ano_'+val).css('display', 'table');
	  } );
	  } else $('#content .frame_historico .mais_antigos').hide();

    },
    error: function ( xhr, textStatus, errorThrown ) {
      $('#lista_news').empty().append( $.create('p', {'class': 'erro'}, 'Erro ao buscar as notícias no servidor') );
      //if ( console != undefined ) console.debug( {xhr: xhr, stat: textStatus, exc: errorThrown} );
    }
  });

  $('#content .frame_anterior .voltar a').bind( 'click', function() {
    $('#content .frame_anterior').hide();
    $('#content .frame_historico').show();
  } );
});