function setBrowserClassName(){
	browserClass = $.browser.name;
	browserVersion = ($.browser.version).split(".")[0];
	if( browserClass == "msie") browserClass += browserVersion;
	$("body").addClass(browserClass);
}

function msg(txt){
	window.console ? console.log(txt) : alert(txt);
}

$.fn.debug = function(){
	return this.each(function(i){
		window.console ? console.log(this) : null;
	});
}

/* destacar um elemento
default: firstEvent:focus | activeClass:onFocus | lastEvent:blur
modo de usar:
	$("input:text, input:password, textarea").highlight();		
	$("ul li").highlight({ firstEvent:'mouseover', activeClass:'hover', lastEvent:'mouseout' });
*/
$.fn.highlight = function(settings){
	settings = jQuery.extend({
		activeClass:'onFocus',
		firstEvent:'focus',
		lastEvent:'blur'
	},settings);
		
	return $(this)
		.bind(settings.firstEvent,function(){
			$(this).addClass(settings.activeClass)
		})
		.bind(settings.lastEvent,function(){
			$(this).removeClass(settings.activeClass)
		});
}
	
/* kill default event 
usage: myfunction(e){ kill(e); doStuffs() }	
*/
kill = function(e) {
	if (!e) e = window.event;
	(e.stopPropagation) ? e.stopPropagation() : e.cancelBubble = true;
	(e.preventDefault) ? e.preventDefault() : e.returnValue = false;
	return false;
}
	
/* ir para uma pagina
usage: goto('index.php') */
goto = function(url){
	window.location = url;
}

function in_array (x, matriz){
	var txt = "¬" + matriz.join("¬") + "¬";
	var er = new RegExp ("¬" + x + "¬", "gim");
	return ( (txt.match (er)) ? true : false );
}
/* fim MÉTODOS GENÉRICOS */

/* inicio MÉTODOS ESPECÍFICOS */

function applyLayoutFix(){

	if($.browser.msie){
		//bordas arredondadas no container
		$("#wrapper").corner("20px");
		
		//bordas arredondadas nos itens do menu somente para o IE7 ou superior
		if($.browser.version.indexOf("6") == -1){
			$("#nav > ul > li > a").corner("top 5px");
		}
		
		//bordas arredondadas no bloco de ultimo login do dashboard
		//$(".ultimoLogin").corner("5px"); //position relative gera bug com submenu
		
		//bordas arredondadas no container de botões
		$(".form .botoes").corner("5px");
	}
	
	if($.browser.opera){
		$("#wrapper").corner("20px");
				
		$(".form .botoes").corner("5px");
	}
}

function initMainNavigation(){
	$("#nav > ul > li")
		.bind("mouseenter", function(){		
			$("> a", this).addClass("over");
			if($(this).children("ul").children().size() > 0)
				$(this).children("ul").fadeIn("fast");
				$(".msie6 select").css("visibility","hidden");
		})
		.bind("mouseleave", function(){
			$("> a", this).removeClass("over");
			$(this).children("ul").hide();
			$(".msie6 select").css("visibility","visible");
		});
}

function enableHighlights(){
	//mouse sobre as linhas de um grid
	$(".grid tr").highlight({ firstEvent:'mouseover', activeClass:'highlight', lastEvent:'mouseout' });
			
	//destacar inputs
	$(".input, textarea").highlight();
}

function enableFormsValidation(){	
	
	$(".formValidate").each(function(){
		$(this).bind("invalid-form.validate", function(e, validator){
			var errors = validator.numberOfInvalids();
			if (errors) {
				var message = errors == 1 ? 'Ooops! Falta preencher um campo obrigat&oacute;rio!' : 'Ooops! Falta preencher alguns campos obrigat&oacute;rios!';
				if($('#mensagemErro').size()){
					$("#mensagemErro").show().html(message);
					$.scrollTo("h2");
				}
			}else{
				$("#mensagemErro").hide();
			}
		});
	});
	
	$(".formValidate").each(function(){
		$(this).validate({
			onkeyup: false
		});
	});
	
}

function enableMasks(){
	$(".maskFone").mask("(99) 9999-9999");
	
	$(".maskCEP").mask("99999-999");
	
	$(".maskCPF").mask("999.999.999-99");
	
	$(".maskData").mask("99/99/9999");
	
	$(".maskHora").mask("99:99");
}

function enableTableSorter(nonSortablesColumns){
	nonSortablesColumns = nonSortablesColumns || null;
	$(".grid").tablesorter(nonSortablesColumns);
}

function enableConfirmations(){
	$(".confirmar").livequery(function(){
		$(this).each(function(){
			_msg = $(this).attr("pergunta");
			$(this)
				.click(function(event){						
					_url = $(this).attr("destino");
					goto(_url);
				})
				.confirm({
					timeout:10000,
					msg: _msg,
					wrapper: '<span class="msgConfirm"></span>' ,
					buttons: {
						wrapper: "<button></button>",
						cls: "skin4 button",
						ok: "Sim",
						cancel: "N&atilde;o",
						separator: ' '
					}
				});
		});		
	});
}

function fillEmptyGrid(){
	$(".grid").each(function(){
		if( $("td", this ).size() == 0 ){
			colspan = $("th", this).size();
			$(this).append("<tr><td colspan=\""+colspan+"\" class=\'textcenter\'>N&atilde;o h&aacute; registros</td></tr>");
		}
	});
}

function enableRichTextEditor(targetSelection, settings){
	$.fck.config = {path: 'fckeditor/' };
	$.fck.waitFor = 1;  
	$(targetSelection).fck( settings );  
}

