// JavaScript Document
$(document).ready(function() {
/************************************************************************				   
	//CARROSSEL HOME
***********************************************************************/	
	//Set Default State of each portfolio piece

	$(".paging").show();

	$(".paging a:first").addClass("active");
	
	$(".boxConteudoPrincipal .sidebar .boxTwitter ul li p a:last").addClass("noBackground");

		

	//Get size of images, how many there are, then determin the size of the image reel.

	var imageWidth = $(".window").width();

	var imageSum = $(".image_reel img").size();

	var imageReelWidth = imageWidth * imageSum;

	

	//Adjust the image reel to its new size

	$(".image_reel").css({'width' : imageReelWidth});

	

	//Paging + Slider Function

	rotate = function(){	

		var triggerID = $active.attr("rel") - 1; //Get number of times to slide

		var image_reelPosition = triggerID * imageWidth; //Determines the distance the image reel needs to slide



		$(".paging a").removeClass('active'); //Remove all active class

		$active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)

		

		//Slider Animation

		$(".image_reel").animate({ 

			left: -image_reelPosition

		}, 500 );

		

	}; 
	//Rotation + Timing Event

	rotateSwitch = function(){		

		play = setInterval(function(){ //Set timer - this will repeat itself every 3 seconds

			$active = $('.paging a.active').next();

			if ( $active.length === 0) { //If paging reaches the end...

				$active = $('.paging a:first'); //go back to first

			}

			rotate(); //Trigger the paging and slider function

		}, 7000); //Timer speed in milliseconds (3 seconds)

	};
	rotateSwitch(); //Run function on launch
	//On Hover

	$(".image_reel a").hover(function() {

		clearInterval(play); //Stop the rotation

	}, function() {

		rotateSwitch(); //Resume rotation

	});	
	//On Click

	$(".paging a").click(function() {	

		$active = $(this); //Activate the clicked paging

		//Reset Timer

		clearInterval(play); //Stop the rotation

		rotate(); //Trigger rotation immediately

		rotateSwitch(); // Resume rotation

		return false; //Prevent browser jump to link anchor

	});	
/***********************************************************************				   
	/CARROSSEL HOME
************************************************************************/

	/*
	//resolucao				   
    var resolucaoAtual = screen.width;
    if (screen.width >= 1024) {
        $("html").css('overflow-x', 'hidden');
    }
	*/
	
	//FUNÇÕES
	limpaInput()
	link()	
	AbreMenulateral()
	controlerFontSize('.boxLupa','.boxConteudoPrincipal',4,'.fixedSize');	
	controleAltura();
	$('.calendario').carrossel(1);
	$('.BoxMiniCarrossel').carrossel(4);
	clickMiniCarrossel();
	LightBoxCet();
	AbreMenuTransparencia('.boxItemPerguntas li', 'p');
	AbreMenuTransparencia2('.boxItemListDemonstrativos', 'ul');
//	trocaAba(0);
	controleAltura2();
	stylePag();	
	
	//Mascara formulario
	//$('.campRG input').mask('99.999.999-9');
	
	$('.campNum input').bind('keyup blur',function(){
	    $(this).val($(this).val().replace(/[a-zA-Z\s]+/gi, ''));
    });    
    
    //$('.campCpf input').mask('999999999-99'); 
	$('.campNasc input').mask('99/99/9999');
	//$('.campTel input').mask('(99)9999-9999');
	$('.boxItensResultado ul li input').mask('99.999.999/9999-99');
	$('.boxItensResultado ul li input').keypress(function(){
		    return false;	  
    });
	
	caixaBusca();
	
	//Para paginas com GoogleMaps
	flashMap('MapaCentro','http://maps.google.com/maps/ms?ie=UTF8&hl=pt-BR&msa=0&msid=110889405027558679688.000494df52ac2ac51b627&source=embed&ll=-23.562728,-46.662369&spn=0.220288,0.291824&z=11&output=embed');
	flashMap('MapaIbirapuera','http://maps.google.com/maps/ms?ie=UTF8&hl=pt-BR&msa=0&msid=110889405027558679688.000490c8f6930ead534b4&t=k&source=embed&ll=-23.587941,-46.658163&spn=0.013765,0.024676&output=embed');
	flashMap('mapaZmrc','http://maps.google.com/maps/ms?ie=UTF8&hl=pt-BR&msa=0&msid=110889405027558679688.000494daf8f0265841e0d&source=embed&ll=-23.575316,-46.660995&spn=0.204534,0.222816&output=embed');
		
	//Pagina Programa de estagio
	flashMap('boxCadastre','http://cetsp1.cetsp.com.br/estagiario/ficha.asp?opcao=0');
	flashMap('boxCurriculo','http://cetsp1.cetsp.com.br/estagiario/login.asp');
	flashMap('boxInformacoes','http://cetsp1.cetsp.com.br/estagiario/default.asp');
	
	
	titPaginas();
	
	
});

