$(function() {
    hideMenu = function() {
        $("#menu table").fadeOut('slow',function() { $('#menu').removeClass('hover').addClass('closed'); $("#menu table").show(); /*$('#banner_topo').css({visibility:'visible'});*/ });
    }
    hideLinks = function() {
        $('.links_restrito').fadeOut('slow');
    }
    

    $('#menu .botao_menu,#menu').mouseover(function() {
        //$('object,embed').css({visibility:'hidden'});
        //$('#banner_topo div').addClass('closed');
        $('#menu').addClass('hover').removeClass('closed');
    });

    $('#menu').mouseleave(function() {
        //$('#banner_topo div').removeClass('closed');
        //$('object,embed').css({visibility:'visible'});
        if($(this).hasClass('hover')) {
            $(this).addClass('closed');
            $(this).removeClass('hover');
        }
    });

    $("#menu table th").each(function() {
        $Wrap = $(this).attr('wrap') == undefined ? false : true;
        $(this).pir({
            font: "HelveticaNeueLTStd-ThCn2.ttf",
            color:'#7e7777',
            size: 16 ,
            wrap: $Wrap
        });
    });

    $(".w_hel_cond").each(function() {
        $Wrap = $(this).attr('wrap') == undefined ? false : true;
        $(this).pir({
            font: "HelveticaNeueLTStd-Cn2.ttf",
            color:'#FFF',
            size: 10 ,
            wrap: $Wrap
        });
    }).hover(function() { $(this).addClass('hover'); },function() { $(this).removeClass('hover'); });

    $(".helv_tc").each(function() {
        $Wrap = $(this).attr('wrap') == undefined ? false : true;
        $Cor = $(this).css('color') == undefined ? '#5f5858' : $(this).css('color');
        $Font = $(this).css('fontSize') == undefined ? '11' : $(this).css('fontSize');
        $(this).pir({
            font: "HelveticaNeueLTStd-ThCn2.ttf",
            color:$Cor,
            size: $(this).css('fontSize') ,
            casing: 'uppercase',
            wrap: $Wrap
        });
    });
    
    $('#representantes_home').change(function() {
        window.location = BaseURL +'/representantes/index/estado/'+$(this).val();
    });
    
    $('#news_home').submit(function() {
        
        Email = $(this).find('#email_news').val();
        Nome = $(this).find('#nome_news').val();
        Interesse = $(this).find('#interesse_news').val();
        $.post(BaseURL+'/news/assinar/',{ nome: Nome, email: Email,interesse: Interesse },function(response) { TrataRespostaAjax(response,$('#news_home')); });
        return false;
    });

    $('#enquete_home').submit(function() {
        return false;
    });

    $('#bt_votar_enquete').click(function() {
        EnviaEnquete();
        return false;
    });

    $('#bt_resultado_enquete').click(function() {
        Enquete = $('#enquete_home input[name=enquete]').val();
        $('#enquete_home').hide();
        $('#load_enquete_home').show();
        $.post(BaseURL+'/enquete/resultado',{
            enquete: Enquete
        },function(response) {
            if(response.indexOf('0,,') == 0) {
                TrataRespostaAjax(response,$('#enquete_home'));
            }
            else {
                $('#load_enquete_home').hide();
                $('#resultado_enquete_home').html(response).show();
            }
        });
        return false;
    });

    $('input[prompt]').each(function() {
        $(this).val($(this).attr('prompt'));
    }).focus(function() {
        if($(this).val()==$(this).attr('prompt'))$(this).val('');
    }).blur(function() {
        if($(this).val() == '')
            $(this).val($(this).attr('prompt'));
    });

    $('#botao_restrito').mouseover(function() {
        $('.links_restrito').show();
    });
    $('.links_restrito').hover(function() {
        $(this).show();
    },
    function() {
        $(this).hide();
    });

    $('.link_print_page').click(function() {
        print();
    });

    $('#form_busca').submit(function() {
        $.post(BaseURL + '/busca/geratermo/termo/',{termo:$('#termo_busca').val()},function(response) {
            if(response != '') {
                window.location = BaseURL + '/busca/index/termo/'+response;
            }
        })
        return false;
    });
    $('#busca_noticias').submit(function() {
        $.post(BaseURL + '/busca/geratermo/termo/',{termo:$('#termo_busca').val()},function(response) {
            if(response != '') {
                window.location = BaseURL + '/busca/index/tipo/noticias/termo/'+response;
            }
        })
        return false;
    });

});

function EnviaEnquete() {
    Enquete = $('#enquete_home input[name=enquete]').val();
    Voto = $('#enquete_home input[name=voto]:checked').val();
    if(Voto!=undefined)
        $.post(BaseURL+'/enquete/votar',{
            voto: Voto,
            enquete: Enquete
        },function(response) {
            TrataRespostaAjax(response,$('#enquete_home'));
        });
    else
        alert('É necessário escolher alguma das opções para votar');
    return false;
}

function EscondeResultado() {
    $('#enquete_home').show();
    $('#load_enquete_home').hide();
    $('#resultado_enquete_home').html('').hide();
    return false;
}

