(function($){
    //cache needed for overagressive garbage collectors.
    var cache = [];
    //images can either be an array of paths to images or a  single image. 
    $.loadImages = function(images, callback){
    
        //convert to array if needed so rest of script works
        if (!(images instanceof Array)) {
            images = [images];
        }
        
        var imagesLength = images.length;
        var loadedCounter = 0;
        
        for (var i = imagesLength; i--;) {
			var cacheImage = document.createElement('img');
			//set the onload method before the src is called otherwise will fail to be called in IE
            cacheImage.onload = function(){
                loadedCounter++;
                if (loadedCounter >= imagesLength) {
                    if ($.isFunction(callback)) {
                        callback();
                    }
                }
            }
            cacheImage.src = images[i];
            cache.push(cacheImage);
        }
    }
})(jQuery)

bg_ad = {
    original: '#masthead',
    container: '.wrapper_bg',
    load: function(){
        or = $(this.original);
        if(or.length)
        {
            bg = or.css('background-image');
            bg_pos = or.css('background-position');
            olink = or.find('a').attr('href');
            banner_title = stringToSlug(or.find('a')[0].innerHTML);
            or.remove();
            container = $(this.container);
            container.click(function(e){
                if(e.target) {
                    targ = e.target;
                } else if(e.srcElement) {
                    targ = e.srcElement;
                }
                if($(targ).attr('class') == container.attr('class') ) {
                    window.open(olink);
                    try
                    {
                        _gaq.push(['_trackPageview', '/publicidade/click/background_' + banner_title]);
                        //_gaq.push(['_trackEvent', 'Publicidade', 'Click', 'Background - ' + banner_title]);
                    }catch(e){}
                }
            });
            container.css('background-image', bg);
            container.css('background-position', bg_pos);
            container.css('background-repeat', 'no-repeat');
            try
            {
                _gaq.push(['_trackPageview', '/publicidade/view/background_' + banner_title]);
                //_gaq.push(['_trackEvent', 'Publicidade', 'View', 'Background - ' + banner_title]);
            }catch(e){}
        }
    }
}