function getFlashMovieObject(movieName) {
	if (window.document[movieName]) {
		return window.document[movieName];
	}
	if (navigator.appName.indexOf("Microsoft Internet")==-1) {
		if (document.embeds && document.embeds[movieName]) return document.embeds[movieName]; 
	}
	else {
		return document.getElementById(movieName);
	}
}

function toggle(i) {
	if($(i).is(":hidden")) $(i).show();
	else $(i).hide();
}

 //Funcões Básicas

/* Limpa o Input ao clicar */
function limpaInput() {
    $('input:text').focus(function() {
        if ($(this).val() == $(this).attr("title")) {
            $(this).val("");
            if ($(this).hasClass("password")) {
                $(this).attr("type", "password");
            }
            $(this).bind("blur", function() {
                if ($(this).val() == '') {
                    if ($(this).hasClass("password")) {
                        $(this).attr("type", "text");
                    }
                    $(this).val($(this).attr("title"));
                }
            });
        }
    });
}	

function link() {
	 /* Target hack - para Strict */
    $('a.blank').click(function() {
        $(this).attr("target", "_blank");
    });

    $('a.self').click(function() {
        $(this).attr("target", "_self");
    });

    $('a.parent').click(function() {
        $(this).attr("target", "_parent");
    });
}

//Abre e fecha Menu Esquerdo
function AbreMenulateral(){
	if($('.boxMenuLateral').find('.active').length == 1){
		$('.active').next().slideDown();	
	}
	$('.boxMenuLateral h2').click(function(){
		if($(this).next('ul').length == 1){
		$('.boxMenuLateral').find('ul:not(:animated)').slideUp('slow');
		$(this).next().slideDown();	
			return false
		}else if($(this).next('ul').length == 0){
			return true;
		}
	});
}

//Opções Abre e fecha 
function AbreMenuTransparencia(obj, target){
	obj = $(obj);
	obj.eq(0).find(target).show()
	.end().find('h3').addClass('active');
	obj.find('table').hide();
	obj.find('h3').click(function(){
		if($(this).hasClass('active')){
			return false;
		}
		obj.find(target+':not(:animated)').slideUp('slow');
		obj.find('h3').removeClass('active');
		obj.find('ul').hide();
		obj.find('table').hide();
		$(this).addClass('active');
		$(this).closest('li').find('p').slideDown();
		$(this).closest('li').find('ul').slideDown();
		$(this).closest('li').find('table').slideDown();		
		return false		
	});
}

//Opções Abre e fecha 
function AbreMenuTransparencia2(obj, target){
	obj = $(obj);
	obj.eq(0).find(target).show()
	.end().find('h3').addClass('active');
	obj.find('h3').click(function(){
		if($(this).hasClass('active')){
			return false;
		}
		obj.find(target+':not(:animated)').slideUp('slow');
		obj.find('h3').removeClass('active');
		obj.find('ul').hide();
		$(this).addClass('active');
		$(this).next('ul').slideDown();
		return false		
	});
}

