/**
 *
 * Arquivo de funções gerais do Site
 * Autor: BiTS - Business IT Solutions
 *
 */

//Funções que inicializam com o Site
$(document).ready(function(){

    //Plugin para aplicar Rollover nas Imagens
    jquery_hover_img.init();

	//Menu principal
	menu.init();
	
	//Validação de Formulários
	validacao.validacaoForms();
	
	//Plugin Accordion
	if($('.accordion_descricao').length > 0){
		accordion.init('.accordion_titulo a','.accordion_descricao');
	}

    //Adiciona o atributo title nas imagens baseado no alt
    $('img').each(function(){
        alt = $(this).attr('alt');
        $(this).attr('title',alt);
    });

    //Links para abrirem em uma página nova
    $('a[rel="externo"]').each(function(){
        $(this).attr('target','_blank');
    });
	
	//Links para imprimir a página
	$('a[rel="imprimir"]').click(function(){
		print();								  
	});
	
	//Máscara para Somente Número
	$('input[rel="numero"]').each(function(){
        $(this).keypress(function(e){			
            if(e.which!=8 && e.which!=0 && e.which!=46 && (e.which<48 || e.which>57)){
                return false;
            }
        });
    });
	
	//Lightbox
	$('a[@rel*=lightbox]').lightBox();

	//Listagem de Revistas
	if($('.jornal_mtg').size()){
		var i = 1;
		$('.jornal_mtg .edicoes').each(function(){
		   if(i % 3 == 0)
			   $(this).css('margin-right','0');
		   i++;
		});
	}

	//Listagem de Vídeos
	if($('.outros_videos').size()){
		var i = 1;
		$('.outros_videos').each(function(){
		   if(i % 3 == 0)
			   $(this).css('margin-right','0');
		   i++;
		});
	}

	//Listagem de Sala de Imprensa
	if($('.fotos_imprensa').size()){
		var i = 1;
		$('.fotos_imprensa').each(function(){
		   if(i % 3 == 0)
			   $(this).css('margin-right','0');
		   i++;
		});
	}	
	
	//Select de ano da Galeria
	if($('#f_ano').size()){
		$('#f_ano').change(function(){
			if($(this).val() != ''){
				alert($(this).val());
			}
		});
	}
	
	//Select de Dissídios
	if($('#dissidios_pdf').size()){
		$('#dissidios_pdf').change(function(){
			if($(this).val() != ''){
				openPopup($(this).val(),'target="_blank"');
			}
		});
	}
	
	//Navegação de Galeria
	if($('#imgs_galeria').size()){
		$('#imgs_galeria').jCarouselLite({
			btnNext : "#next",
			btnPrev : "#prev"
		});
		$('#imgs_galeria a').click(function(){
			alert($(this).attr('rel'));
		});
	}
	
	//Topo em Flash
	if($('#topo_flash').size()){		
		$('#topo_flash').flash({
			src		  : $('base').attr('href') + 'assets/site/swf/topo.swf', 
			width	  : 755,
			height	  : 270,
    		wmode	  : 'transparent',
			flashvars : {
				link  : $('base').attr('href')
			}
		});
	}
	
	//Radio Flash
	if($('#radio_topo').size()){
		$('#radio_topo').flash({
			src	   : $('base').attr('href') + 'assets/site/swf/radio_topo.swf', 
			width  : 204,
			height : 104,
    		wmode  : 'transparent'
		});
	}

	//jQueryCycle para a navegação de vídeos
    if($('#fade_video').size()){
		$('#fade_video').cycle({
			fx		: 'fade',
			timeout : 0,
			next	: '.botoes_video .proximo',
			prev	: '.botoes_video .anterior'
		});
	}
	
	//jQueryCycle para as Notícias randômicas
//	if($('#noticia_randomica').size()){
//		$('#noticia_randomica').cycle({
//			fx : 'fade'
//		});
//	}
	//JL jquery Cycle - noticias_destaque
        $(".notd_txt").each( function() { if ($(this).height() > 33) { $(this).children('h3').remove(); } });
        $(".notn_txt").each( function() { if ($(this).height() > 38) { $(this).children('h3').remove(); } });
	if($('#not_destaque').size()){
		$('#not_destaque').cycle({
                    fx:     'fade',
                    next:   '.notd_next',
                    timeout: 7000
		});
	}
//        if ($(".notd_txt").height > 20) {
//        }
	//Carrega a galeria de Metalúrgico em Foco
	if($('#select_ano').size()){
		x_get_ano(document.getElementById('x_ano').value);
		x_get_galeria();
	}

});

function modalConhecaMedico(n){
	jQuery.facebox({ ajax: $('base').attr('href') + 'index.php/atendimentos/medico/' + n });
}

function modalConhecaOdonto(){
	jQuery.facebox({ ajax: $('base').attr('href') + 'index.php/atendimentos/odontologico/' });
}