function enableProcessIndicator(){
	$("<div>Processando...</div>").attr("id", "processIndicator").appendTo("body");

	$('#processIndicator')
		.ajaxStart(function(){
			$(this).show();
		})
		.ajaxStop(function(){
			$(this).hide();
		});
}

function ativarDesativar(button, tabela, componente, codigo){
	$.get("index.php",{
		option: 'com_ajax',
		task: 'ativarDesativar',
		format: 'raw',
		tabela: tabela,
		componente: componente,
		sq: codigo
	},function(retorno){
		retorno_partes = retorno.split("|");
		retorno_status = retorno_partes[0];
		retorno_msg	   = retorno_partes[1];
		
		switch(retorno_status){
			case '404':{
				//showErrorBox(retorno_msg);
				alert('Erro 404');
			} break;
			case '500':{
				//showErrorBox(retorno_msg);
				alert('Erro 500');
			} break;
			case '200':{
				$(button).val(retorno_msg);
			} break;
			default: {
				alert('Codigo do retorno nao informado');
			}
		}
	});
}

function desabilitarCampos(){
	for(i = 0; i < arguments.length; i++){
		$("."+arguments[i]).fadeOut().children("input").removeClass("required");
	}
}

function habilitarCampos(){
	for(i = 0; i < arguments.length; i++){
		$("."+arguments[i]).fadeIn().children("input").addClass("required");
	}
}

function enableTabs(){
	var tabContainers = $('div.tabs > div');
    
    $('div.tabs ul.tabNavigation a').click(function () {
        tabContainers.hide().filter(this.hash).fadeIn("fast");
        
        $('div.tabs ul.tabNavigation a').removeClass('selected');
        $(this).addClass('selected');
        
        return false;
    }).filter(':first').click();
}

function integrarCombos(combo1, combo2, url){
	$(combo1).chainSelect(combo2, url, null);
	
	$("option", combo2).livequery(function(){
		$(this).each(function(){
			$(this).val( $.trim( $(this).val() ) );
		});
	});
}

function transferirOption(from, to, forceSelected){
	forceSelected = forceSelected || false;
	option = $(from).find('option:selected');	
	if(option.val() != ""){		
		$(to).append( option.clone() );
		if(forceSelected) 
			$("option", to).attr("selected","selected");
		else
			$("option", from).attr("selected","selected");
		$(to).focus();
		$(to).blur();
		$(option).remove();
	}
}

function verificarEmailUsuario(input){
	novoEmail  = $(input).val();
	atualEmail = $(input).attr('email_atual');
	if(atualEmail != undefined && novoEmail != atualEmail){ //o atributo só existirá na tarefa de edição				
		$.get("index.php",{
				option: 'com_ajax',
				email: novoEmail,
				task: 'verificarEmailUsuario',
				format: 'raw'
			},function(retorno){
				if(retorno == 'false'){
					$("#inlineErrorEmail").show();
					$(input).focus();				
				}else
					$("#inlineErrorEmail").hide();
			}
		);
	}else{ //não houve alteração do Email mas se antes estava um nick errado, esconde o erro desnecessario
		$("#inlineErrorEmail").hide();
	}
}

function enableModals(){
	$(".modal").nyroModal();
}

function tratarItemSelecionado(item) {
	
	//if( item == null ) return alert("Nenhuma pessoa encontrada.");

	// if coming from an AJAX call, let's use the ID as the value
	//if( !!item.extra ) var sValue = item.extra[0];

	// otherwise, let's just display the value in the text box
	//else var sValue = item.selectValue; 
		
	$("#idVoluntario").val( item.extra[0] );
	$(".idVoluntario").html( item.extra[0] );
}
	
function onItemSelecionado(item){	
	tratarItemSelecionado(item);
}

function autocompletarNomeVoluntario(voluntarios){
	$("#voluntario")
		.autocomplete("index.php?option=com_ajax&task=autocompletarNomeVoluntario&format=raw",
		{
			delay: 1,
			minChars: 1 ,
			onItemSelect: onItemSelecionado,
			onFindValue: tratarItemSelecionado
			//autoFill: true
		})
		.keypress(function(e){
			// http://augustin.vidovic.org/pages/x30/Xmodmap
			charCode = e.keyCode;
			//if(charCode > 31 && (charCode < 65 || charCode > 90) && (charCode < 97 || charCode > 122) ) 
				//kill(e);
			if(charCode == 13)
				return false;
		})
		//.blur(function(){
			//if( $("#idVoluntario").val() < 1)
				//alert('Voluntario invalido');
		//});
	
	$("#formAgendar").keypress(function(e){
		if(e.keyCode == 13)
			kill(e);
	});
	
}

function adicionarParticipanteEvento(evento, valor_evento){
	sq_voluntarios = $("#formVoluntariosEvento-"+evento).serialize();
	
	$.get("index.php?"+sq_voluntarios,{
		option: 'com_ajax',
		format: 'raw',
		task: 'adicionarParticipantesEvento',
		sq_evento: evento,
		valor_evento: valor_evento
	},function(){
		transferirOption('#cmbVoluntarios-'+evento,'#cmbParticipantes-'+evento, true);
	});
}

function removerParticipanteEvento(evento, valor_evento){
	sq_voluntarios = $("#formParticipantesEvento-"+evento).serialize();
	
	$.get("index.php?"+sq_voluntarios,{
		option: 'com_ajax',
		format: 'raw',
		task: 'removerParticipantesEvento',
		sq_evento: evento,
		valor_evento: valor_evento
	},function(){
		transferirOption('#cmbParticipantes-'+evento,'#cmbVoluntarios-'+evento);
	});
}

/* fim MÉTODOS ESPECÍFICOS */
