/**
 * TikiCMS
 * Copyright (C) 2009, Tiki Web Inteligente Ltda.
 * @requires jQuery 1.3.2 or latter
 *
 * $Id: application.js 124 2011-10-06 13:05:23Z edson $
 */

// define o namespace da aplicação
Application = {
    Controller: {}
};

/**
 * Retorna uma URL completa dado um caminho relativo.
 *
 * É importante que esta função seja definida antes
 * da definição das biliotecas "thickbox" e "sIFR",
 * pois alterei o código-fonte delas para que caminhos
 * relativos sejam convertidos em caminhos absolutos utilizando
 * esta função.
 *
 * @param  string url Um pedaço de URL (caminho relativo dentro do servidor)
 * @return string     Uma URL completa
 */
Application.build_url = function(url) {

    if (!Application.BASE_URL || !Application.BASE_URL.match(/^http/)) {
        Application.BASE_URL = $('meta[name=base_url]').attr('content');
    }

    return Application.BASE_URL + url; 
}

jQuery(document).ready(function($) {

    // invoca o controlador e o método solicitados
    var controller = $('meta[name=controller]').attr('content');
    var method = $('meta[name=method]').attr('content');
    var camelizedController = $.map(controller.split('_'), function(val) { return val.substr(0,1).toUpperCase() + val.substr(1) } ).join('');

    Application.Controller[camelizedController] &&
    Application.Controller[camelizedController]['init'] &&
    Application.Controller[camelizedController]['init'].call();

    Application.Controller[camelizedController] &&
    Application.Controller[camelizedController][method] &&
    Application.Controller[camelizedController][method].call();

    // Abre links com o rel external em novas janelas
    $("a[rel~='external']").click(function(){
        window.open($(this).attr('href'));
        return false;
    });
    
    // Animação links
    $('.link:not(.current)').hover(function(){
        $(this).stop('true','true').animate({ 
            color: '#8a8a8a',
            backgroundPosition: 'center bottom'
        }, 200);
    },function(){
        $(this).stop('true','true').animate({
            color: '#ffffff',
            backgroundPosition: 'center 50px'
        }, 200);
    });
    
    $('.dicas a, .outras_noticias a').hover(function(){
        $(this).stop('true','true').animate({ 
            backgroundColor: '#484848'
        }, 200);
        $(this).find('.resumo').stop('true','true').animate({ 
            color: '#fff'
        }, 200);
    },function(){
        $(this).stop('true','true').animate({ 
            backgroundColor: '#ffffff'
        }, 200);
        $(this).find('.resumo').stop('true','true').animate({ 
            color: '#343434'
        }, 200);
    });
    
    $('.conecte a').hover(function(){
        $(this).stop('true','true').animate({ 
            backgroundColor: '#484848',
            color: '#fff'
        }, 200);
    },function(){
        $(this).stop('true','true').animate({ 
            backgroundColor: '#ffffff',
            color: '#343434'
        }, 200);
    });
    
    $('.internas p a').hover(function(){
        $(this).stop('true','true').animate({ 
            color: '#959595'
        }, 200);
    },function(){
        $(this).stop('true','true').animate({ 
            color: '#343434'
        }, 200);
    });
    
    $('.banner272').hover(function() {
        $(this).find('.hover').fadeIn(200);
    }, function(){
        $(this).find('.hover').fadeOut(200);
    });
    
    // Animação submenu
    
    $('.sub').hover(function() {
        $(this).find('ul').stop(true,true).fadeIn(200);
    }, function() {
        $(this).find('ul').stop(true,true).fadeOut(200);
    });
    
    $('.noticias .img, .lista_colecao li, .novidades .img').hover(function() {
        $(this).find('.hover').stop(true,true).fadeIn(200);
    }, function() {
        $(this).find('.hover').stop(true,true).fadeOut(200);
    });
    
    // Animação botões
    $('.bt a, .bt input, .bt_voltar, .paginacao a').hover(function(){
        $(this).stop('true','true').animate({ color: '#929292' }, 200);
    },function(){
        $(this).stop('true','true').animate({ color: '#4b4b4b' }, 200);
    });
        
    $("a[rel^='colecao']").prettyPhoto({
        slideshow: false,
        overlay_gallery: false,
        opacity: 1
    });
    
    $("a[rel^='galeria']").prettyPhoto({
        slideshow: false,
        overlay_gallery: false,
        opacity: 1,
        theme: 'light_rounded'
    });
    
    $('.contato input').focus(function() {
        $(this).parent().removeClass('erro');
    });
    
    $("a[rel^='campanhas']").prettyPhoto({
        slideshow: false,
        overlay_gallery: false,
        opacity: 1,
        theme: 'light_rounded'
    });
    
    // Blogueiras
    $('#slides').slides({
        //preload: true,
        generateNextPrev: true
    });

    // share
    
    $('.send_wrap').hover(function() {
        $('.send_facebook').fadeIn(200);
    }, function(){
        $('.send_facebook').fadeOut(200);
    });
    
    // Processa a submissão de formulários Ajax
    $('form.generic_ajax').submit(function() {
        var $form = $(this);
        
        // realiza uma animação antes de começar a requisição ajax
        $.ajax({
            type: 'post',
            url: $form.attr('action'),
            data: $form.serialize(),
            beforeSend: function() {                  
                $form.find('.enviando').removeClass('hide');
                //$form.find('.error').addClass('hide');
                $form.find('.erro').removeClass('erro');
            },
            success: function() {
                $form.hide();
                $form.siblings('.msg_apresentacao').hide();
                $form.siblings('.msg_sucesso').show();
            },
            error: function(XMLHttpRequest) {
                $form.find('.enviando').addClass('hide');
                //$form.find('.error').removeClass('hide');
                if (XMLHttpRequest.status == '403') {
                    var errors = $.parseJSON(XMLHttpRequest.responseText);
                    for (var fieldName in errors) {
                        $form.find('[name='+fieldName+']').closest('p').addClass('erro');
                    }
                } else {
                    alert('Erro inesperado: falha na comunicação com o servidor. Por favor, tente novamente mais tarde.');
                }
            }
        });

        return false;
    });
});