$(document).ready(function() {
    bg_ad.load();
    rmamz = $('.remover-amigo');
    if(rmamz.length){
        rmamz.each(function(){
            el = $(this);
            if(el[0].tagName == 'A') {
               el.click(function(e){
                   e.preventDefault();
                   if(confirm('Maahh ooeee! Tem certeza disso? Posso perguntar? Valendo 100 mil reais. Deseja remover esta amizade?')){
                       window.location.href = el.attr('href');
                   }
                   return false;
               })
           }
        });
    }
    
    if($('.mask-date').length > 0){
        $('.mask-date').mask('99/99/9999');
    }
	
    function cadastrar () {
        emailel = $('#email');
        var email = emailel.val();
        if( email.indexOf("@") >= 1 && email.indexOf(".") >= 3 ) {
            $.post("/newsletter", {'email': email, 'csrf_token': emailel.parent().find('input[name=csrf_token]').val()}, 
            function(data) {
                if(data == 'E-mail inválido' || data == 'E-mail já cadastrado') {
                    emailel.css('color', 'red');
                } else {
                    emailel.css('color', 'green')
                }
                emailel.val(data);
            });
        } else {
            emailel.val('E-mail inválido').css('color', 'red');
        }
    }

    $('#email').click(function () {
        var email = $(this).val();
        $(this).css('color', '#999999');
        if( email.indexOf("@") <= 0 && email.indexOf(".") <= 2) {
            $(this).val('');
        }
    });
    $('#enviar').click(function (e) {
        e.preventDefault();
        cadastrar();
        return false;
    });
    $('#email').keypress(function (event) {
        if (event.which == '13') {
            event.preventDefault();
            cadastrar();
        }
    });	
	
    try{
        $('.slideshow').cycle({
            fx:     'scrollHorz',
            prev:   '.left_arrow',
            next:   '.right_arrow',
            timeout: 0
        });
    }catch(e){}
    
    try{
        $('.ultimos-videos-list').cycle({
            fx:     'scrollVert',
            prev:   '.subir',
            next:   '.descer',
            timeout: 600000
        });
    }catch(e){}
	
    try{
        jQuery('ul.sf-menu').superfish();
    }catch(e){}
	
    $('.skin input').focus(function(){
        $(this).prev().fadeOut();
    }).blur(function(){
        if($(this).attr('value') == ''){
            $(this).prev().fadeIn();
        }
    }).each(function(){
        if($(this).attr('value') !== ''){
            $(this).prev().hide();
        }
    });
	
    fileField = $('#fakefile input[type="file"]');
    if(fileField.length == 1){
        fileField.css('opacity',0).change(function(){
            $(this).parent().find('input[type="text"]').val($(this).val())
        });
    }
    if($.prettyPhoto){
        $('.pp-open').prettyPhoto();
    }
		
    if($('.gallery a .destaque-titulo').length){
        $('.gallery a').hover(
            function(){
                $(this).find('span.destaque-titulo').animate({
                    opacity:1
                });
            },
            function(){
                $(this).find('span.destaque-titulo').animate({
                    opacity:0
                });
            }
            );
    }
	
    tps = $('.tp-error');
    if(tps.length){
        makeErrors(tps);
    }
	
    $('#userbar').load('/usuario/logado', function() {
        $("#cadastre-se, #login").prettyPhoto();
    });
    
    sb = $('.slider_box');
    if(sb.length)
    {
        if($.cookie("visitou") == null){
            $('.precadastro .skin input').focus(function(){
                $(this).prev().fadeOut();
            }).blur(function(){
                if($(this).attr('value') == ''){
                    $(this).prev().fadeIn();
                }
            }).each(function(){
                if($(this).attr('value') !== ''){
                    $(this).prev().hide();
                }
            });
            $('.precadastro .close-bt').click(function(){
                $('.precadastro').fadeOut('slow', function(){
                    $(this).remove();
                    $.cookie("visitou", "true", {path:"/", expires: new Date( new Date().setDate(new Date().getDate() + 5) )});
                })
            });
            $('.precadastro form').submit(function(e){
                e.preventDefault();
                f = $(this);
                $.ajax({
                    url: f.attr('action'),
                    dataType: 'json',
                    type: 'POST',
                    data: f.serialize(),
                    success: function(json){
                        if(json.error){
                            jQuery.each(json.error_messages, function(where, message){
                                $('.precadastro form').find('div.' + where).after($(message).hide().fadeIn());
                            });
                            makeErrors($('.precadastro .tp-error'));
                        }else{
                            $.prettyPhoto.open({descrition_class: 'green'}, '/usuario/sucesso/?iframe=true&width=490&height=265', '', 'Yahoo! Tchanãnã');
                            setTimeout(function(){
                                window.location.href = '/usuario/configuracoes';
                            }, 6000);
                            $.cookie("visitou", "true", {path:"/", expires: new Date( new Date().setDate(new Date().getDate() + 5) )});
                        }
                    }
                });
                return false;
            });
            $('.precadastro').show();
        }         
    }
    
    lnkmedalhas = $('.link-medalha');
    if(lnkmedalhas.length)
    {
        lnkmedalhas.click(function(){
            $(this).parent().prepend('<a href="javascript:void(0);" style="position:absolute" id="md-exp"><img src="/images/medalhas/exp_medalha_101.png" alt=""></a>');
            $('#md-exp').click(function(){$(this).remove()})
        });
    }
	
});

function makeErrors(tps){
    tps.each(function(){
        tp = $(this);
        if(tp.has('.tp-seta').length === 0)
        {
            text = tp.html();
            tp.empty().append('<div class="tp-seta"></div><div class="tp-content box-round"><div class="tp-text"></div><a href="javascript:void(0);" class="box-round">x</a><div class="clear"></span></div>');
            tp.find('.tp-content .tp-text').html(text);
            tp.find('a').click(function(){
                $(this).parents('.tp-error').fadeOut('fast',function(){$(this).remove()});
            });
        }
    });
}

window.closePrettyphoto = function(params){
    if($.prettyPhoto){
        params = jQuery.extend({
            url: false,
            settings: {},
            title: ''
        },params);
        $.prettyPhoto.close();
        if(params.url !== false){
            setTimeout(function(){
                $.prettyPhoto.open(params.settings, params.url, '', params.title);
            }, 1000);
        }
    }
}