function modalReivindicacoes(id){
	jQuery.facebox({ ajax: $('base').attr('href') + 'index.php/chao_de_fabrica/reivindicacao/' + id });
}

function modalNossaHistoria(id){
	jQuery.facebox({ ajax: $('base').attr('href') + 'index.php/revistas/revista/' + id });
}

function modalComentario(id, tipo){
	jQuery.facebox({ ajax: $('base').attr('href') + 'index.php/'+tipo+'/comentar/' + id });
}

function modalComentarioMais(id, tipo){
	jQuery.facebox({ ajax: $('base').attr('href') + 'index.php/'+tipo+'/comentar_mais/' + id });
}

function x_video(id){
	jQuery.facebox({ ajax: $('base').attr('href') + 'index.php/videos/x_video/' + id });
}

function googleMaps(id){
	jQuery.facebox({ ajax: $('base').attr('href') + 'index.php/o_sindicato/x_maps/' + id });
}

function x_saiba_seus_direitos(){
	jQuery.facebox({ ajax: $('base').attr('href') + 'index.php/saiba_seus_direitos/x_saiba_seus_direitos/' });
}

valEmail = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;

indiceCombo = 0;

/**
 * Função que abre uma Popup
 *
 * @param url string
 * @param name string
 * @param w int
 * @param h int
 * @param scrolling int
 */
function openPopup(url,name,w,h,scrolling) {
	var leftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	var topPosition = (screen.height) ? (screen.height-h)/2 : 0;
	var settings = "height="+h+",width="+w+",top="+topPosition+",left="+leftPosition+",scrollbars="+scrolling+",resizable=0";
	return window.open(url,name,settings);
}

function abreRadio(){
	openPopup($('base').attr('href')+'index.php/radios/', 'Radio', 728, 395, 0);
}

function openFile(dir){	
	var value = $('dissidios_pdf').options[$('dissidios_pdf').value].selectedIndex;
	return false;
}

function validaFrmDuvida(){

	if($('#f_nome_pergunta').val() == ''){
		$('.erros').html('Campo nome não foi preenchido.').fadeIn();
		return false;
	}

	if($('#f_email_pergunta').val() == ''){
		$('.erros').html('Campo e-mail não foi preenchido.').fadeIn();
		return false;
	} else if (!valEmail.test($('#f_email_pergunta').val())) {
		$('.erros').html('E-mail inválido.').fadeIn();
		return false;
	}

	if($('#f_pergunta').val() == ''){
		$('.erros').html('Campo pergunta não foi preenchido.').fadeIn();
		return false;
	}

}

function validaFrmComentario(){

	if($('#f_nome_comentario').val() == ''){
		$('.erros').html('Campo nome não foi preenchido.').fadeIn();
		return false;
	}

	if($('#f_email_comentario').val() == ''){
		$('.erros').html('Campo e-mail não foi preenchido.').fadeIn();
		return false;
	} else if (!valEmail.test($('#f_email_comentario').val())) {
		$('.erros').html('E-mail inválido.').fadeIn();
		return false;
	}

	if($('#f_mensagem_comentario').val() == ''){
		$('.erros').html('Campo comentário não foi preenchido.').fadeIn();
		return false;
	}

}

function erroAjax(){
	jQuery.facebox('Ocorreu um erro. Desculpe-nos o transtorno.');
}

function x_galeria_mes(mes, elemento){

	//Troca o mês atual
	$('ul.calendario_mtg li.mes_selecionado').removeClass().removeAttr('class');
	$(elemento).parent().addClass('mes_selecionado');
	document.getElementById('x_mes').value				= mes;
	
	//Limpa a foto em tamanho grande
	document.getElementById('content_foto').innerHTML	= htmlGaleria('Selecione um ano.');
	
	//Limpa o título da galeria atual
	document.getElementById('titulo_foco').innerHTML	= '';
	
	//Limpa a listagem de galerias
	comboCarregando = '<select id="f_galeria" name="f_galeria" class="select_gal"><option value="">Selecione um ano</option></select>';
	document.getElementById('select_galeria').innerHTML = comboCarregando;
	
	//Limpa os thumbnails da galeria
	document.getElementById('thumb_foco').innerHTML		= '';

	//Limpa as notícias relacionadas
	document.getElementById('noticias').innerHTML		= '';
	
	//Ajax que pega os anos baseado no mês
	x_get_ano();

}

function x_galeria_ano(ano, elemento){
	
	//Atribui o ano escolhido
	document.getElementById('x_ano').value			  = ano;
	
	//Limpa a foto principal
	document.getElementById('content_foto').innerHTML = htmlGaleria('Selecione uma galeria.');

	//Limpa o título da galeria atual
	document.getElementById('titulo_foco').innerHTML  = '';

	//Limpa os thumbnails da galeria
	document.getElementById('thumb_foco').innerHTML   = '';
	
	//Ajax que traz a galeria escolhida
	x_get_galeria();
	
	mes = document.getElementById('x_mes').value;
	ano = document.getElementById('x_ano').value;

}

