$(document).ready(function() {
    $.ajax({
        url: '?',
        data: "action=getNFavorites&p=1&cd=" + new Date().getTime(),
        success: function(vl){
            if (vl > 0){
                $('#mnFavorites').text("Favorites (" + vl + ")");
            }
        }
    });

    $('#changeCountry').change(function(){
        $('#formChangeCountry').attr('action', window.location);
        $('#formChangeCountry').submit();
    });

    //enter pra enviar form
    $('#form_search').keydown(function(e){
        if (e.keyCode == 13) {
            $(this).parents('form').submit();
            return false;
        }
    });

    $('.linkClass_personal').click(function(){
        var url = $(this).attr('href');
        $.ajax({
            url: '?action=modal_aviso&'+ new Date().getTime(),
            beforeSend: function() {
                $.blockUI();
            },
            success: function(tpl){
                if (tpl != 'false'){
                    $.blockUI(tpl, {
                        'top':'30%',
                        'width':'350px'
                    });
                    $('#entrar').click(function(){
                        $.ajax({
                            url: '?action=modal_aviso&vrf=true&'+ new Date().getTime()
                        });
                        window.location = url;
                    });
                    $('#sair').click(function(){
                        $.ajax({
                            url: '?action=modal_aviso&vrf=true&'+ new Date().getTime()
                        });
                        $.unblockUI(tpl, {
                            'top':'30%'
                        });
                    });
                } else {
                    window.location = url;
                }
            }
        });
        return false;
    });

    //Block UI default
    $.blockUI.defaults = {
        pageMessage:    '<h1 style="font-size: 14px;text-align: center;padding: 5px">Please wait...</h1>',
        overlayCSS:  {
            backgroundColor: '#000',
            opacity: '0.5'
        },
        pageMessageCSS:  {
            width:'250px',
            margin:'-50px 0 0 -125px',
            top:'15%',
            left:'50%',
            color:'#000',
            backgroundColor:'#fff',
            border:'1px solid #aaa',
            'cursor':'default',
            'display': 'inline'
        }
    };

    $("input[name='Go search']").click(function(){
        $("#searchArea").submit();
    });

    //Block UI Search
    $("input[name='Change search'], input[name='New search'], input[name='search_here'], #mnSearch, #mapSiteSearch, #searchEsquerda").click(function() {
        $.ajax({
            url: '?action=modal_search&'+ new Date().getTime(),
            beforeSend: function() {
                $.blockUI();
            },
            success: function(tpl){
                $.blockUI(tpl, {
                    'width':'',
                    'height': '450px'
                });
                $(".mallSubArea").hide();
                showAreaInicio();
                $(".mshowSubArea").click(function(){
                    if ($("#mshowSub"+$(this).attr('id')).css('display') == 'none'){
                        $("#mshowSub"+$(this).attr('id')).show('slow');
                        $("#mImg"+$(this).attr('id')).attr("src", "imagens/flecha_branca_baixo.gif");
                    } else {
                        $("#mshowSub"+$(this).attr('id')).hide('slow');
                        $("#mImg"+$(this).attr('id')).attr("src", "imagens/flecha_branca_direita.gif");
                    }
                });
                $("#closeModal").click(function(){
                    $("#mnFavorites").html();
                    $.unblockUI(".agrupaModal");
                });
                $("input[name='all']").click(function(){
                    var x = false;
                    if (this.checked) x = true;
                    $("#mshowSubArea"+this.value+" input").each(function(){
                        this.checked = x;
                    });
                });
                $(".jsAddCity").click(function(){
                    abrePopUp();
                });
                $('.imgDeleteCity').click(function(){
                    var id = $(this).attr('id').split('_');
                    $.ajax({
                        url: '?action=remove_location&' + new Date().getTime(),
                        data: {
                            'tipo': id[0],
                            'codigo':id[1]
                        },
                        success: function(res){
                            reloadLocations();
                        }
                    });
                });
            }
        });
        return false;
    });


    //pop-up add city
    function abrePopUp(){
        window.open('?action=add_city', 'Add_city', 'width=517, height=400, scrollbars=no, top=' + (screen.height-400)/2 + ', left=' + (screen.width-518)/2 + '');
    }
    $(".jsAddCity").click(function(){
        abrePopUp();
    });

    //limpar sessions de busca
    $(".clear_search").click(function(){
        $.ajax({
            url: '?action=clear_session&'+ new Date().getTime(),
            success: function(){
                window.location = String(document.location);
            }
        });
    })

    //buscar location na lista
    $(".linkLocation").click(function(){
        $.ajax({
            url: '?action=modal_search&area=locations&'+ new Date().getTime(),
            beforeSend: function() {
                $.blockUI();
            },
            success: function(tpl){
                $.blockUI(tpl, {
                    'width':'',
                    'height': ''
                });
                $("#addCityModal").click(function(){
                    abrePopUp();
                });
                $("input[name='go']").click(function(){
                    window.location.reload();
                    return false;
                });
                $("#closeModal").click(function(){
                    $.unblockUI();
                });
                $('.imgDeleteCity').click(function(){
                    var id = $(this).attr('id').split('_');
                    $.ajax({
                        url: '?action=remove_location&' + new Date().getTime(),
                        data: {
                            'tipo': id[0],
                            'codigo':id[1]
                        },
                        success: function(res){
                            reloadLocations();
                        }
                    });
                });
            }
        });
        return false;
    });

    //redireciona para resultados de busca de classificados com ou sem imagens
    $("#has_image").click(function(){
        if(this.checked) x = 1;
        else x = 0;
        $.ajax({
            url: '?action=set_has_image',
            data: {
                has_image:x
            },
            success: function(){
                document.location = window.location;
            }
        });
    });

    //recuperar senha
    $(".jsForgotPassword").click(function(){
        $.ajax({
            url: '?action=forgot_password&'+ new Date().getTime(),
            beforeSend: function() {
                $.blockUI();
            },
            success: function(tpl){ // carregando o formulário
                $.blockUI(tpl, {
                    'width':'330px',
                    'height': 'auto',
                    'margin':'-50px 0 0 -170px'
                });
                $("#cancel").click(function(){
                    $.unblockUI();
                    return false;
                });
                //Post reply // se enviado algo pelo form
                $("#send").click(function(){
                    $.ajax({
                        url:'?action=forgot_password',
                        type:'POST',
                        data: {
                            'system': $("#system").val(),
                            'email': $("#emailForgote").val(),
                            'birthday': $("#birthdayForgote").val()
                        },
                        beforeSend: function(){
                            $('#send, #cancel').hide();
                            $('.alinhaBtnForgotForg').prepend('<img id="imgLoad" src="imagens/load2.gif" />');
                        },
                        success: function(erro){
                            if (erro == '1'){ //caso sucesso no envio
                                $("#formForgot input").val('');
                                alert('New password sent to your email.');
                                $.unblockUI();
                            } else { //caso tenha erros na validação
                                $("#erroForg").html('');
                                var i, obj;
                                obj = eval('(' + erro + ')');
                                for (i in obj){
                                    $("#erroForg").append(obj[i]);
                                }
                            }
                            //mostrando os botoes
                            $('#send, #cancel').show();
                            $('#imgLoad').remove();
                        }//fim success
                    });//fim ajax
                    return false;
                });
            }
        });
    });

    //mostrar na caixa by as áreas selecionadas
    $(".allSubArea").hide();
    $(".showSubArea").click(function(){
        if ($("#showSub"+$(this).attr('id')).css('display') == 'none'){
            $("#showSub"+$(this).attr('id')).show('slow');
            $("#Img"+$(this).attr('id')).attr("src", "imagens/flecha_branca_baixo.gif");
        } else {
            $("#showSub"+$(this).attr('id')).hide('slow');
            $("#Img"+$(this).attr('id')).attr("src", "imagens/flecha_branca_direita.gif");
        }
    });
    //seleciona todas
    $("input[name='all']").click(function(){
        var x = false;
        if (this.checked) x = true;
        $("#showSubArea"+this.value+" input").each(function(){
            this.checked = x;
        });
    });
    showAreaInicio();

    //mensagem quando classificado já se encontra nos favoritos
    $('.selFavorites').click(function(){
        alert('Classified is already in your favorites');
        return false;
    });

    //remove um location
    $('.imgDeleteCity').click(function(){
        removeLocation($(this).attr('id'));
    });

    $('.linkImagem').click(function(){
        var id = $(this).attr('id');
        showAbaBusca(id);
    });


    $('#abaNew, #abaElectronics, #abaTop, #abaHousing, #abaVehicles').hover(
        function(){
            $(this).attr('src', 'imagens/' + this.id + 'Hover.jpg');
        },
        function(){
            $(this).attr('src', 'imagens/' + this.id + '.jpg');
        }
    );


     /** VOTES **/

    $('.linkVotoMais').click(function(){
        var codigo = $(this).attr('rel');
        $.ajax({
            url:'index.php?',
            data: 'action=votar&codigo=' + codigo,
            beforeSend: function(){
                imgLoadingVoto('show', codigo);
            },
            success: function(res){
                imgLoadingVoto('hide', codigo);
                $('#nVoto' + codigo).html(res);
            },
            erro: function(){
                imgLoadingVoto('hide', codigo);
            }
        });
    });

    /** select visualizar **/
    $('#order').change(function(){
        window.location = '?' + $('#urlOrder').val() + '&order=' + $('#order').val();
    });
});

