$().ready( function() {
	//menu();
	confirmacao();
	printing();
	target();
	zebra();
	ieFlickerFix();

	$(".lightbox").lightbox();
	
	//masks();

	search();
	languages();

	newsletter();
	webmail();

	$("#newsletter").bind("submit", validacaoForm);
});

//////////////////////////////////////////////////////////

var getVars,tGet=[];
getVars=document.location.search.substr(1);
getVars=getVars.split('&').join('%26').split('%26');

var t,n,tmpV; for (t=0,n=getVars.length;t<n;t++) {
  tmpV=getVars[t].split('='); tGet[tmpV[0]]=tmpV[1];
}

//////////////////////////////////////////////////////////

function newsletter(){
	$('input[name=newsletter_name]').focus(function() {
		if( 'Nome Completo' == $(this).val() ) $(this).val('');	
		if( 'Full Name' == $(this).val() ) $(this).val('');	
		if( 'Nombre Completo' == $(this).val() ) $(this).val('');	
	});
	$('input[name=newsletter_name]').blur(function () {
         if( '' == $(this).val() && 'pt' == tGet['language'] ) $(this).val('Nome Completo');
		 if( '' == $(this).val() && 'en' == tGet['language'] ) $(this).val('Full Name');
		 if( '' == $(this).val() && 'es' == tGet['language'] ) $(this).val('Nombre Completo');
    });
	
	$('input[name=newsletter_email]').focus(function() {
		if( 'E-mail' == $(this).val() ) $(this).val('');
	});
	$('input[name=newsletter_email]').blur(function () {
         if( '' == $(this).val() ) $(this).val('E-mail');
    });
}

function webmail(){
	$('input[name=horde_user]').focus(function() {
		if( 'usuário' == $(this).val() ) $(this).val('');
		if( 'user' == $(this).val() ) $(this).val('');
		if( 'usuario' == $(this).val() ) $(this).val('');
	});
	$('input[name=horde_user]').blur(function () {
        if( '' == $(this).val() && 'pt' == tGet['language'] ) $(this).val('usuário');
		if( '' == $(this).val() && 'en' == tGet['language'] ) $(this).val('user');
		if( '' == $(this).val() && 'es' == tGet['language'] ) $(this).val('usuario');
    });
	
	$('input[name=horde_pass]').focus(function() {
		if( 'senha' == $(this).val() ) {
			$(this).replaceWith('<input class="pass" id="senha" name="horde_pass" type="password" value="" />');
			$('input[name=horde_pass]').focus();
		}
		if( 'pass' == $(this).val() ) {
			$(this).replaceWith('<input class="pass" id="senha" name="horde_pass" type="password" value="" />');
			$('input[name=horde_pass]').focus();
		}
		if( 'contraseña' == $(this).val() ) {
			$(this).replaceWith('<input class="pass" id="senha" name="horde_pass" type="password" value="" />');
			$('input[name=horde_pass]').focus();
		}
	});

}

/////////////////////////////* Form Validation */////////////////////////////

/*/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	OPÇÕES DE VERIFICAÇÃO DO CAMPO:
	nomecompleto	 » verifica se o campo contém mais de 7 caracteres, se contém espaço e se é fake ( "888 888" ).
	telefone		 » verifica se o campo contém mais de 8 caracteres, se contém somente números e se é fake ( "(88) 8888.8888" ).
	email			 » verifica se o campo contém caracteres como "@" e "." e a posição deles, e se é fake ( "aaa@aaa.aaa" ).
	cidade			 » verifica se o campo contém mais de 3 caracteres.
	mensagem		 » verifica se o campo contém mais de 20 caracteres.
	cep				 » verifica se o campo é um cep válido ( "88888-888" ).
	cpf_cnpj		 » verifica se o campo é um cpf/cnpj válido.
	data			 » verifica se o campo é uma data válida ( "dd/mm/aaaa" ).
	numero			 » verifica se o campo contém mais de 5 caracteres, se contém somente números e se é fake ( "(88) 8888.8888" ).
	selected		 » verifica se o campo foi ou não selecionado.
	login			 » verifica se o campo não contém espaços, se contém mais de 3 caracteres, se não é composto apenas por números e se é fake.
	pass			 » verifica se o campo não contém espaços, se contém mais de 6 caracteres e se é fake.
	radio			 » verifica se algum dos campos "radio" com o mesmo "name" foi marcado.
	checkbox		 » verifica se algum dos campos "checkbox" com o mesmo "name" foi marcado.
	file			 » verifica se o campo contém a extensão indicada e se contém mais de 5 caracteres ( ex: ["#imagem", "Imagem", "imagem", "jpg|jpeg|gif|png"] ).

	MODELOS DE CAMPO COM VERIFICAÇÃO DE ARQUIVOS:
	["#level_imagem", "Imagem", "file", "jpg|jpeg|gif|png"]

	MODELOS DE CAMPO COM VERIFICAÇÃO DE E-MAIL:
	["#level_name", "Nome", "email"]

	MODELOS DE CAMPO SEM VERIFICAÇÃO, PORÉM OBRIGATÓRIO:
	["#level_name", "Nome"]
	
	TODOS OS CAMPOS DEVEM ESTAR DENTRO DE UMA ARRAY, SEPARADOS POR VÍRGULA:
	campos = new Array(
	["#level_name", "Nome"],
	["#level_description", "Descrição"]
	);

	MODELOS DE CAMPO COM VERIFICAÇÃO SE PREENCHIDO:
	para fazer com que um campo seja verificado apenas se ele estiver preenchido, adicione "@" antes do tipo de verificação que você deseja usar.
	Ex: ["#level_name", "Nome", "@email"] OU ["#level_imagem", "Imagem", "@file", "jpg|jpeg|gif|png"]

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////*/

