/**
 * TikiCMS
 * Copyright (C) 2009, Tiki Web Inteligente Ltda.
 * @requires jQuery 1.3.2 or latter
 *
 * $Id: application.js 295 2010-11-29 18:15:34Z leandro $
 */

// 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;
    });
    
    if ( $.browser.msie ) {        
        $('#nav > li').hover(function(){
            if( $(this).is('.empresa') ) {
                $(this).children('.sub').css('left','-5px');
            } else if ( $(this).is('.contato') ) {
                $(this).children('.sub').css({
                    right: '-5px',
                    left: 'auto'
                });
            } else {
                $(this).children('.sub').css('left','-16px');
            }
        }, function(){
            $(this).children('.sub').css('left','-9999px');
        });
    }
    
    else {
        // Efeito hover menu
        $('#nav > li').hover(function(){
            $(this).children('.link_glow').stop('true','true').fadeIn(250);
            $(this).children('.sub').stop('true','true').fadeIn(250);
        }, function(){
            $(this).children('.link_glow').stop('true','true').fadeOut(250);
            $(this).children('.sub').stop('true','true').fadeOut(250);
        });
        
        // Abre submenu
        
        // Efeito submenu hover
        $('#nav .sub a').hover(function(){
            $(this).stop('true','true').animate({ color: '#6d9ae4' },250)
        },function(){
            $(this).stop('true','true').animate({ color: '#1f2d60' },250)
        });
        
        
    
        // Efeito hover botões
        $('.bt_a').not('.current').hover(function(){
            $(this).children().stop('true','true').animate({ opacity: 1}, 250);                         
        }, function(){
            $(this).children().stop('true','true').animate({ opacity: 0}, 250);
        });
        
        // Efeito hover
        $('.hover_a').hover(function(){
            $(this).find('.hover').stop('true','true').animate({ opacity: 1}, 250);                         
        }, function(){
            $(this).find('.hover').stop('true','true').animate({ opacity: 0}, 250);
        });
        
        
    };
    
    // Efeito login SIM
    $('.nav_mini .has_sub > a').click(function(){
        $(this).siblings('.form_sub').show();
        
        return false;
    });    
    $('.nav_mini .tit').click(function(){
        $(this).parent('.form_sub').hide();
        
        return false;
    });
    //Fecha o login SIM quando clica fora dele
    $('body').mouseup(function(e){
        var $target = $(e.target);
        // se o target é filho do seletor
        if ($target.parents('.nav_mini li.has_sub').length == 1) return false;																			  
        $(this).find('.form_sub').hide();
    });
    
    
    
    
    // Submenu do rodapé
    $('#footer .has_sub').hover(function(){
        $submenu = $(this).children('.sub');
        var largura = $submenu.width();
        
        $submenu.css({
            left: '50%',
            marginLeft : -(largura + 16) / 2
        });        
    },function(){
        $submenu.css({ left: '-9999px' });
    });
    
    $('form#post_envio_senha').submit(function() {
        var $form = $(this);
        var email = $form.find('[name=email]').val();
        if (!email) return false;

        $.ajax({
            type: 'post',
            url: $form.attr('action'),
            data: $form.serialize(),
            beforeSend: function() {
                $form.find('span.error').hide();
                $form.find('p.error').removeClass('error');
                $form.find('.message_enviando').show();
            },
            success: function() {
                $form.hide();
                $('.mensagem.senha_enviada').show();
            },
            error: function(XMLHttpRequest) {
                $form.find('.message_enviando').hide();
                if (XMLHttpRequest.status == '403') {
                    $form.find('[name=email]').closest('p').addClass('error').find('span.error').show();
                } else {
                    alert('Erro inesperado: sua senha não foi enviada. Por favor, tente novamente mais tarde.');
                }
            }
        });

        return false;
    });

    $('.esqueci a').click(function() {
        $('.flutuante_esqueci').lightbox_me({
            centered: true
        });
        return false;
    });

	// Mudança da linguagem do site
    $('ul.idiomas a').click(function() {

        var lang = $(this).attr('id').split('_').pop();
        var currLang = $('ul.idiomas .curr_lang').text();
        var url = window.location.href;

		if (lang && currLang && currLang != lang) {
			var redirectTo = '';
			var regEx = new RegExp("/" + currLang + "/");
			if (url.match(regEx)) {
				redirectTo = url.replace(regEx, "/"+lang+"/");
			} else {
				redirectTo = url + "/" + lang;
			}
			window.location = redirectTo;
			return false;
		}		
    });    
});