//Aumenta e diminui fonte conteudo
function controlerFontSize(obj,container,multipleSize,dontChangeMe){
	//inicializo os valores
	var lastSize = 0;
	var size = 0;

	$(obj).find('a').click(function(){
		//guardo todos os objetos da lista
		var objs = $(this).parents(obj).find(this.tagName);
		//guardo o indice do intem selecionado
		var actualIndex = $(objs).index(this);
		//guardo na variavel size o tamanho selecionado
		for(var i=0; i<objs.length; i++){
				if(actualIndex > $(objs).index($(objs).eq(i)))
					size = size + multipleSize;
		}

		//altero o valor do font size subtraindo o ultimo valor
		$(container).find('*:not(dontChangeMe *)').animate({
			fontSize: '+=' + (size - lastSize) + 'px'
		},'fast')

		//atualizo as variaveis
		lastSize = size;
		size = 0;
	})
}

//Controle de altura h2 
function controleAltura(){
	var maiorAlturaBox = 0;
	var maiorAlturaH2 = 0;
	var alturaBox;
	var alturaH2;
	$('.boxItemTec').each(function(){
		alturaBox = $(this).height();
		alturaH2 = $(this).find('h2').height();
		if( alturaH2 > maiorAlturaH2) {
			maiorAlturaH2 = alturaH2;	
		}
		if( alturaBox > maiorAlturaBox) {
			maiorAlturaBox = alturaBox;	
		}
	}).height(maiorAlturaBox).find('h2').height(maiorAlturaH2);
}

//Controle de altura Conteudo Educação e segurança 
function controleAltura2(){
	var maiorAlturaLi = 0;
	var alturaLi;
	$('.boxConsulta ul li').each(function(){
		alturaLi = $(this).height();
		if( alturaLi > maiorAlturaLi) {
			maiorAlturaLi = alturaLi;	
		}			
	}).height(maiorAlturaLi);
	$('.boxConsulta ul li')
}

//carrossel 
$.fn.carrossel = function (view) {
    if (!view) {
        view = 5;
    }
    else {
        view = parseInt(view);
        if (isNaN(view))
            return false;
    }

    $(this).each(function () {
        var carrossel = $(this);
        var list = carrossel.find('ul');
        var itemWidth = list.find('li:first').outerWidth();
        var countItens = list.children().length;
        var controlButtons = carrossel.find('.anterior,.proximo');
        var minItemView = 1;
        var maxItemView;
        var countNextRange = view;
        var button;
        var disable;

        if (countItens <= view) {
            controlButtons.addClass('disable');
        }
        else {
            carrossel.find('.anterior').addClass('disable');
        }

        controlButtons.bind('click', function () {
            button = $(this);
            disable = false;
            maxItemView = minItemView + view - 1;

            if (button.hasClass('disable') || list.is(':animated'))
                return false;

            controlButtons.removeClass('disable');

            if (button.hasClass('proximo')) {
                if ((maxItemView + view) <= countItens) {
                    countNextRange = view;
                    minItemView = minItemView + view;
                }
                else {
                    countNextRange = countItens - maxItemView;
                    minItemView = countItens - view + 1;
                }

                disable = (minItemView >= countItens - view + 1);
                direction = '-=';
            }
            else {
                if ((minItemView - view) >= view) {
                    countNextRange = view;
                    minItemView = minItemView - view;
                }
                else {
                    if (minItemView - view > 0) {
                        countNextRange = view;
                        minItemView = minItemView - view;
                    }
                    else {
                        countNextRange = minItemView - 1;
                        minItemView = 1;
                    }
                }

                disable = (minItemView <= 1);
                direction = '+=';
            }

            list.stop().animate({
                marginLeft: direction + (itemWidth * countNextRange)
            }, 500);

            if (disable)
                button.addClass('disable');

            return false;
        });
    });
}

//Click carrossel
function clickMiniCarrossel() {
	$('.boxImgGr img:first').show()
	$('.BoxMiniCarrossel ul li a').click(function(){
		var imgThumb = $(this).attr('href');
		$('.boxImgGr').find('img').hide();
		$('.boxImgGr').find('img'+imgThumb).show();		
		//alert($('.imgConteudo').find('.imgGr').length);
		return false
	});
}