function x_get_ano(selected){
	
	//Posição no ano
	if(selected == undefined){
		selected = 0;
	}
	
	//Limpa a listagem de anos
	comboCarregando = '<select class="select_year" disabled><option value="">Carregando...</option></select>';
	document.getElementById('select_ano').innerHTML = comboCarregando;
	
	//Ajax para trazer os anos
	$.ajax({
		type: "POST",
		url: $('base').attr('href') + "index.php/metalurgicos_foco/x_get_ano",
		data: ({
			mes      : document.getElementById('x_mes').value,
			selected : selected
		}),
		success: function(resposta) {
			document.getElementById('select_ano').innerHTML = resposta;
		},
		error:   erroAjax,
		timeout: erroAjax
	});

}

function htmlGaleria(texto){

	html = '<div class="info_foco"> \
				<h3>'+texto+'</h3> \
			</div>';

	return html;

}

function x_get_galeria(){
	
	comboCarregando = '<select id="f_galeria" name="f_galeria" class="select_gal" disabled><option value="">Carregando...</option></select>';
	document.getElementById('select_galeria').innerHTML = comboCarregando;

	$.ajax({
		type: "POST",
		url: $('base').attr('href') + "index.php/metalurgicos_foco/x_get_galeria",
		data: ({
			mes : document.getElementById('x_mes').value,
			ano : document.getElementById('x_ano').value
		}),
		success: function(resposta) {
			document.getElementById('select_galeria').innerHTML = resposta;
			if(indiceCombo != 0){
				var i = 0;
				$('#f_galeria option').each(function(){
					if($(this).val() == indiceCombo){
						$('#f_galeria').selectedIndex = i;
					}
					i++;
				});
			}
		},
		error:   erroAjax,
		timeout: erroAjax
	});

}

function x_get_fotos(galeria){

	if(galeria != ''){
	
		//Limpa a foto em tamanho grande
		document.getElementById('content_foto').innerHTML = htmlGaleria('Carregando foto...');

		$.ajax({
			type	: "POST",
			url		: $('base').attr('href') + "index.php/metalurgicos_foco/x_get_foto_principal",
			data	: ({
				galeria : galeria
			}),
			success : function(resposta) {
				document.getElementById('content_foto').innerHTML = resposta;
			},
			error	:   erroAjax,
			timeout : erroAjax
		});

		$.ajax({
			type	: "POST",
			url		: $('base').attr('href') + "index.php/metalurgicos_foco/x_get_fotos",
			data	: ({
				galeria : galeria
			}),
			success : function(resposta) {

				document.getElementById('thumb_foco').innerHTML = resposta;
				
				var i = 0;
				$('#imgs_galeria li').each(function(){
					i++;
				});
				
				if(i > 3){
					$('#imgs_galeria').jCarouselLite({
						btnNext: "#next",
						btnPrev: "#prev"
					});
				}

			},
			error	: erroAjax,
			timeout : erroAjax
		});

		$.ajax({
			type	: "POST",
			url		: $('base').attr('href') + "index.php/metalurgicos_foco/x_get_galeria_unica",
			data	: ({
				galeria : galeria
			}),
			success : function(resposta) {

				document.getElementById('titulo_foco').innerHTML = resposta;

				$('body').append('<input type="hidden" id="value_titulo_foco" rel="'+document.getElementById('titulo_foco').innerHTML+'" />');

				if($('#value_titulo_foco[rel*="Campanha Salarial"]')){
					cat = $('#value_titulo_foco').attr('rel');
				}

			},
			error	: erroAjax,
			timeout : erroAjax
		});
		
		$.ajax({
			type	: "POST",
			url		: $('base').attr('href') + "index.php/noticias/noticias_foco",
			data	: ({
				mes : document.getElementById('x_mes').value,
				ano : document.getElementById('x_ano').value,
				cat : cat
			}),
			success : function(resposta) {
				document.getElementById('noticias').innerHTML = resposta;
			},
			error	: erroAjax,
			timeout : erroAjax
		});
		

	} else {
		
		document.getElementById('content_foto').innerHTML = htmlGaleria('Selecione uma galeria.');

		//Limpa os thumbnails da galeria
		document.getElementById('thumb_foco').innerHTML	  = '';

		//Limpa o título da galeria atual
		document.getElementById('titulo_foco').innerHTML  = '';

		//Limpa as notícias relacionadas
		document.getElementById('noticias').innerHTML	  = '';

	}

}

function x_muda_foto(id){

	//Limpa a foto em tamanho grande
	document.getElementById('content_foto').innerHTML = htmlGaleria('Carregando foto...');

	$.ajax({
		type	: "POST",
		url		: $('base').attr('href') + "index.php/metalurgicos_foco/x_muda_foto",
		data	: ({
			id  : id
		}),
		success : function(resposta) {
			document.getElementById('content_foto').innerHTML = resposta;
		},
		error	: erroAjax,
		timeout : erroAjax
	});

}
