var
    link = 0,
    qnt_links = 0;
$(function(){
    
    /* ## BANNERS ## */
    
    try{
        $('a.bannerImage').each(function(){
            var a = $(this);
            SRC = a.find('span.src').html();
            a.html('').append($('<img />').attr({
                src: SRC,
                title: a.attr('title'),
                alt: ''
            }));
        })
        $('a.bannerImage').siblings('.nivo-html-caption').appendTo($('body'));
    }
    catch(e){
        
    }
    
    /* ## VIDEO ## */
    
    try{
        $('.video_img').click(function(){
            VIDEO_URL = $(this).attr('href');
            $.ajax({
                url: VIDEO_URL,
                type: 'GET',
                dataType: 'html',
                data: {ajax: 1, width: 235, height: 176},
                success: function(html){
                    $('.video_img').replaceWith(html);
                }
            })
            return false;
        })
        /*$('.colorbox').colorbox({
            opacity:0.5,
            href: function(){
                return $(this).attr('href') + '?ajax=1'
            }
        });*/
    }catch(e){
        
    }
    
    /* ####### ENQUETE ######## */
    
    function enviarEnquete(){
        if(!$('#votar_btn').hasClass('disabled'))
            $.ajax({
                url: $('#formEnquete').attr('action'),
                type: 'GET',
                dataType: 'json',
                data: $('#formEnquete').serialize() + '&ajax=1',
                beforeSend: function (){
                    $('#votar_btn').addClass('disabled');
                    parentButton = $('#votar_btn').parent();
                    if(!$('#enquete .loader').length)
                        parentButton.prepend(
                            $('<img/>').attr({
                                id: 'enqueteLoader',
                                src: $_basedir + 'default/imagens/ajax-loader.gif'
                            }).addClass('loader')
                        );
                    $('#enquete .loader').show();
                },
                success: function (json){
                    $('#enquete .loader').hide();
                    if(json.notify.length){
                        for(var i in json.notify)
                            jAlert(json.notify[i].text);
                    }
                    if(json.resultados.length){
                        $('#enquete .answer')
                            .removeClass('radios')
                            .unbind('click')
                            .click(function(){return false;})
                        for(var i in json.resultados){
                            $('#resposta-' + json.resultados[i].id)
                            .parent()
                            .append(
                                $('<div/>')
                                .addClass('resultado')
                                .width(json.resultados[i].stat + '%')
                                .html('&nbsp;')
                            )
                            .append(
                                $('<div/>')
                                .addClass('resultado_text')
                                .text(json.resultados[i].stat + '% com ' + json.resultados[i].votos + (json.resultados[i].votos == 1 ? 'voto' : ' votos'))
                            );
                        }
                        $('#enquete li').css({'paddingBottom': '0px'});
                        $('#enquete li:first').css({'marginBottom': '15px'}).siblings().css({'marginTop': '-15px'});
                        $('#votar_btn').unbind('click').hide();
                    }
                    $('#votar_btn').removeClass('disabled');
                },
                error: function(jqXHR, textStatus, errorThrown){
                    $('#enquete .loader').hide();
                    jAlert('Houve um problema ao computar seu voto. Tente novamente mais tarde');
                }
            })
    };
    
    $('#enquete input').hide();
    $('#ul-enquete .answer')
        .click(function(){
            value = $(this).attr('id').split('-').pop();
            $('#ul-enquete .answer').removeClass('selected');
            $('#enquete input[type="radio"]').removeAttr('checked');
            $(this).addClass('selected');
            $('#enquete_opcao-' + value).attr('checked', 'checked');
        })
    ;
    
    $('#votar_btn').show().click(function(){enviarEnquete();return false;});
    $('#formEnquete').submit(function(){enviarEnquete();return false;});
    
    /* ####################### */
    
    $('#slider')
        .nivoSlider({
            pauseTime:5000,
            captionOpacity:0.8,
            directionNav:false,
            effect:'fade',
            keyboardNav: false,
            afterChange: function(){
                currentA = $(this).find('.nivo-imageLink').not(':hidden');
                caption = $(this).find('.nivo-caption');
                caption
                    .removeClass('banner-font-pequena')
                    .removeClass('banner-font-normal')
                    .removeClass('banner-font-grande')
                if(currentA.is('.banner-font-pequena'))
                    caption.addClass('banner-font-pequena');
                else if(currentA.is('.banner-font-normal'))
                    caption.addClass('banner-font-pequena');
                else if(currentA.is('.banner-font-grande'))
                    caption.addClass('banner-font-pequena');
            }
        });
        
    $('#links-veja-tambem li')
        .each(function(i,e){
            $(e)
                .addClass('vj-tb-'+ i);
        })
        
    qnt_links = $('#links-veja-tambem li').length;
        
    $('#top #veja-tambem a.prev')
        .click(function(){
            
            clearInterval(h);
            h = setTimeout(function(){
                $('#top #veja-tambem a.next')
                    .triggerHandler('click');
            },8000);
            
            lista = $('#links-veja-tambem');
            lista
                .find('li')
                .removeClass('show');
                
            prox = link - 1;
            if(prox < 0)
                prox=qnt_links - 1;
            lista
                .find('li.vj-tb-'+prox)
                .addClass('show');
            
            link = prox;
        });
        
    $('#top #veja-tambem a.next')
        .click(function(){
            
            clearInterval(h);
            
            h = setTimeout(function(){
                $('#top #veja-tambem a.next').triggerHandler('click');
            },8000);
            
            lista = $('#links-veja-tambem');
            lista
                .find('li')
                .removeClass('show');
                
            prox = link + 1;
            if(prox >= qnt_links)
                prox=0;
            
            lista
                .find('li.vj-tb-'+prox)
                .addClass('show');
            
            link = prox;
            
        });
        
        h = setTimeout(function(){
            $('#top #veja-tambem a.next').triggerHandler('click');
        },5000)
        
        $('#celular')
            .mask('(99) 9999-9999');
            
        $('input[type="text"]')
            .val('')
            
        $('li.tweet:last').addClass('no-border');
        
        $('#formNewsletter').submit(function(){
            $.ajax({
                url: $('#formNewsletter').attr('action'),
                type: $('#formNewsletter').attr('method'),
                dataType: 'json',
                data: $('#formNewsletter').serialize() + '&ajax=1',
                beforeSend: function(){
                    $('#formNewsletter .loader').show();
                },
                success: function(json){
                    $('#formNewsletter .loader').hide();
                    if(json.notify.length > 0){
                        for(var i in json.notify)
                            jAlert(json.notify[i].text);
                    }
                    if(json.status == 1)
                        $('#formNewsletter').get(0).reset();
                    $('#formNewsletter input:first').focus();
                },
                error: function(jqXHR, textStatus, errorThrown){
                    $('#formNewsletter .loader').hide();
                    jAlert('Erro na comunicação com o servidor: ' + errorThrown);
                }
            })
            return false;
        });
        $('#linksUteisForm').attr({target: '_blank'});
        
        $("#links select:first")
            .change(function(){
                option = $(this).find('option:selected');
                if(option.val() != 0){
                    $('#linksUteisForm').attr({action: option.val()});
                    $('#linksUteisForm').trigger('submit');
                }
            })
            .msDropDown()
        ;
        /*
        setInterval(function(){
            inicial = 18690;
            addNumber = jQuery.randomBetween(10000, 20000)
            numeroAtual = $.cookie('cnt_numero') == null ? inicial : parseInt($.cookie('cnt_numero'));
            numero = Math.floor(numeroAtual + addNumber);
            if(numero > 9999999999)
                numero = inicial;
            $.cookie('cnt_numero', numero);
            $('#esgoto-tratado-por-segundo .metros .number').text(number_format (numero, 0, ',', '.'));
        }, 1500);
        */
       var NumeroM3 = parseInt($('#esgoto-tratado-por-segundo .metros .number').text());
        setInterval(function(){
            numero = NumeroM3++;
            $('#esgoto-tratado-por-segundo .metros .number').text(number_format (numero, 0, ',', '.'));
        }, 1000);
})
jQuery.extend({
	random: function(X) {
	    return Math.floor(X * (Math.random() % 1));
	},
	randomBetween: function(MinV, MaxV) {
	  return MinV + jQuery.random(MaxV - MinV + 1);
	}
});
function number_format (number, decimals, dec_point, thousands_sep) {
    /* http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival
    // +      input by: Kheang Hok Chin (http://www.distantia.ca/)
    // +   improved by: davook
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Jay Klehr
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Amir Habibi (http://www.residence-mixte.com/)
    // +     bugfix by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Theriault
    // +      input by: Amirouche
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
    // *     example 7: number_format(1000.55, 1);
    // *     returns 7: '1,000.6'
    // *     example 8: number_format(67000, 5, ',', '.');
    // *     returns 8: '67.000,00000'
    // *     example 9: number_format(0.9, 0);
    // *     returns 9: '1'
    // *    example 10: number_format('1.20', 2);
    // *    returns 10: '1.20'
    // *    example 11: number_format('1.20', 4);
    // *    returns 11: '1.2000'
    // *    example 12: number_format('1.2000', 3);
    // *    returns 12: '1.200'
    // *    example 13: number_format('1 000,50', 2, '.', ' ');
    // *    returns 13: '100 050.00'
    // Strip all characters but numerical ones.*/
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}