function isset(VarName) {
    type = undefined;
    try {
        eval('type = typeof('+VarName+')');
        if(type == 'undefined') {
            return false;
        }
        else {
            return true;
        }
    }
    catch(e) {
        return 'false1';
    }
}

function empty(Valor) {
    if(Valor == '' || Valor == null || Valor == undefined) {
        return true;
    }
    else
        return false;
}

function ChangeStatus(Controller,Action,Codigo,This) {
    BGPos = This.css('backgroundPosition');
    This.css({
        background:'url('+BaseURL+'/imagens/admin/loading.gif) no-repeat center center'
        });
    $.post(BaseURL+'/admin/'+Controller+'/'+Action+'/cod/'+Codigo+'/ajax/1',{
        cod:Codigo
    },function(response) {
        if(response == 1) {
            if(This.hasClass('ativo')) {
                This.removeAttr('style').removeClass('ativo').addClass('desativado').attr({
                    'title':'Ativar'
                });
            }
            else {
                This.removeAttr('style').removeClass('desativado').addClass('ativo').attr({
                    'title':'Desativar'
                });
            }
            return true;
        }
        else {
            if(response.indexOf('0,,')==0) {
                Str = response.split('0,,');
                alert(Str[1]);

            }
            else
                alert('Falha ao processar a informação tente novamente mais tarde.');

            This.css({
                background:'url('+BaseURL+'/imagens/admin/bg/sprites.gif) no-repeat '+BGPos
                });
        }
    });
    return false;
}


function DeletaItem(Controller,Action,Codigo,This) {
    BGPos = This.css('backgroundPosition');
    Debug(This);
    This.css({
        background:'url('+BaseURL+'/imagens/admin/loading.gif) no-repeat center center'
        });
    if(confirm('Deseja realmente deletar esse item?')) {
        $.post(BaseURL+'/admin/'+Controller+'/'+Action+'/cod/'+Codigo+'/ajax/1',{
            cod:Codigo
        },function(response) {
            if(response == 1) {
                Debug(Linha = This.parents('tr:eq(0)'));
                Linha.fadeOut(200,function() {
                    Linha.remove();
                    $('#listagem_geral tr:nth-child(odd)').each(function() {
                        $(this).find('td').css({backgroundColor:'#E1E1E1'});
                    });
                    $('#listagem_geral tr:nth-child(even)').each(function() {
                        $(this).find('td').css({backgroundColor:'#f0f0f0'});
                    });
                });
            }
            else {
                if(response.indexOf('0,,')==0) {
                    Str = response.split('0,,');
                    alert(Str[1]);

                }
                else
                    alert('Falha ao processar a informação tente novamente mais tarde.');

                This.css({
                    background:'url('+BaseURL+'/imagens/admin/bg/sprites.gif) no-repeat '+BGPos
                    });
            }
        });
    }
    else {
        This.css({
            background:'url('+BaseURL+'/imagens/admin/bg/sprites.gif) no-repeat '+BGPos
            });
    }
    return false;
}

function TrataRespostaAjax(Str,Form) {

    if(Str == 1 || Str.indexOf('1,,')==0) {
        if(Str.indexOf('1,,')==0) {
            Str = Str.split('1,,');
            alert(Str[1]);
            if(Form != '') {
                Form.get(0).reset();
            }
        }
        else
            alert('Informação processada com sucesso.')
    }
    else if(Str.indexOf('0,,')==0) {
        Str = Str.split('0,,');
        alert(Str[1]);

    }
    else {
        alert('Falha ao processar a informação. Por favor tente mais tarde.')
    }

    Form.fadeTo('fast',1);
    Form.find('input').each(function() {
        $(this).removeAttr('disabled');
    });
}

function Debug(Var) {
    if(isset('window.console')) {
        window.console.debug(Var);
        return true;
    }
    return false;
}

function AbsMiddle(Opt) {
    //$('window').unbind('resize',function() { AbsMiddle(Opt); });
    if(Opt.Obj == undefined) {
        return;
    }
    else {
        Obj = $(Opt.Obj);

        width = !empty(Opt.width) ? parseInt(Opt.width) : Obj.outerWidth();
        height= !empty(Opt.height)? parseInt(Opt.height): Obj.outerHeight();

        wW= $(window).width();
        wH= $(window).height();

        mHor= (wW > width) ? parseInt(wW - width) : 0;
        mVer= (wH > height)? parseInt(wH - height) : 0;

        if(empty(mHor) || empty(mVer)) {
        //return;
        }

        Top = mVer/2 + 'px';
        Left= mHor/2 + 'px';

        Obj.css({
            'position':'absolute',
            'top':Top,
            'left':Left
        });
        //$(window).bind('resize',function() { AbsMiddle(Opt); });
        if(!empty(Opt.onFinish)) {
            Opt.onFinish();
        }
    //Debug('W: '+width+', H: '+height+', wW: '+wW+', wH: '+wH+', mHor: '+mHor+', mVer: '+mVer);
    }
}