function imgLoadingVoto(acao, codigo){
    if (acao == 'show'){
        $('#nVoto' + codigo + ', #textVoto' + codigo ).hide();
        $('#imgVoto' + codigo).show();
    } else {
        $('#nVoto' + codigo + ', #textVoto' + codigo ).show();
        $('#imgVoto' + codigo).hide();
    }
}

function showAbaBusca(id){
    if ($('#'+id).attr('title') == 'Advanced Search'){
        $('#imgPos1').attr({
            'src':'imagens/botaoAmareloBasicSearch2.jpg'
        });
        $('#imgPos2').attr({
            'src':'imagens/botaoVermAdvancedSearch2.jpg'
        });
        $('#cantoImg').attr({
            'src':'imagens/cantoBrancoAmareloCimaDireita.jpg'
        });
        $('#formLista').hide();
        $('#formBusca').show();

    } else {
        $('#imgPos1').attr({
            'src':'imagens/botaoVermBasicSearch.jpg'
        });
        $('#imgPos2').attr({
            'src':'imagens/botaoAmareloAdvancedSearch.jpg'
        });
        $('#cantoImg').attr({
            'src':'imagens/cantoBrancoVermCimaDireita.jpg'
        });
        $('.allSubArea').hide();
        $(".cxArea input[type='checkbox']").each(function(){
            this.checked = false;
        });
        $('#formBusca').hide();
        $('#formLista').show();
    }
}

function showAreaInicio(){
    arr = new Array;
    var area = 'imgPos1';
    $(".cxArea input[type='checkbox']").each(function(){
        if (this.checked){
            x = $(this).attr('class').split(' ');
            arr.push(x[0]);
        }
    });

    if (arr.length > 0){
        for (x in arr){
            $("#showSubArea"+arr[x]+", #mshowSubArea"+arr[x]).show('slow');
        }
        area = 'imgPos2';
    }
    showAbaBusca(area);
}
//adiciona os novos locations no html
function reloadLocations(){
    $.ajax({
        url: '?action=getCidadesSelecionadas&js=true&'+ new Date().getTime(),
        success: function(res){
            $(".cidade").empty().append(res);
            window.location.reload();
        }
    });

}

function removeLocation(id){
    id = id.split('_');
    $.ajax({
        url: '?action=remove_location&' + new Date().getTime(),
        data: {
            'tipo': id[0],
            'codigo':id[1]
        },
        success: function(res){
            reloadLocations();
        },
        error : function(){
            window.location.reload();
        },
        timeout : 20
    });
    return false;
}
function trim(str){
    return str.replace(/^\s+|\s+$/g,"");
}
