$(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 - 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);
  });
  $("#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 currentFontSize = $('.font_change').css('font-size');
    var currentFontSizeNum = parseFloat(currentFontSize, 10);
    var newFontSize = currentFontSizeNum*1.2;
    $('.font_change, .font_change > *').css('font-size', newFontSize);
  });
  // Decrease Font Size
  $("#link_font_down").click(function(){
    var currentFontSize = $('.font_change').css('font-size');
    var currentFontSizeNum = parseFloat(currentFontSize, 10);
    var newFontSize = currentFontSizeNum*0.8;
    $('.font_change, .font_change > *').css('font-size', newFontSize);
  });
    
  var SCHEMA = 'noticia182';
  var URL_LOGIN = "/appss/wad10/autenticar";
  var URL_COMENTAR = "/appss/wad10/comentar";
  var URL_VOTAR = "/appss/wad10/votar";
  URL_LOGOFF = "/appss/wad10/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 {
                $.post(URL_LOGIN, {'e': email, 'senha': password, ids: '34'},
                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 {
            $.get(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) {
            $.get(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', 'imgs/star.gif')
        $.each(img.nextAll(), function () {
            var nimg = $(this)
            nimg.data('src', nimg.attr('src'))
            nimg.attr('src', 'imgs/star_off.gif')
        })
        $.each(img.prevAll(), function () {
            var nimg = $(this)
            nimg.data('src', nimg.attr('src'))
            nimg.attr('src', 'imgs/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).lightBox({
            imageLoading: 'imgs/lightbox-ico-loading.gif',
            imageBtnClose: 'imgs/lightbox-btn-close.gif',
            imageBtnPrev: 'imgs/lightbox-btn-prev.gif',
            imageBtnNext: 'imgs/lightbox-btn-next.gif',
            //txtImage: 'Imagem',
            txtOf: 'de'
            //fixedNavigation:true
        })
        }
    })
    function get_user() {
        var c = $.cookie('wdah')
        if (c != undefined) {
            return c.split('|')[1]
        }
        else return false;
    
    }
    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();
        $.get(URL_LOGOFF, function(data)
        {
          $('#div_form_comentario').hide();
          $('#div_form_login').show();
          $("#form_comentario_loading").hide()
         });
    });
})
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);
    }
}