campos = new Array(
["#newsletter_name", "Nome", "nomecompleto"],
["#newsletter_email", "E-Mail", "email"]
);

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function languages(){
	
	//$('#languages').css("top","-60px");
	$("#languages").animate( { top:"-60px" }, 500 );

	$('#languages a').bind('click', function() {
		
		if( '-60px' == $('#languages').css("top") ) $("#languages").animate( { top:"0" }, 500 );
		else $("#languages").animate( { top:"-60px" }, 500 );
		
	});

}

function search(){
	$('input[name=search]').bind('click', function() {
		if( 'Buscar no Site' == $(this).val() ) $(this).val('');	
		if( 'Search Site' == $(this).val() ) $(this).val('');	
		if( 'Búsqueda en el sitio' == $(this).val() ) $(this).val('');	
	});
}

function confirmacao() {
	$('a.confirmacao').bind('click', function() {
		var title = $(this).attr('title');
		
		if (!confirm(title)) {
			return false;
		}
		else return true;

		return false;
	});
}


function printing() {
	$('.printit').click( function() {
		window.print();
	});
}


function target() {
	$("a[rel$='external'], .external").each( function(){
		$(this).attr('target','_blank');
		$(this).attr('title', $(this).attr('title')+' (este link abre em nova janela)');
	});
}


function zebra() {
	$('table:not(.nozebra) tr:nth-child(odd)').addClass('par');
}


function ieFlickerFix() {
	try {
	  document.execCommand("BackgroundImageCache", false, true);
	} catch(err) {}
}


function masks() {

	$('.mask-date').mask('99/99/9999',{placeholder:' '});
	
	$('.mask-phone').mask('(99) 9999-9999',{placeholder:' '});
	
	$(".mask-cep").mask('99999-999',{placeholder:' '});

	//$('.mask-cpf').mask('999.999.999-99',{placeholder:" "});
	//$('.mask-cnpj').mask('99.999.999/9999-99',{placeholder:" "});
	$('.mask-rg').mask('999.999.9999',{placeholder:" "});

	$('.mask-inscr').mask('999/9999999',{placeholder:" "});
}


function affectedFields(form,el) {
	var classname = 'affected';
	$(form+' *').each( function() {
		if (el!='') {
			if ($(this).attr('id')==el) {
				$(this).focus().addClass(classname);
			} else {
				$(this).removeClass(classname);
			}
		} else {
			$(this).removeClass(classname);
			$(form).resetForm();
		}
	});
	return false;
}


function get(el) {
  return document.getElementById(el);
}


function limiter(el, max) {
	$(el).bind('keypress', function() {
		var valor = $(this).attr('value');
		valor = valor.substr(0,max);
		if (valor > max) {
			$(this).attr('value',valor);
		}
	});
}

////////////////// MENU ///////////////////////////////////////////////////////////////////////////

/* Preload Menu */

/*
var preloaded = new Array();
function preload_images() {
    for (var i = 0; i < arguments.length; i++){
		preloaded[i] = document.createElement('img');
		preloaded[i].setAttribute('src',arguments[i]);
    };
};

preload_images(
	'themes/default/images/menu_links.gif',
	'themes/default/images/menu_hover_cidade.gif',
	'themes/default/images/menu_hover_governo.gif',
	'themes/default/images/menu_hover_secretarias.gif',
	'themes/default/images/menu_hover_cultura.gif',
	'themes/default/images/menu_hover_polo.gif',
	'themes/default/images/menu_hover_publicacoes.gif',
	'themes/default/images/menu_seta.gif'
);
*/


/* Menu */

function menu() {
	
	$('#menu>ul>li').hover(
		
		function start() {

			// aplica o hover, aplicando a classe, e procura um submenu
			$(this).addClass('affected').find('ul.sub').each( function() {
				
				/*
				$(this).animate({
					opacity: 0
				}, 0 );
				*/
				
				// iniciando o hover...
				$(this).hover( 
					
					function() {

						/*
						$(this).animate({
							opacity: 1
						}, 250 );
						*/

						// primeiro exibe o submenu através da classe, e então busca os itens da lista
						$(this).addClass('affected').find('>li').each( function() {

							// se os sub itens estiverem em hover, então...
							$(this).hover(

								function() {

									/////////////////////////////////////////////////////////////////////////////////////////////////
									// aplica o hover, aplicando a classe, e procura um submenu
									$(this).addClass('affected').find('ul.sub2').each( function() {
										
										// iniciando o hover...
										$(this).hover( 
											
											function() {

												// primeiro exibe o submenu através da classe, e então busca as itens da lista
												$(this).addClass('affected').find('>li').each( function() {

													// se os sub itens estiverem em hover, então...
													$(this).hover(

														function() {

															// ... vê se ele item um submenu derivado e exibe
															$(this).find('ul').each( function() {
																$(this).css('display','block');
															});								
															
														},

														function() {

															$(this).find('ul').each( function() {
																$(this).css('display','none');
															});

														}

													);
												
												});
												
											}, 
											
											function() {
												
											}
										
										);
									
									});
									///////////////////////////////////////////////////////////////////////////////////////////////

									// ... vê se ele item um submenu derivado e exibe
									$(this).find('ul').each( function() {
										$(this).css('display','block');
									});
									
								},

								function() {

									$(this).find('ul').each( function() {
										$(this).css('display','none');
									});

								}

							);
						
						});
						
					}, 
					
					function() {
						
						/*
						$(this).animate({
							opacity: 0
						}, 250 );
						*/
					}
				
				);
			
			});
		
		},
		
		// faz alguma coisa quando o menu sair de hover
		function end() {
			$(this).removeClass('affected');
		}
	
	);
	return false;
}

///////////////////////////////////////////////////////////////////////////