//window.onerror = function(){return true;}

$(function () {
  $("#link_enviar").click(function () {
    $("#url").remove() 
    $('<input type="hidden" id="url"  value=""/>').val(window.location.href).appendTo(document.body)
    var winl = (screen.width)/2 - 400;
    var wint = (screen.height)/2 -188;
    window.open(URL_ENVIAR, 'wenviar', 'status=no, toolbar=no, menubar=no, personalbar=no, resizable=no, scrollbars=no, width=560, height=376, top='+wint+', left='+winl);
  });
  $("#link_corrigir").click(function () {
    $("#url").remove() 
    $('<input type="hidden" id="url"  value=""/>').val(window.location.href).appendTo(document.body)
    var winl = (screen.width)/2 - 230;
    var wint = (screen.height)/2 -290;
    window.open(URL_CORRIGIR, 'wenviar', 'status=no, toolbar=no, menubar=no, personalbar=no, resizable=no, scrollbars=no, width=560, height=290, top='+wint+', left='+winl);
  });
  $("#video_enviar").click(function () {
     $("#url").remove() 
    $('<input type="hidden" id="url"  value=""/>').val(window.location.href).appendTo(document.body)
    var winl = (screen.width)/2 - 230;
    var wint = (screen.height)/2 -188;
    window.open(URL_ENVIAR, 'wenviar', 'status=no, toolbar=no, menubar=no, personalbar=no, resizable=no, scrollbars=no, width=560, height=376, top='+wint+', left='+winl);
  });
  $("#galeria_enviar").click(function () {
     $("#url").remove() 
    $('<input type="hidden" id="url"  value=""/>').val(window.location.href).appendTo(document.body)
    var winl = (screen.width)/2 - 230;
    var wint = (screen.height)/2 -188;
    window.open(URL_ENVIAR, 'wenviar', 'status=no, toolbar=no, menubar=no, personalbar=no, resizable=no, scrollbars=no, width=560, height=376, top='+wint+', left='+winl);
  });
  $("#link_imprimir").click(function () { print() });
  
 // Reset Font Size
  var originalFontSize = $('.font_change').css('font-size');
  // Increase Font Size
  $("#link_font_up").click(function(){
  
	var tituloTexto = $('.news_heading .h1').css('font-size');
	var tituloTextoNum = parseFloat(tituloTexto, 10);
	var newtituloTexto = tituloTextoNum*1.2;
	if(newtituloTexto<52) {
		$('.news_heading .h1, .news_heading .h1 > *').css('font-size', newtituloTexto);
    }
	
    var currentFontSize = $('.font_change').css('font-size');
    var currentFontSizeNum = parseFloat(currentFontSize, 10);
    var newFontSize = currentFontSizeNum*1.2;
    if(newFontSize<25) {
		$('.font_change, .font_change > *').css('font-size', newFontSize);
    }
    
    });
  // Decrease Font Size
  $("#link_font_down").click(function(){
  
	/* diminui o título da matéria */ 
	var tituloTexto = $('.news_heading .h1').css('font-size');
	var tituloTextoNum = parseFloat(tituloTexto, 10);
	var newtituloTexto = tituloTextoNum*0.8;
	if(newtituloTexto>19) {
		$('.news_heading .h1, .news_heading .h1 > *').css('font-size', newtituloTexto);
    }
	
 
	/* diminui o corpo da matéria */ 
    var currentFontSize = $('.font_change').css('font-size');
    var currentFontSizeNum = parseFloat(currentFontSize, 10);
    var newFontSize = currentFontSizeNum*0.8;
     if(newFontSize>8) {
		$('.font_change, .font_change > *').css('font-size', newFontSize);
    }
  });

    
  var URL_LOGIN = BASEXJ + "da_wad/" + MODULO + "/autenticar";
  var URL_COMENTAR = BASEXJ + "da_wad/" + MODULO + "/comentar";
  var URL_VOTAR = BASEXJ + "da_wad/" + MODULO + "/votar";
  URL_LOGOFF = BASEXJ + "da_wad/" + MODULO + "/logoff";

  var ids = ['', '2'];

  $.each(ids, function () {
        var id = this   
        $("#login_submit" + id).click(function () {
            var self = $(this)
            var email = $.trim($("#login_email" + id).val())
            var password = $.trim($("#login_password" + id).val())
            $("#form_login_loading" + id).show()
            self.hide()
            if (email == '') {
                alert('Digite um Email.')
                $("#login_email" + id).focus();
                $("#login_submit").show();
                $('#form_login_loading').hide();
            }
            else {
                $.getJSON2Script(URL_LOGIN, {'e': email, 'senha': password},
                function (data) {
                    $("#form_login_loading" + id).hide()
                    if (data.type == 'ok') {
                        $("#comentario_nome").text(email);
                        $("#div_form_login" + id).hide();
                        $("#div_form_comentario" + id).show();
                        $("#login_submit").show();
                        if (id == '2') {
                            $('#login_dialog').dialog('close');
                            $($('#login_dialog').data('voto')).click()
                        }
                    }
                    else {
                        $("#form_login_loading" + id).hide()
                        self.show()
                        if (data.id == '1' || data.id == '3' ||  data.id == '4')
                            alert('Desculpe mas não foi possível efetuar o login: tente novamente dentre de instantes.');
                        else if (data.id == '2' || data.id == '5')
                            alert('Desculpe mas não foi possível efetuar o login: Usuário ou senha incorreta.');
                    }
                },
                'json')
            }
        })
    })
    
    $("#comentario_submit").click(function () {
        var self = this
        var texto = $("#comentario_texto").val()
        $("#form_comentario_loading").show()
        $(self).hide()
        if (texto == '') {
            alert('Digite um texto.')
            $("#comentario_texto").focus();
            $("#login_submit").hide();
            $("#comentario_submit").show();
        }
        else {
            $.getJSON2Script(URL_COMENTAR, {'schema': SCHEMA, 
                                            'comentario': escape(texto),
                                            'i': ID_NOTICIA},
            function (data) {
                if (data.type == 'ok') {
                    alert('Obrigado, seu comentário foi adicionado com sucesso, dentre de instantes irá ser publicado.');
                    $('#comentario_texto').attr('value', '');
                    $('#count_l').empty().text('300');
                }
                else {
                    if (data.id == '1')
                    {
                      alert('Desculpe mas não foi possível inserir seu comentário: Seu login expirou, será necessário logar novamente.');
                      $('#div_form_comentario').hide();
                      $('#div_form_login').show();
                    } else {
                      alert('Desculpe mas não foi possível inserir seu comentário: Por favor tente mais tarde.');
                    }

                }
                $("#form_comentario_loading").hide()
                $(self).show()
            },
            'json')
        }
    })

    $("#p_votacao > img").click(function () {
        var img = this
        var u = get_user();
        var v = $(this).attr('value');

        if (u) {
            $.getJSON2Script(URL_VOTAR, 
                {'schema': SCHEMA,
                 'i': ID_NOTICIA,
                 'voto': v},
                function (data) {
                    if (data.type == 'ok') {
                        alert('Obrigado, seu voto foi computado com sucesso.')
                        hover_in(img);
                        
                    }
                    else {
                      if (data.id == '1')
                      {
                        alert('Desculpe mas é necessário estar logado para votar.');
                        $('#login_dialog').dialog('open');
                      } else if (data.id == '2') {
                        alert('Desculpe mas é permitido somente votar uma vez por notícia.');
                      } else {
                        alert('Desculpe não foi possível efetuar o voto, tente mais tarde por favor.');
                      }
                    }
                },
                'json')
        } else {
            $('#login_dialog').data('voto', this)
                              .bind('dialogclose' + v, function(event, ui) {
                                 $(img).click()
                              })
                              .dialog('open');
        }
    })

    $("#login_dialog").dialog({
        title:'Login', 
        autoOpen:false, 
        width:385, 
        height:200, 
        modal: true,
        overlay:{opacity: 0.5,background:"black"} 
    }).show()

    function hover_in(img) {
        var img = $(img)
        img.data('src', img.attr('src'))
        img.attr('src', 'http://imgs2.lugarcerto.com.br/star.gif')
        $.each(img.nextAll(), function () {
            var nimg = $(this)
            nimg.data('src', nimg.attr('src'))
            nimg.attr('src', 'http://imgs2.lugarcerto.com.br/star_off.gif')
        })
        $.each(img.prevAll(), function () {
            var nimg = $(this)
            nimg.data('src', nimg.attr('src'))
            nimg.attr('src', 'http://imgs2.lugarcerto.com.br/star.gif')
        })
    }
        
    function hover_out(img) {
        var img = $(img)
        img.attr('src', img.data('src'))
        $.each(img.nextAll(), function () {
            var nimg = $(this)
            nimg.attr('src', nimg.data('src'))
        })
        $.each(img.prevAll(), function () {
            var nimg = $(this)
            nimg.attr('src', nimg.data('src'))
        })
    }
        
    $("#p_votacao > img").hover(
        function () { hover_in(this) },
        function () { hover_out(this) }
    )

    $(".noticia_link_foto_grande").each(function () {
        if ($(this).attr('href') != '')
        {
            $(this).fancybox({'callbackOnStart':function(i) {  },
                      'hideOnContentClick':true,
                      'imageScale':false,
                      'centerOnScroll':false,
                      'overlayShow':true,
                      'frameWidth':720,
                      'frameHeight':480,
                      'callbackOnClose':function(){  } 
            });
        }
    })
    var u = get_user();
    if (u) {
        $("#comentario_nome").text(u)
        $("#div_form_login").hide()
        $("#div_form_comentario").show()    
    }

   $('#comentario_texto').keypress(function(e){
     var vl = $(this).attr('value');
     $('#count_l').empty().text( String(300-vl.length) );
     if (vl.length > 300)
       $(this).attr('value', vl.substr(0, 300));
   })

   $("#notlogoff").click(function () {
        $("#form_comentario_loading").show();
        $.getJSON2Script(URL_LOGOFF, function(data)
        {
          $('#div_form_comentario').hide();
          $('#div_form_login').show();
          $("#form_comentario_loading").hide()
         });
    });
})

