/*
 *  Funções Gerais
 *
 *----------------------------------------------------*/
jQuery(document).ready(function() {
    /* Iniciaizar Topo
    * ---------------------------*/
    $("#header_trans li").fadeTo(0,0.2);
    function beforeFIani(carousel, item, idx, state) {
        $(item).next().fadeTo(5000,1);
    }
    function beforeFOani(carousel, item, idx, state) {
        $(item).next().fadeTo(5000,0.2);
    }
    jQuery('#header_trans').jcarousel({
        wrap: 'circular',auto: 10,start: 1,animation: 5000,scroll:1,
        itemFirstInCallback: {onBeforeAnimation: beforeFIani},
        itemFirstOutCallback: {onBeforeAnimation: beforeFOani}
    });

    /* Iniciaizar Hover Images
    * ---------------------------*/
    jquery_hover.init();
    $('.msn').simpletip({content: 'manueladavila.msn@hotmail.com', fixed: true,position:'top'}).click(function() {
        if (navigator.appName != 'Microsoft Internet Explorer') {return false}
    });




    $('input').keydown(function(event) {if (event.keyCode == '13 ') {$(this).parents('form').find('.button .submit').trigger('click');}});
    if ($(".twt_cont").length > 0) {
        while($(".twt_cont div").height() > 280) $(".twt_cont div").children('p').last().remove();

    }
    if ($('#np_roll').length > 0 ) {
        $('#np_roll').cycle({fx: 'fade', speed:  2000, timeout: 8000});
    }

//    if ( $('.imgheader').length > 0 ) {
//            $(function () {
//                var img = new Image();
//                $(img).load(function () {
//                    $('.imgheader').css({'background-image' : 'url('+$("base").attr("href")+'assets/site/img/topo_manu.png)'});
//                    $('.imgheader').removeClass('loading');
//                }).error(function () {
//                }).attr('src', $("base").attr("href")+'assets/site/img/topo_manu.png');
//            });
//    }
/* FOOTER */
    if ($("#login").length > 0 )
    {
        $("#enviar_login").click(function() {$(this).parents("#login").submit();});
    }
    if ($("#cadf").length > 0 )
    {
        $("#enviar_cadastro").click(function() {$(this).parents("#cadf").submit();});
    }
    if ($("#busca").length > 0 )
    {
        $(".termo").keypress(function (e) {if (e.which == 13) {$("#enviar_busca").trigger('click');}});

        $("#enviar_busca").click(function() {
            if ( ($(".termo").val() != "Busca") && ( $(".termo").val() != "") ) {
                $(location).attr('href', $("base").attr("href")+'pesquisa/'+$.URLEncode($(".termo").val()));
            }
            else return false;
        });
    }
    if ($("#busca2").length > 0 )
    {
        $(".termo2").keypress(function (e) {if (e.which == 13) {$("#enviar_busca2").trigger('click');}});

        $("#enviar_busca2").click(function() {
            if ( ($(".termo2").val() != "Busca") && ( $(".termo2").val() != "") ) {
                $(location).attr('href', $("base").attr("href")+'pesquisa/'+$.URLEncode($(".termo2").val()));
            }
            else return false;
        });
    }


    /* noticias */

    generateImgs = function() {

        if($('.ins_img_left').length >=1)
        {
            $('.ins_img_left').wrap('<span class="insimg">');
            $('.insimg .ins_img_left').parent().wrap('<span class="insimg_left gnot">');
            $('<strong class="insimg_leg">'+$('.ins_img_left').attr('alt')+'</strong>' ).appendTo('.insimg_left');
        }
        if($('.ins_img_center').length >=1)
        {
            $('.ins_img_center').wrap('<span class="insimg">');
            $('.insimg .ins_img_center').parent().wrap('<span class="insimg_center">');
            $('<strong class="insimg_leg">'+$('.ins_img_center').attr('alt')+'</strong>' ).appendTo('.insimg_center');
        }
        if($('.ins_img_right').length >=1)
        {
            $('.ins_img_right').wrap('<span class="insimg">');
            $('.insimg .ins_img_right').parent().wrap('<span class="insimg_right">');
            $('<strong class="insimg_leg">'+$('.ins_img_right').attr('alt')+'</strong>' ).appendTo('.insimg_right');
        }
    }

    if ($(".videostr").length > 0) { $(".videostr").find("br").remove(); }

    applyGalImg = function() {
        $('.insimg').each(function() {
            var img = $(this).children("img");
            var title= $(this).children("img").attr('alt').replace('"','');
            var href= $("base").attr('href')+$(img).attr('src').replace('_185.','.').replace('_500.JPG','.').replace('./','');
            $(img).wrap('<a rel="gnf" href="'+href+'" title="'+title+'" ></a>');
        });
        $("a[rel='gnf']").colorbox();


        $('.ginc').each(function() {
            var href= $("base").attr('href')+$(this).attr('src').replace('_150.','.').replace('./','');
            var title= $(this).attr('title').replace('"','');
            $(this).wrap('<a rel="nrg" href="'+href+'" title="'+title+'" ></a>');
            $("a[rel='nrg']").colorbox();
        });
    }
    if ( ($(".insimg").length >= 1) || ($('.ginc').length >= 1) ) {
        generateImgs();
        applyGalImg();
    }

    // Validate
    if ($("#noticia").length > 0 )
    {

        $("#sub_comentar_noticias").click(function() {$(this).parents("#form_comentar").submit();});
        $("#sub_comentar_artigos").click(function() {$(this).parents("#form_comentar").submit();});
    }

    if ($("#form_comentar").length > 0) {
        $("#form_comentar").validate({
            rules: {
//                nome: {required: true},
//                email: {required: true, email:true},
                comentario: {required: true}
            },
            messages: {
//                nome: {required: "Preecha com o seu nome."},
//                email: {required: "Preencha com o seu e-mail.", email:"Formato inválido."},
                comentario: {required: "Preencha com o comentário."}
            }
        });

    }
    if ( $('textarea.limit').length > 0 )
    {
        $('textarea.limit').limit('.countertext');
    }
    ativarWaterMark = function() {
        $(".watermark").each(function(){
            var label = $(this).prev();
//            alert(label.html();)
            $(this).watermark(label.html());
            label.hide();
        });
    }
    if($('.watermark').length >0)
    {
        ativarWaterMark();
    }

    if ($("select").length >0)
    {
        $("select").prev().hide();
        $("select, .checkbox, .file").uniform({fileBtnText : "Minha Foto",fileDefaultText: "Escolha sua foto"});

    }
    // Validate

    jQuery.validator.addMethod("selectNone", function(value, element) {if (element.value == "null"){return false;} else {return true;}},"Selecione uma opção" );

    if ($("#senha").length > 0 )
    {
            $("#sub_cadastrar").click(function() {$(this).parents("#senha").submit();});

            $("#senha").validate({
                rules: {

                    old_senha: {required: true},
                    senha: {required: true},
                    senha_red: {required: true, equalTo: ".senha"}
                },
                messages: {

                    old_senha: {required: "Preecha com a senha atual."},
                    senha: {required: "Preecha com a senha."},
                    senha_red: {required: "Redigite a senha", equalTo: "As senhas devem ser iguais."}


                }
            });
    }
    if ($("#recuperar").length > 0 )
    {
            $("#sub_recuperar").click(function() {$(this).parents("#recuperar").submit();});

            $("#recuperar").validate({
                rules: {

                    email: {required: true, email:true}
                },
                messages: {
                    email: {required: "Preencha com o seu e-mail.", email:"Formato inválido."}


                }
            });
    }
    if ($("#recuperar_senha").length > 0 )
    {
            $("#sub_cadastrar").click(function() {$(this).parents("#recuperar_senha").submit();});

            $("#recuperar_senha").validate({
                rules: {

                    senha: {required: true},
                    senha_red: {required: true, equalTo: ".senha"}
                },
                messages: {
                    senha: {required: "Preecha com a senha."},
                    senha_red: {required: "Redigite a senha", equalTo: "As senhas devem ser iguais."}


                }
            });
    }
    if ($("#cadastro").length > 0 )
    {
        $("#sub_cadastrar").click(function() {$(this).parents("#cadastro").submit();});
        $(".databr").mask("99/99/9999");

        $.validator.addMethod("acceptFile", function(val, element, param) {
            if ($(element).val() == "") {return true;}
            var ext = $(element).val().split('.').pop().toLowerCase();
            if(jQuery.inArray(ext, param) == -1) {return false;} else{return true;}

        }, "Tipo de arquivo errado.");
        $.validator.addMethod("invalidChar", function(val, element, param) {

            var alphaExp = /^[a-zA-Z-0-9\_\-\#\.]+$/;
            if(!element.value.match(alphaExp)){return false}
            return true;

        }, "Login inválido.");
        if ($("#cadastro").hasClass(".editar").length != 1 ) {
            $("#cadastro").validate({
                rules: {
                    foto: {acceptFile: new Array("jpg")},
                    nome: {required: true},
                    login: {required: true, invalidChar: true},
                    senha: {required: true},
                    senha_red: {required: true, equalTo: "#senha"},
                    email: {required: true, email:true},
                    data_nascimento: {required: true},
                    estado_id: {selectNone: true},
                    cidade_id: {selectNone: true},
                    sexo: {selectNone: true}
                },
                messages: {
                    foto: {acceptFile: "Formato inválido. Formato aceito: .jpg"},
                    nome: {required: "Preecha com o seu nome."},
                    login: {required: "Preecha com o login."},
                    senha: {required: "Preecha com a senha."},
                    estado_id: {selectNone: "Selecione p estado."},
                    cidade_id: {selectNone: "Selecione a cidade."},
                    sexo: {selectNone: "Selecione o seu sexo."},
                    senha_red: {required: "Redigite a senha", equalTo: "As senhas devem ser iguais."},
                    data_nascimento: {required: "Preecha com a data de seu nascimento."},
                    email: {required: "Preencha com o seu e-mail.", email:"Formato inválido."}
                }
            });
        }
        else {
            $("#cadastro").validate({
                rules: {
                    foto: {acceptFile: new Array("png")},
                    nome: {required: true},
                    email: {required: true, email:true},
                    data_nascimento: {required: true},
                    estado_id: {selectNone: true},
                    cidade_id: {selectNone: true},
                    sexo: {selectNone: true}
                },
                messages: {
                    foto: {acceptFile: "Formato inválido. Formato aceito: .jpg"},
                    nome: {required: "Preecha com o seu nome."},
                    estado_id: {selectNone: "Selecione p estado."},
                    cidade_id: {selectNone: "Selecione a cidade."},
                    sexo: {selectNone: "Selecione o seu sexo."},
                    senha_red: {required: "Redigite a senha", equalTo: "As senhas devem ser iguais."},
                    data_nascimento: {required: "Preecha com a data de seu nascimento."},
                    email: {required: "Preencha com o seu e-mail.", email:"Formato inválido."}
                }
            });
        }


        $(".cadastrofoto").change(function(){
            $(".cadastrofoto").blur().focus();
        });
    }

    if ($("#galeria").length > 0)
    {
    }
    if ($("a.imprimir").length > 0) {
        $("a.imprimir").click(function() {
            window.print();
            return false;
        });
    }
    if ($(".noticias_relacionadas").length >0) {
        $(".noticias_relacionadas").click(function() {
                $.ajax({
                    type: "POST",
                    url: $("base").attr('href')+"noticias/relacionadas/"+$(".noticias_relacionadas").attr('rel'),
                    beforeSend: function(){
                        $("#acoes_retorno").html("<div class='acoes_carregando'><p> Carregando... </p></div>");
                        $('.acoes_carregando').fadeIn();
                    },
                    success: function(retorno) {
                        $('.acoes_carregando').hide();
                        $("#acoes_retorno").html(retorno);
                        if ($('.show_relacionadas').length > 0) {
                            $(document).ready(function(){
                                    $('.show_relacionadas').pajinate({
                                        items_per_page : 2,
                                        item_container_id : '.relacionadas',
                                        nav_panel_id : '.page_relacionadas',
                                        nav_label_first : '',
                                        nav_label_prev : 'Anterior',
                                        nav_label_next : 'Próxima',
                                        nav_label_last : ''

                                    });
                            });
                            if (  $('.relacionadas li').length == 1 ){$('.page_relacionadas').hide();}
                        }

                    },
                    error: function(txt)
                    {

                    }
            });
            return false;
        });
    }


    if ($(".artigos_relacionadas").length >0) {
        $(".artigos_relacionadas").click(function() {
                $.ajax({
                    type: "POST",
                    url: $("base").attr('href')+"artigos/relacionadas/"+$(".artigos_relacionadas").attr('rel'),
                    beforeSend: function(){
                        $("#acoes_retorno").html("<div class='acoes_carregando'><p> Carregando... </p></div>");
                        $('.acoes_carregando').fadeIn();
                    },
                    success: function(retorno) {
                        $('.acoes_carregando').hide();
                        $("#acoes_retorno").html(retorno);
                        if ($('.show_relacionadas').length > 0) {
                            $(document).ready(function(){
                                    $('.show_relacionadas').pajinate({
                                        items_per_page : 2,
                                        item_container_id : '.relacionadas',
                                        nav_panel_id : '.page_relacionadas',
                                        nav_label_first : '',
                                        nav_label_prev : 'Anterior',
                                        nav_label_next : 'Próxima',
                                        nav_label_last : ''

                                    });
                            });
                            if (  $('.relacionadas li').length == 1 ){$('.page_relacionadas').hide();}
                        }

                    },
                    error: function(txt)
                    {

                    }
            });
            return false;
        });
    }



    if ($(".noticias_tags").length >0) {
        $(".noticias_tags").click(function() {
                $.ajax({
                    type: "POST",
                    url: $("base").attr('href')+"noticias/tags/"+$(".noticias_tags").attr('rel'),
                    beforeSend: function(){
                        $("#acoes_retorno").html("<div class='acoes_carregando'><p> Carregando... </p></div>");
                        $('.acoes_carregando').fadeIn();
                    },
                    success: function(retorno) {
                        $('.acoes_carregando').hide();
                        $("#acoes_retorno").html(retorno);


                    },
                    error: function(txt)
                    {

                    }
                });
                return false;
            });
    }


    if ($(".artigos_tags").length >0) {
        $(".artigos_tags").click(function() {
                $.ajax({
                    type: "POST",
                    url: $("base").attr('href')+"artigos/tags/"+$(".artigos_tags").attr('rel'),
                    beforeSend: function(){
                        $("#acoes_retorno").html("<div class='acoes_carregando'><p> Carregando... </p></div>");
                        $('.acoes_carregando').fadeIn();
                    },
                    success: function(retorno) {
                        $('.acoes_carregando').hide();
                        $("#acoes_retorno").html(retorno);


                    },
                    error: function(txt)
                    {

                    }
                });
                return false;
            });
    }
    compartilharOrkut = function(titulo, subtitulo, link, imgParentSelector){
        var params = {};
        params[google.orkut.share.Field.TITLE] = titulo;
        params[google.orkut.share.Field.DESTINATION_URL] = link;
        imgs = [];
        $( imgParentSelector+' img').each(function() {
            imgs.push($(this).attr('src'));
        });
        if (subtitulo) params[google.orkut.share.Field.CONTENT] = subtitulo;
        params[google.orkut.share.Field.THUMBNAIL] = imgs;
        var connection = new google.orkut.share.Connection(params);
        connection.send('orkut.com', {});
    }
    compartilharOrkutVideo = function(video) {
        window.open('http://www.orkut.com/FavoriteVideos.aspx?u='+video, {height:650, width:1024, scrollbars:true});
        return false;
    }



    // Videos
    // Validate

    if ($("#video").length > 0 )
    {
        $("#sub_comentar_video").click(function() {$(this).parents("#form_comentar").submit();});
    }


    if ($("#carousel").length > 0 ) {
//        var idstartit = 0;
//
//        loadFeatureCarousel = function(idstartit) {
//            if (idstartit > 0) {idstartit = $(".carousel-feature").index($("#"+idstartit));}
//            idstartit += 1;
//            $("#carousel").featureCarousel({
////                    startingFeature : 1,
//                startingFeature: idstartit,
//                largeFeatureHeight: 300,
//                largeFeatureWidth: 0,
//                smallFeatureHeight: 89,
//                smallFeatureWidth: 133,
//                movedToCenter: function($feature) {
//                  $("#gfhideid").val($feature.attr('id'));
//                  $('.actComentarios').trigger('click');
//                }
//            });
//        }

    }
    if ($("#galeria").length > 0 ) {
        $("#galeria").carousel({
                dispItems:1,

                nextBtn: "<div> </div>",
                prevBtn: "<div> </div>"
        });
//        $(".mudar_galeria").click(function() {
//                $("#gfcomentarios").children().remove();
//                $("#fotos").children().remove();
//                $("#fotos").html("<div class='acoes_carregando'><p> Carregando... </p></div>");
//                $('.acoes_carregando').fadeIn();
//                $("#fotos").load($("base").attr('href')+"/fotos/load/"+$(this).attr('rel'));
//                loadFeatureCarousel(0);
//                return false;
//        });

    }

    // Videos
    // Validate

    if ($("#form_enviar_recado").length > 0) {
        $("#form_enviar_recado").validate({
            rules: {
//                nome: {required: true},
//                email: {required: true, email:true},
                recado: {required: true}
            },
            messages: {
//                nome: {required: "Preecha com o seu nome."},
//                email: {required: "Preencha com o seu e-mail.", email:"Formato inválido."},
                recado: {required: "Preencha com o recado."}
            }
        });
        $("#sub_recado").click(function() {$(this).parents("#form_enviar_recado").submit();});

    }
    if ($('.estado_id').length > 0)
    {

        $('.estado_id').change(function() {
            var id = $(this).val();
            if (id > 0) {
                var cidade = "";
                if ($(this).attr('rel') > 0) {cidade = "/"+$(this).attr('rel');}

                $.ajax({
                    type: "POST",
                    url: $("base").attr('href')+"usuario/getCidade/"+id+cidade,

                    beforeSend: function() {
                        $('.cidade_id').html('Processando...');
                    },
                    success: function(txt) {
                        $('.cidade_id').html(txt);

                        $(".cidade_id option:selected").each(function () {
                            $('.cidade_id').prev('span').text($(this).text());
                        });


                    },
                    error: function(txt) {
                        alert('Não foi possível carregar a lista de cidades.');
                    }
                });
            }
        }).trigger('change');
    }



    // LOGAR E CADASTRAR
    // Validate

    if ($("#logar").length > 0) {
        $("#logar").validate({
            rules: {
                login: {required: true},
                senha: {required: true}
            },
            messages: {
                login: {required: "Preecha com o login."},
                senha: {required: "Preencha com a senha."}
            }
        });
        $("#sub_logar").click(function() {$(this).parents("#logar").submit();});

    }
    if ($("#cadastrar").length > 0) {
        $("#cadastrar").validate({
            rules: {
                nome: {required: true},
                email: {required: true, email:true}
            },
            messages: {
                nome: {required: "Preecha com o seu nome."},
                email: {required: "Preencha com o seu e-mail.", email:"Formato inválido."}
            }
        });
        $("#sub_cadastrar").click(function() {$(this).parents("#cadastrar").submit();});
    }
    if ($("#sub_votar").length > 0)
        {
            $("#sub_votar").live('click',function() {
                $(this).parents('form').submit();


            });
        }
    if ($("#form_contato").length > 0 )

    {
        
        $("#sub_enviar_contato").click(function() {$(this).parents("#form_contato").submit();});
        $("#form_contato").validate({
                rules: {
                    nome: {required: true},
                    email: {required: true, email:true},
                    contato: {required: true}
                },
                messages: {
                    nome: {required: "Preecha com o seu nome."},
                    email: {required: "Preencha com o seu e-mail.", email:"Formato inválido."},
                    contato: {required: "Preencha com a mensagem."}
                }
        });

    }
    /* Galerias */
    tornar_individual = function(el) {
        if( el.index() ==  ($("#lista_fotos li").length)) {
            return false;
        }
        if( el.index() == -1) {
            return false;
        }
        if( el.index() ==  ($("#lista_fotos li").length -1)) {
//            $('.nextPic').children('a').hide();
            $('.nextPic').fadeTo(0,0.5);
        }
        else {$('.nextPic').fadeTo(0,1);}
        if( el.index() ==  0) {
            $('.prevPic').fadeTo(0,0.5);
//            $('.prevPic').children('a').toggle();
        }
        else {$('.prevPic').fadeTo(0,1);}

        $(".active").removeClass("active");
        $(el).addClass('active');
        el = $(el).children('a');
        img = $(el).attr('href');
        legenda = $(el).children('img').attr('alt');
        id = $(el).attr('id');
        $('#gfhideid').val(id);
        var newimg = false;
        $(function () {
            var newimg = new Image();
            $(newimg).load(function () {
                $('.box_imagem').html(this);
                $("#foto_individual").find('p').html(legenda);
                if($(this).height() > 400) {
                    $(this).height(400);
                }
                $("#gfcomentarios").children().remove();
                $("#gfcomentarios").load($('base').attr('href')+'galerias/comentarios/'+id);
                return false;
            }).error(function () { }).attr('src', $(el).attr('href')).attr('alt',$(el).children('img').attr('alt'));
        });
        atualizarTwitter();
    }


});