//LightBox
function LightBoxCet(){    
	$('.activeLight').live('click',function(e){
	    thisClick = this;
	    if($(e.target).is('.boxLight,.boxLight *')) {
			return;
		}
		$('<div />').appendTo('body').addClass('boxFundo').css({
			width : $(document).width(),	
			height : $(document).height(),
			opacity : 0.65
		});		
		if($(this).find('.boxLight').length == 1){ 
		   /* if($(this).find('.topGr').length == 1){
		        $('.boxLight').css('width','828px');		    
		    }*/
		    
            if($(this).find('iframe').attr('src')=="http://www.cetsp.com.br/internew/informativo/selo/selo.html")
                $(this).find('.boxLight').addClass('boxLight2');
            else if($(this).find('iframe').attr('src')=="/util/swf/apresenta.swf")
                $(this).find('.boxLight').addClass('boxLight3');
		    
			$(this).find('.boxLight').fadeIn(1000, function(){
				$('iframe').show();
			}).css({
				'top' : ($(window).height() / 2) - $(this).find('div:first').height()/2,
				'left' : ($(window).width() / 2) - $(this).find('div:first').width()/2 
			});
			$(window).scrollTo(0,500);			
		}else{
			$('.boxFundo').hide();	
			return false;
		}
		fechaLight();
		return false;
	});
}

//Fecha LightBox
function fechaLight(){
	$('.boxLight .btFechar, .boxFundo').click(function(){
		$(this).closest('.boxLight').fadeOut(1000, function(){
			$('iframe').hide()		
		});
		$('.boxFundo').fadeOut(1000, function(){
			$('iframe').hide()		
		});
		$('.boxLight').fadeOut(1000);
		return false;
	})		
}

//Troca abas e conteudo
function trocaAba(index){
	index = parseInt(index);
	if(isNaN(index))
		index = 0;
	
	var contents = $('.contAgenda .boxItemTransito');
	var abas = $('.listMenuAba li a');
	var classes;
	var linkIndex;
	
	$(abas.eq(index).attr('href')).show();
	
	$('.listMenuAba').addClass('aba'+index);
	
	abas.click(function(){
		
		contents.slideUp(1000);
		
		linkIndex = abas.index($(this));
		
		$(this).closest('.listMenuAba')
		.removeClass(function() {
			classes = '';
			abas.each(function(i){
				classes += ' aba' + i;
			});
			return classes;
		})
		.addClass('aba'+linkIndex);

		$($(this).attr('href')).slideDown(1000);
		
		return false;
	});
}


//Estilizar Paginação
function stylePag(){
    $('.boxPaginacao').find('.separator:last').removeClass('separator');
    $('.boxPaginacao a').live('click',function(){
       setTimeout(function(){
            $('.boxPaginacao').find('.separator:last').removeClass('separator');    
        },50)
    });    
}

//Busca de Notícias
function BuscarNoticias(Ano, Mes) {
    if (Ano > 0) {
        if (Mes > 0) {
            window.location = '/' + Ano + '/' + Mes + '/noticias.aspx';
        }
        else
            window.location = '/' + Ano + '/noticias.aspx';        
    }
    else {
        window.location = '/noticias.aspx';
    }
}

//Caixa de busca
function caixaBusca(){
	$('#txtBusca').keyup(function(e) {
        if (e.keyCode == 13) {
            Buscar($('#txtBusca').val());
        }
    });
    $('.buscar').click(function() {
        Buscar($('#txtBusca').val());
    });
}

function Buscar(valor) {
    if (valor.length == 0) {
        alert('Preencha sua busca');
    }
    else {
        window.location.href = '/resultado-de-busca.aspx?q=' + valor;
    }
}
//Função incluir Mapa
function flashMap(param, mapa ){
   // alert($('#Mapa').length);   
   if($('#' + param).length==1){
		$('#' + param).append(		
			$('<iframe />').attr({
				'src': mapa,
				'width':'750px',
				'height':'650px'				
			})				   			
		)
	}else{
		return false
	}	
}


//função Titilos das paginas
function titPaginas(){
    var urlBreadcrumb = ($('.boxUrl li').length) ? ' - ' + $('.boxUrl li:eq(1)').text() : '';
	document.title = 'CET - Companhia de Engenharia de Trafego' + urlBreadcrumb;
}