function get_user() 
{
  var c = $.cookie('wdah')
  if (c != undefined)
  {
    return c.split('|')[1]
  } else return false;
}
function marcarDesmarcarChkSlide()
{
    if (navigator.appName.substring(0,9) == "Microsoft")
    {
      var chkSlide = document.getElementById('slideck')
      if(chkSlide.checked == true) chkSlide.checked = false;
      else  chkSlide.checked = true;
      galeriaFotosIniciaSlideShow();
    }
}
function galeriaFotosIniciaSlideShow()
{
    var chkSlide = document.getElementById('slideck');
    if (chkSlide.checked ==true)
    {
      if(statusInterval)
        clearInterval(statusInterval);
      cont = 0
      statusInterval = setInterval('galeriaFotosSlideShow()', '3000');
    } else {
      clearInterval(statusInterval);
    }
}

var gld = false;
var items;
var iic = 0;

jQuery(document).ready(function() {

        $('#abas > li > a').each(function(i, item){
        $(item).click(function(e){

          $('#abas > li').each(function(i, item){ $(item).removeClass('selecionado') });
          var its = ['abanoticia', 'abavideo', 'abafoto', 'abainfografico', 'items_noticia'];
          for (i=0;i<its.length; i++){$('#' + its[i]).hide()}
          $(this.parentNode).addClass('selecionado');

          var tl = $(this).attr('title');
          try { reloadAnalitics(); }
          catch(e){};
         
          switch (tl)
          {
            case 'Notícia':
              $('#abanoticia').show();
              $('#items_noticia').show();
              break;
            case 'Vídeo':
              $('#abavideo').show();
              break;
            case 'Foto':
              $('#abafoto').show();
              if (!gld)
              {
                if($.browser.msie && /6.0/.test(navigator.userAgent))
                {
                  tt = setTimeout("workaroundIE6();", 500);
                } else {
                  $('#thumbs > a > b > img').each(function(i, item){
                    $(item).attr('src', $(item).attr('srci'));
                  })
                  var igg = $('#viewimg > img').eq(0);
                  igg.attr('src', igg.attr('srci'));
                }
                gld = true;
             }
             break;
           case 'Gráfico':
             $('#abainfografico').show();
             $("#grfbox").click();
             break;
          }
        })
        });

        $.fn.fancybox.build();
 
        $("#grfbox").fancybox({'hideOnContentClick':true,
                               'imageScale':false,
                               'centerOnScroll':false,
                               'overlayShow':true,
                               'frameWidth':720,
                               'frameHeight':480,
                               'callbackOnClose':function(){ $('#abas > li:first > a').click(); }});


        function workaroundIE6() // i luv this browser
        {
          var igg = $('#viewimg > img').eq(0);
          igg.attr('src', igg.attr('srci'));
          if (!items) items = $('#thumbs > a > b > img');
          var item = items.eq(iic)
          item.attr('src', item.attr('srci'));
          if (tt) clearTimeout(tt);
          if (! (iic++ >= items.lenght) )
            tt = setTimeout("workaroundIE6();", 250);
        }
});
var fcs = {}
function dofancy(id)
{
  if (fcs[id]) return;
  fcs[id] = true;
  $('#' + id).fancybox({'callbackOnStart':function(i) { i['href'] = $(i['el']).attr('hrefi'); },
                      'hideOnContentClick':true,
                      'imageScale':false,
                      'centerOnScroll':false,
                      'overlayShow':true,
                      'frameWidth':720,
                      'frameHeight':480,
                      'callbackOnClose':function(){  } 
  });
  $("#" + id).click();
}
function boxDenuncie(idc)
{
   var winl = (screen.width)/2 - 275;
   var wint = (screen.height)/2 -145;
   document.getElementById('icomentario').value = idc;
   window.open(URL_DENUNCIE, 'wdenunciar', 'status=no, toolbar=no, menubar=no, personalbar=no, resizable=no, scrollbars=no, width=550, height=290, top='+wint+', left='+winl);
}
