/**
* Arquivo responsavel por possuir todos os metodos em javascript Genericos para framework SGI
* @autor Jefferson Otoni Lima
* @since  16/12/2010
*/

/*@Global var*/
var iframe_counters = 0 ; 
var content_counter	= 0 ;
var form_object 	= 0 ;
/**
* @abstract Função para Criar uma div dinâmicamente. Essa div vai receber um determinado valor.
* data = [String] pode ser um texto como tambêm pode ser o conteúdo trazido do Ajax;
* pw/ph = [Numeric] sendo um valor flutuante menor que 1, o código entende que o tamanho da div deve ser
 x porcento da tela, tanto em altura quanto e largura.;scroll = [String] um parâmetro que estou tentando
 implementar que automaticamente o código sabe quando o conteúdo da div passou do tamanho estabelecido
 e logo cria um scroll.
* @since 13/08/2010
*/
SgiCreateContent = function(data,pw,ph,scroll,ad_pos_top){
	
	if(ad_pos_top){
		ad_pos_top = parseInt(ad_pos_top);
	}else{
		ad_pos_top = 175 ; 
	}
	
	id = 'sgi_content_div_'+content_counter;content_counter++;
	$(document.body).append('<div class="SgiContent" id="'+id+'"><div class="close"></div><div class="content"></div></div>');
	$('#'+id+' > .content').html(data);
	
	if(pw != 'auto' && ph != 'auto' ){
		if(!pw) pw = 0.74 ;
		if(!ph) ph = 0.74 ;
		var w = pw > 1 ? pw : $(window).width()*pw;
		var h = ph > 1 ? ph : $(window).height()*ph;
	}else{
		var w = $('#'+id+'').width();
		var h = $('#'+id+'').height();
	}
	
	$('#shadow').fadeIn('fast',function(){
		
		
		$('#'+id).fadeIn('fast',function(){
			$('#'+id+' > .close').click(function(){SgiDropContent(id); return false});
			
			$(this).animate({
				
				width  	: w , 
				height 	: h,
				top 	: ($(window).height()/2) - (h/2) + $(window).scrollTop() - ad_pos_top , 
				left 	: ($(window).width()/2) - (w/2) + $(window).scrollLeft()
				
			});
			
		});
	});	
		
		$(window).scroll(function(){
			$('#'+id).css({
				top		: ($(window).height()/2) - (h/2) + $(window).scrollTop() - ad_pos_top,
				left 	: ($(window).width()/2) - (w/2) + $(window).scrollLeft()
				
			});
		});
		
	
	
	$(window).resize(function(){
		
		w = pw > 1 ? pw : $(window).width()*pw;
		h = ph > 1 ? ph : $(window).height()*ph;
		if($('#'+id).css('display') != 'none'){
			
			$('#'+id).animate({
				width  	: w, 
				height 	: h,
				top		: ($(window).height()/2) - (h/2) + $(window).scrollTop() - ad_pos_top,
				left 	: ($(window).width()/2) - (w/2) + $(window).scrollLeft()	
			});
			
		}
	});	
	
	
		if(scroll){// tem que implantar
			$('#'+id).css({
				'overflow-y' : 'visible'
			});
		}
}

/**
* @abstract Função para remover a div criada dinamicamente padrão
* id = [String] obrigatório;
* @since 13/08/2010
*/
SgiDropContent = function(id){

	$('#'+id).fadeOut('fast',function(){
		$('#'+id).empty().remove();
		$('#shadow').fadeOut('fast');
	});	
}

/**
* @abstract Função para auxiliar na hora de fazer o json de insert em tabelas passar o id para o campo.
* parametros elemento = [String] o elemento se não existir, a função cria;
* form = [String] O formulário, se na existir, busca o primeiro.
* @since 02/08/2010
*/

SgiSetId = function(element,valor,form){
	
	if(!element){
		  return false
	}else{
		
		if(typeof(element) == 'object'){
			
		}else if(typeof(element) == 'string'){
			
			var id = element
			element = document.getElementById(element);
			
			if(!element){
				
				if(!form){
					form = document.forms[0];
				}
				
				element = document.createElement('input');
				element.value 	= valor;
				element.id		= id;
				element.name	= id;
				element.type	= 'hidden';
				$(form).append(element);
				
			}else{
			
				element.value = valor ; 
			
			}
		}
	}
}

/* @abstract Variaveis globais no sistema, onde a linha de x
* e a linha de y  do cursor na página, é carregado 
* automaticamente.
*
* @since  31/05/2010
*/
onmousemove=function(e){  	cx = e.pageX;    cy = e.pageY;  };


/*@abstract comentar...*/
function SgiSendPermissaoModuloAcao(el,pagina,perm_id,perm_codlogin,perm_nome,json,callback){
	
	var el = $Peg(el);
	var v  = 0; 
	if(el){
		var perm_permid = el.value;
		if(el.checked){
			v = 1 ;
		}else{
			v = 0 ;
		}
		
		pagina = pagina+'?perm_id='+perm_id+'&'+'perm_codlogin='+perm_codlogin+'&'+'perm_permid='+perm_permid+'&'+'perm_nome='+perm_nome+'&status='+v;

		$.get(pagina,function(data){
			if(data){
				eval(data.js);
			}
		},json);
		
		if(callback)
			callback.call();
	}
}

/**
* @abstract Função para gerar um tooltip.
* parametros id_div = [String] O id do tooltip; el = [Object]
* o objeto que utilizara o tooltip; call = [Function] Uma callback; 
* position = [Function] as posições do tooltip, são definidas como 
* top ou bottom - left ou right, fica assim : top-left.
*
* @since 28/05/2010
*/
function SgiShowToolTipSimple(id_div,el,texto,call,position){
	
		var delay = 200 ; 
		var d = '';
		var s = '';
		
		try{
			call;
		}catch(e){
			//faz nada
		}
		
		var xline = cx+5
		var yline = cy+5	
		
		if(position != undefined || position != null){
			if(position == 'top-right'){
				var xline = cx+5
				var yline = cy-5
			}else if(position == 'top-left'){
				var xline = cx-5
				var yline = cy-5				
			}else if(position == 'bottom-right'){
				var xline = cx+5
				var yline = cy+5				
			}else if(position == 'bottom-left'){
				var xline = cx-5
				var yline = cy+5				
			}			
		}
		
		d = document.getElementById(id_div);
		if(texto == undefined || texto == null){
			if(el.title){
				s = el.title;
				
			}else if(el.innerHTML){
				s = el.innerHTML;
			}else if(el.value){
				s = el.value;
			}
		}else{
			s = texto ; 
		}
		
		if(((d == undefined) || (d == null))){
			$(document.body).append('<div id="'+id_div+'" class="SgiClassDivTooltip">'+s+'</div>');
			try{
				$('#'+id_div).animate({
					'opacity' : '1',
					'left' : xline,
					'top' : yline						
				},function(){
						$(el).mouseleave(function(){
							$('#'+id_div).delay(delay).fadeOut();
						});	
				});
			}catch(err){}
		}else{
			try{
				$('#'+id_div).html(s);
				$('#'+id_div).fadeIn();
				$('#'+id_div).animate({
					'opacity' : '1',
					'left' : xline,
					'top' : yline						
				},function(){
						$(el).mouseleave(function(){
							$('#'+id_div).delay(delay).fadeOut();
						});	
				});
			}catch(err){}				
		}
}


/**
* @abstract Função que cria o iframe em tempo real melhorando a 
* utilização de uploads com iframe simulando Ajax, dentre outras funcionalidades.
* parametros pagina = [String] Página para onde acontecerá o evento;
* response_id = [String] Div ou elemento que receberá o iframe; iframe_id = [String]
* O id do iframe. Parametro não é obrigatório.; getloadbar = [String] Futuramente
* o usuario podera escolher se quer receber o progresso do upload como resposta ajax.
*
* @since 28/05/2010
*/

SgiSendIframe = function(pagina,response_id,iframe_id,getloadbar){
	
	var b = document.forms;
	
	if(iframe_id == null){
		iframe_id = 'SgiIframeGeneric'
	}
	
	if(document.getElementById(iframe_id) != null){
			iframe_id = iframe_id+'_'+iframe_counters;
			iframe_counters++;
	}
	for(f = 0 ; f < b.length; f++){ 
		//alert(b[f]);
		if($(b[f]).attr('enctype') == 'multipart/form-data'){
			
			var form = $(b[f]);
			form_object = form
			$Peg(response_id).innerHTML = '';
			$('#'+response_id).append('<iframe height="100%" width="100%" style="border:none;" id="'+iframe_id+'" name="'+iframe_id+'" src="'+pagina+'"></iframe> ')			
			$(form).attr('target',iframe_id);
			$(form).attr('action',pagina);
			//alert($(form).attr('action')+' - '+$(form).attr('target')+' - '+$(form).attr('enctype'));
			form.submit();
			

			if(getloadbar == 'getloadbar'){
				var interval_instance = setInterval(function(){
				
					name = $(form_object).find("input[type='file']").val();
					name = name.split('/');
					name = name[name.length-1];
					if(name){
						$.get(pagina+'?getloadbar=1&file_name='+name,function(data){
							
							if(data){
								if(data.progress == 'complete'){
									clearInterval(interval_instance);
									return false;
								}else{
									alert(data.percent);
								}
							}
						},'json');
					}
				},5000);
			}
		}
	}
}

/**
* @abstract Função bastante expecifica para módulos que se passam uma junção de 
* ids separados por vírgula em Ajax. Muito usada na interface de grupo.
* parametros  pagina = [String] Pagina ajax. Pode conter tambêm todos seus parâmetros específicos;
* ids = [String] ids passados pelo ajax separados por um delimitador.
*
* @since 25/05/2010
*/
SgiSendGrupoList = function(pagina,ids){
	if(ids != null){
		$Aja2(pagina+'&ids='+ids,'GET',null,null,null,'json');
	}
}

/**
* @abstract Função bastante importante, usada para transferir options de um select para o outro,
* essa função é muito usada nos módulos de grupo de usuário por exemplo.
* parametros saida_elemento = [String/Object] Elemento que transfere seus options selecionados para o entrada_elemento;
* entrada_elemento = [String/Object] Elemento que recebe os options logo após, remove os options do saida_elemento.
*
* @since 25/05/2010
*/
SgiTransSelectedItens = function(saida_elemento,entrada_elemento){
	
	var saida 	= $Peg(saida_elemento);
	var entrada = $Peg(entrada_elemento);
	
	var query	= '';
	if(saida.type === 'select-multiple'){
		if(saida.hasChildNodes()){
			var val = $(saida).val();
			var t = val.join(',').split(',');
			var option = saida.options;
			for(i = 0 ; i <= option.length ; i++){
				for(x = 0 ; x <= t.length; x++){
					if(option[i] != undefined){
						if(option[i].value == t[x]){
							$(entrada).append($(option[i]),function(){
								$(option[i]).remove();
							});
						}
					}
				}
			}
		}
	}
	
}

/**
* @abstract Função para apresentar e sumir com a mensagem de erro das apls.
* Essa função existe hoje porque esse método que apresenta a mensagem, é padrão
* em todas as aplicações.
* parametros id = [String] O id do elemento que sofrerá a ação de aparecer e desaparecer;mensagem = [String] A mensagem que ficará dentro da div.
*
* @since 24/05/2010
*/
SgiAlert = function(id,mensagem){
	var countdown = 300 ;
	var string 		= mensagem.toLowerCase();
	var classe 		= 'SgiInterModSalvo';
	var shadowset	= $('#shadow').css('display') != 'none' ? false : true ;

	if(string.search('erro') > -1  || string.search('error') > -1) { 

		classe = 'SgiInterModErro'
	}
	
	var d = document.getElementById(id);
		
		if(((d == undefined) || (d == null))){
			//document.body.innerHTML += '<div id="'+id+'" class="'+classe+'" >'+mensagem+'</div>' ; 
			$(document.body).append('<div id="'+id+'" class="'+classe+'" >'+mensagem+'</div>');
		}else{
			$Peg(id).className = classe ; 
			$Peg(id).innerHTML = mensagem;
		}

		$('#shadow').delay(countdown).fadeIn(countdown/2,function(){
			$('#'+id).animate({'opacity':'0.9'},function(){
				$('#'+id).delay(countdown).animate({'opacity':0},function(){
					
					//if(shadowset){
						$('#shadow').fadeOut(countdown/2);
					//}
					
					$('#'+id).remove();
			    });
			});
		});
		
}

/**
* @abstract Função para colocar as horas do S.O. no innerHtml de qualquer elemento.
* parametros clock = [Object]ELEMENTO
*
* @since 07/05/2010
*/

horas = function(clock){
	
	var now = new Date();
	var hours = now.getHours();
	var minutes = now.getMinutes();
	var seconds = now.getSeconds()
	if (hours <=9)
		hours="0"+hours;
	if (minutes<=9)
		minutes="0"+minutes;
	if (seconds<=9)
		seconds="0"+seconds;
	var cdate=""+hours+":"+minutes+":"+seconds; 
		if($Peg(clock))
			$Peg(clock).innerHTML= cdate;
		
			setTimeout("horas('"+clock+"')",1000);

}


	/**
	* @abstract Função para chamar os módulos em Ajax 
	* parametros id = [Object] O elemento que sofrerá a ação;delay = [Int] velocidade decorrida do evento.
	*
	* @since 10/05/2010
	**/	
	SgiClickShowMacSelectBox = function(id,delay){
		$(id).slideDown(delay);
		$(id).mouseleave(function(){ 
			$(id).slideUp(delay);
		});
	}
	
/*funcões específicas do macselect*/

	/**
	* @abstract função para mostrar o box-list do select estilo mac criado.
	* parametros id = [Object] O elemento que sofrerá a ação;delay = [Int] velocidade decorrida do evento.
	*
	* @since 10/05/2010
	**/	
	SgiClickShowMacSelectBox = function(id,delay){
		$(id).slideDown(delay);
		$(id).mouseleave(function(){ 
			$(id).slideUp(delay);
		});
	}
	
	/**
	* @abstract Essa função faz o efeito de drop e down em alguma div. Especificamente foi feita para o template do cabeçalho
	* porem em alguns casos ela funciona para outras divs.
	* parametros id = [String] O id da div que sofrerá a ação; min = [Int] Valor mínimo que a altura da div pode chegar;
	* max = [Int] Valor Máximo que a div pode chegar; content = [String] Id do elemento que se existir, fica escondido ou não.
	*
	* @since 10/05/2010
	**/	
	SgiDropDownRoundBar = function(id,min,max,content){
		var el_height = parseInt($('#'+id).css('height'));
		max = max == undefined ? 80 : max ; 
		min = min == undefined ? 10 : min ; 
		
		if(el_height <= min){
				$('#'+content).fadeIn('slow');
				$('#'+id).animate({'height': max});
				
		}else if(el_height >= max){
				$('#'+content).fadeOut('slow');
				$('#'+id).animate({'height': min});		
		}
	}
/*funcões específicas do macselect*/

SgiSelecionaTema = function(tema){
	window.location = 'index?'
}

/**
* @abstract Função para retornar o label e a classe de uma div, repesentando nível de dificuldade da senha.
* parametros nivel = [String] valor predefinido; id_div = [String] Id do elemento que vai receber a barra; 
* label = [String] Id do elemento que vai receber o texto; delay = [Int] Velocidade para se aplicar a alteração
*
* @since 07/05/2010
*/
SgiGenericForcaSenha = function (nivel,id_div,label,delay){
	
	delay = (delay == undefined) ? 200 : delay ; 
	
	if(nivel == 'curta'){
		$Peg(label).innerHTML='Curta';
		$('#'+id_div).animate({width: '50px'},delay,function(){
			$Peg(id_div).className = 'SgiSenhaCurta';			
		});
	}else if(nivel == 'media'){
		$Peg(label).innerHTML='Media';
		$('#'+id_div).animate({width: '100px'},delay,function(){
			$Peg(id_div).className = 'SgiSenhaMedia';			
		});				
	}else if(nivel == 'forte'){
		$Peg(label).innerHTML='Forte';
		$('#'+id_div).animate({width: '150px'},delay,function(){
			$Peg(id_div).className = 'SgiSenhaForte';			
		});		
	}
	
	
}

/**
* @abstract Função para definir um comando via teclado como CTRL+K e agregando uma função.
* parametros SHORTCUTSTRING = [String] comando; FUNCTION_EXEC = [String/Function] Função que será executada
*
* @since 07/05/2010
*/
SgiSetShortcut = function(SHORTCUTSTRING,FUNCTION_EXEC){
	shortcut.add(SHORTCUTSTRING,FUNCTION_EXEC);
}

/**
* @abstract Função para transformar qualquer elemento em arrastável.
* parametros id = [String] id do elemento;
*
* @since 07/05/2010
*/
SgiDrag  = function(id){
	$('#'+id).draggable({disabled : false});
}

/**
* @abstract Função para remover o efeito arrastável qualquer elemento.
* parametros id = [String] id do elemento;
*
* @since 07/05/2010
*/
SgiUndrag = function(id){
	$('#'+id).draggable({disabled : true});
}

/**
* @abstract Opaca e remove os elementos referentes a um determinado tipo, atributo e valor.
* parametros el = [String] tipo de elemento EX.'div'; att = [String] Nome do atributo buscado; value = [String] Valor do atributo buscado
*
* @since 07/05/2010
*/
SgiHideElementByAtt = function(el,att,value){
	divs = document.getElementsByTagName(el);

		var len = parseInt(divs.length);

		i = 0 ; 
		for( i = 0 ; i < len ; i++ ){
			if(divs[i]){
				if($(divs[i]).attr(att) == value){
					$(divs[i]).fadeOut(500,function(){$(divs[i]).remove();});
					$('#shadow').hide('fast');
				}
			}
		}
}

/**
* @abstract Função importante que pretende complementar o Ajax de forma mais inteligente. Ele cria a div se ela não existir.
* parametros ajax = [String] Pagina; id_div = [String] Id da div que recebe o conteúdo; TYPE = [String] Método de envio Get/Post;
* FORM = [String] Id do Formulário; JSON = [String] se é json EX. 'json'; PREDEFINEATT = [String] Atributo adicional inserido
* a div criada caso ela não exista. Deve ter exeção do atributo 'alt'; EFEITO = [String] parametro para quando o Ajax retornar 
* com efeito se for verdadeiro;
*
* @since 07/05/2010
**/
SgiLoadAjaxContent = function(ajax,id_div,TYPE,FORM,JSON,PREDEFINEATT,EFEITO){
	
	//SgiSetShortcut('CTRL+K',SgiHideElementByAtt('div','alt','draggable'));
	
	if(((id_div == undefined) || (id_div == null)) && JSON == null){
		id_div = 'SgiGenericAjaxDiv';
	}	
	
	if(!TYPE)
		TYPE = '';
	
	d = document.getElementById(id_div);
	if(((d == undefined) || (d == null))  && JSON == null){
		
			PREDEFINEATT = PREDEFINEATT == null ? 'class="SgiGenericDyDiv"' : PREDEFINEATT;
			$(document.body).append('<div '+PREDEFINEATT+' id="'+id_div+'" alt="draggable" ></div>');
			

	}
	
	
	if(TYPE == '' || TYPE.toLowerCase() == 'get'){
		
		$.get(ajax,function(data){
			if(data){
				if(JSON){
					eval(data.js)
				}else{
					$('#'+id_div).html(data);
				}
			}
		},JSON);
		
	}else{
		
		frm = FORM ? ($('#'+FORM).length > 0 ? $('#'+FORM) :$(document.forms[0]))  : $(document.forms[0]);
		
		$.post(ajax,frm.serialize(),function(data){
			if(data){
				if(JSON){
					eval(data.js)
				}else{
					$('#'+id_div).html(data);
				}
			}			
		},JSON);
		
	}
	//$Aja2(ajax,TYPE,FORM,id_div,null,JSON);
}

/**
* @abstract É uma integração do SgiAjaxLoadContent, essa função é usada para minimizar um elemento de preferência DIV.
* parametros id_div = [String] Id do elemento que sofrerá a ação; title = [String] Elemento referente ao Titúlo da div;
*
* @since 07/05/2010
**/
SgiMinMaxAjaxContent = function(id_div,title){

	d = document.getElementById(id_div);
	pxheight	= "22px";
	delay 		= 300 ; 
	if($('#'+id_div).css('height') != pxheight){
		$('#'+title).fadeIn(delay); 
		$('#shadow').hide('fast',function(){
			if((d != undefined) || (d != null)){
				
				eval(id_div+'_height = "'+$('#'+id_div).height()+'";');
				eval(id_div+'_width  = "'+$('#'+id_div).width()+'";');
				$('#'+id_div).css('overflow','hidden');
				$('#'+id_div).animate({height: pxheight ,width: "200px",opacity: 0.9},delay);
			}
		});
	}else{
		$('#'+title).fadeOut(delay); 
		$('#shadow').show('fast',function(){
			if((d != undefined) || (d != null)){
				eval('h = '+id_div+'_height;');
				eval('w = '+id_div+'_width;');
				$('#'+id_div).animate({height: h ,width: w,opacity: 1},delay);
			}
		});
	}
	
	
}

/**
* @abstract É uma integração do SgiAjaxLoadContent, essa função é usada para junto a um evento, matar a div criada por ele,
* idependente se elá está fixa no código.
* parametros id_div = [String] Id do elemento que sofrerá a ação de remoção;
*
* @since 07/05/2010
**/
SgiUnloadAjaxContent = function(id_div){
	d = document.getElementById(id_div);

	$('#shadow').hide('fast',function(){
			if((d != undefined) || (d != null)){
				$('#'+id_div).hide('fast',function(){
					$('#'+id_div).remove();
				});
			}
	});
}

/**
* @abstract É uma função criada devido a necessidade de fazer um "hover" para o IE6, desde que o
* elemento passado tenha o atributo class ou src.
* parametros el = [Object] Como o método é passado no evento onmouseover, o interessante é esse parametro ser um this ;
* type = [String] Valor predefinido, 'class' ou 'img'; ext = [String] Se o type for 'img' então ainda sim não é obrigatório
* o parametro ext, porém pode gerar dificuldades para pegar o nome da imagem.
*
* @since 07/05/2010
**/
sgiover = function(el,type,ext){
	
	if(type){
		
		if(type == 'class')
			el.className = el.className+'_hover';
		else if(type == 'img')
			el.src = el.src.replace('.'+ext,'_hover.'+ext);
			
	}else{
		if(el == '[object HTMLImageElement]'){
			var ext = el.src.split('.');
			ext 	= ext[ext.length-1];
			el.src = el.src.replace('.'+ext,'_hover.'+ext);
		}else{
			el.className = el.className+'_hover';
		}
	}
}

/**
* @abstract É uma integração da função sgiover para o IE6, que tira a classe predefinda com o final '_hover' 
* para o nome normal. Para funcionar o elemento passado tem que ter o atributo class ou src.
* parametros el = [Object] Como o método é passado no evento onmouseout, o interessante é esse parametro ser um this ;
* type = [String] Valor predefinido, 'class' ou 'img'; ext = [String] Se o type for 'img' então ainda sim não é obrigatório
* o parametro ext, porém pode gerar dificuldades para pegar o nome da imagem.
*
* @since 07/05/2010
**/
sgiout = function(el,type,ext){
	
	if(type){
		
	if(type == 'class')	
		el.className = el.className.replace('_hover','');
	else if(type == 'img')
		el.src = el.src.replace('_hover.'+ext,'.'+ext);
			
	}else{
		if(el == '[object HTMLImageElement]'){
			var ext = el.src.split('.');
			ext 	= ext[ext.length-1];
			el.src = el.src.replace('_hover.'+ext,'.'+ext);
		}else{
			el.className = el.className.replace('_hover','');
		}
	}
}

/**
* @abstract Desabilita um passado elemento qualquer, caso uma condição qualquer seja verdadeira.
* parametros condition = [Boolean] Passa o retorno de uma condição Ex. SgiUndisable(m == 2,'input_campo');
* element = [Object] Elemento que sofrerá a ação.
*
* @since 07/05/2010
**/
SgiUndisable = function(condition,element){
	if(condition == true){
		element.disabled = false ;
	}else{
		element.disabled = true ; 
	}
}

/**
* @abstract Seleciona todos o elementos vindos de um pai e muda suas classes diferenciando esses elementos de um 
*especial ( ou que recebe o click EX. onclick(this);) passado por parametros.
* parametros pai = [Object/String] Elemento ou id do elemento pai, responsável por apresentar a função todos os seus filhos;
* abasel = [Object] Elemento especial que recebe a classe "especial", diferente de seus irmãos; 
* classenormal = [String] A classe normativa dos filhos; classeselected = [String] A classe especial do elemento especial.
* callback = [Function] Uma Função para ser executada no final da execução desta.
* not_class = [String] Uma Seleção de elementos por classe que não entrarão na lista dos elementos modificados
*
* @since 07/05/2010
**/
SgiSelectGroupElements = function(pai,abasel,classenormal,classeselected,callback,not_class){
		if(!not_class){ not_class = 'empty-class'; }
		pai = $Peg(pai);
		if(pai.hasChildNodes()){
			var len = parseInt(pai.childNodes.length);
			i = 0 ; 
			for( i = 0 ; i < len ; i++ ){
				if(pai.childNodes[i]){
					if(pai.childNodes[i].className != not_class){
						pai.childNodes[i].className = classenormal;
					}
				}
			}
		}
		abasel.className = classeselected;
		if(callback)
			callback.call();
}

/**
* @abstract 
* parametros
*
* @since 07/05/2010
**/
SgiAddRemOption = function (campo_origem, campo_destino){
	
	var objeto1 = $Peg(campo_origem);
	var objeto2 = $Peg(campo_destino);
	var i = 0 ;
	var j = 0 ;
	var VetorPosicaoValue = new Array();
	var VetorPosicaoText = new Array();
	
	////////////fazendo um for para listar os selecionados do campo_origem
	if(objeto1.length > 0){
		for(i = 0; i < objeto1.length ; i++){
			//remove e adiciona
			//remove da origem e adiciona no destino
			var texto  = document.createTextNode (objeto1.options[i].text);
			var value  = objeto1.options[i].value;
			if(objeto1.options[i].selected){

				//adicionar
        		var option = document.createElement("option");
        		option.value = value;
        		option.appendChild( texto );
        		objeto2.appendChild( option );
        		option.selected = true;

        		///////////////NAO PODE, POIS NO CHROME DA ERRO
        		//objeto1.remove(i);
			}else{

				VetorPosicaoValue[j] = value;
				VetorPosicaoText[j]  = texto;
				j++;
			}
		}
		/** FORMA DE APAGAR TODOS DA LISTA OPTION **/
		while(objeto1.firstChild){
			objeto1.removeChild(objeto1.firstChild);
		}
		
		///adicionando novamente
		for(i = 0; i < j ; i++){

			//adicionar
    		var option = document.createElement("option");
    		option.value = VetorPosicaoValue[i];
    		option.appendChild( VetorPosicaoText[i] );
    		objeto1.appendChild( option );
    		//option.selected = true;
		}
	}
}


/**
* @abstract 
* parametros
*
* @since 07/05/2010
**/
SgiAddRemOption2 = function (campo_origem, campo_destino){
	
	var objeto1 = $Peg(campo_origem);
	var objeto2 = $Peg(campo_destino);
	var i = 0 ;
	var j = 0 ;
	var VetorPosicaoValue = new Array();
	var VetorPosicaoText = new Array();
	
	////////////fazendo um for para listar os selecionados do campo_origem
	if(objeto1.length > 0){
		for(i = 0; i < objeto1.length ; i++){
			//remove e adiciona
			//remove da origem e adiciona no destino
			var texto  = document.createTextNode (objeto1.options[i].text);
			var value  = objeto1.options[i].value;
			if(objeto1.options[i].selected){

				//adicionar
        		var option = document.createElement("option");
        		option.value = value;
        		option.appendChild( texto );
        		objeto2.appendChild( option );
        		option.selected = true;

        		///////////////NAO PODE, POIS NO CHROME DA ERRO
        		//objeto1.remove(i);
			}else{

				VetorPosicaoValue[j] = value;
				VetorPosicaoText[j]  = texto;
				j++;
			}
		}
		/** FORMA DE APAGAR TODOS DA LISTA OPTION **/
		while(objeto1.firstChild){
			objeto1.removeChild(objeto1.firstChild);
		}
		
		///adicionando novamente
		for(i = 0; i < j ; i++){

			//adicionar
    		var option = document.createElement("option");
    		option.value = VetorPosicaoValue[i];
    		option.appendChild( VetorPosicaoText[i] );
    		objeto1.appendChild( option );
    		option.selected = true;
		}
	}
}

/**
* @abstract 
* parametros
*
* @since 07/05/2010
**/
SgiSelectedTrueOptions = function(campo_origem){

	var objeto1 = $Peg(campo_origem);
	var i = 0 ;

	if(objeto1.length > 0){
		for(i = 0; i < objeto1.length ; i++){
		
			objeto1.options[i].selected = true;
		}
	}
}

/**
* @abstract 
* parametros
*
* @since 07/05/2010
**/
SgiSelectedTrueOption2 = function(campo_origem,campo_hidden){

	var objeto1 = $Peg(campo_origem);
	var objeto2 = $Peg(campo_hidden);
	var i = 0 ;

	if(objeto1.length > 0){
		objeto2.value = '';
		for(i = 0; i < objeto1.length ; i++){
			////selecionando em tempo real
    		//objeto1.options[i].selected = true;
    		if(objeto2.value.length > 0 )
    		objeto2.value += ",";
    		
    		objeto2.value += objeto1.options[i].value;
		}
	}
}

/**
* @abstract 
* parametros
*
* @since 07/05/2010
**/
SgiMudaMenuSite = function(nomeTag,menuOn,menuTerm,nomeClasse1,nomeClasse2){
    		
	///deixar todos menus OFF
	//var vetorMenu = new Array("sgimenuHome","sgimenuGrupo","sgimenuServico","sgimenuCliente");
	//retorna um array com as tags div
	var e = document.getElementsByTagName(nomeTag);
	
 	for(i=0;i<e.length;i++){
 		
 		if(e[i].hasChildNodes()){
 		
 			var n  = e[i].childNodes;		 			
 			var idTag = e[i].getAttribute("id");
 			
 			var vetorTag = new Array();		 			
 			if(idTag)
 			var vetorTag = idTag.split("_");
 			
 			if(vetorTag[0] == menuTerm){
 				
 				//alert(menuOn+"::"+idTag+ " : "+ n + " = "+vetorTag[0]+"=="+menuTerm);
 				
	 			switch(idTag){
	 					
	 				case menuOn:
	 				$Peg(idTag).className = nomeClasse2;
	 				//alert(idTag+ " : "+ n + " = "+vetorTag[0]);
	 				break;
	 				default:
	 				$Peg(idTag).className = nomeClasse1;
	 				//alert(idTag+ " : "+ n + " = "+vetorTag[0]);
	 			}
 			}
 		}
 	}
}

/**
* @abstract 
* parametros
*
* @since 07/05/2010
**/
turnContainer = function(div,shadow){

	var divElement = $Peg(div);
	var displayElement = "block";

	if(divElement.style.display=="inline"){ displayElement = "none"; }
	if(shadow){ $Peg("shadow").style.display = displayElement; }

	divElement.style.display = displayElement;
}

/**
* @abstract 
* parametros
*
* @since 07/05/2010
**/
toogleFiltro = function(img,div){

var img = $Peg(img);
var div = $Peg(div);

var display = "none";
var src = "img/close_div.gif";

if(div.style.display=="none"){
	display = "inline";
	src = "img/open_div.gif";
}

img.src = src;
div.style.display = display;
}

/**
* @abstract 
* parametros
*
* @since 07/05/2010
**/
SgiToogleFiltroGeneric = function(img,div,imgopen,imgclosed){

var img = $Peg(img);
var div = $Peg(div);

var display = "none";
var src = imgclosed;

if(div.style.display=="none"){
	display = "inline";
	src = imgopen;
}

img.src = src;
div.style.display = display;
}

/**
* @abstract 
* parametros
*
* @since 07/05/2010
**/
AjaxGenericUpdate = function(url,id,idvalue,campo,value,tabela,tipovalor){

	$Aja2(url+"?idvalue="+idvalue+"&tipovalor="+tipovalor+"&campo="+campo+"&id="+id+"&value="+value+"&tabela="+tabela,"GET",null,null,null,"json");
	
}

/**
* @abstract 
* parametros
*
* @since 07/05/2010
**/
FormataValorMoeda = function(campo,tammax,teclapres){
	
	var tecla = teclapres.keyCode;
	
	vr = SgiLimparValue(campo.value,"0123456789");
	
	tam = vr.length;
			
	//COMENTAR PARA 3 CASAS DECIMAIS ATIVO 2 CASAS DECIMAIS
	///if (tam < tammax && tecla != 8){ tam = vr.length + 1 ;}
	
	if (tecla == 8 ){ tam = tam - 1 ; }
	
	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
		if ( tam <= 2 ){
			campo.value=vr ; 
		}
		if ( (tam > 2) && (tam <= 5) ){
			campo.value= vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - 2, tam ) ; 
		}
		//CORRECAO PARA 2 CASAS DECIMAIS NAS CENTENAS
		if ( (tam >= 6) && (tam <= 8) ){
			//alert(tam+" not ");
			campo.value= vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - 2, tam ) ; 
		}
		if ( (tam >= 9) && (tam <= 11) ){
			campo.value= vr.substr( 0, tam - 8 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - 2, tam ) ; 
		}
		if ( (tam >= 12) && (tam <= 14) ){
			campo.value= vr.substr( 0, tam - 11 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - 2, tam ) ; 
		}
		if ( (tam >= 15) && (tam <= 17) ){
			campo.value= vr.substr( 0, tam - 14 ) + "." + vr.substr( tam - 14, 3 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - 2, tam ) ;
		}
	}
}//fim de function

/**
* @abstract 
* parametros
*
* @since 07/05/2010
**/
SgiLimparValue = function(valor,validos) {
// retira caracteres invalidos da string

	var result = "";
	var aux;
	for (var i=0; i < valor.length; i++) {
		aux = validos.indexOf(valor.substring(i, i+1));
		if (aux>=0){
			result += aux;
      	}
 	}//fim de for

return result;
}//fim de function

/**
* @abstract 
* parametros
*
* @since 07/05/2010
**/
SgichangeAba = function(proximaAba,divAtiva,classOn,classOff,divDesativa){

	//sgiAbaProc
	
	if($Peg(proximaAba).style.display=='none'){
		$Peg(proximaAba).style.display = "block";
		divAtiva.className = classOn;
	}
	else{
		$Peg(proximaAba).style.display = "none";
		divAtiva.className = classOff;
	}
}

/**
* @abstract 
* parametros
*
* @since 07/05/2010
**/
SgiMudaMenuDisplay = function(nomeTag,menuOn,menuTerm,nomeClasse1,nomeClasse2,divDisplay){
    		
	///deixar todos menus OFF
	//var vetorMenu = new Array("sgimenuHome","sgimenuGrupo","sgimenuServico","sgimenuCliente");
	//retorna um array com as tags div
	var e = document.getElementsByTagName(nomeTag);
		
 	for(i=0;i<e.length;i++){
 		
 		if(e[i].hasChildNodes()){
 		
 			var n  = e[i].childNodes;		 			
 			var idTag = e[i].getAttribute("id");
 			
 			var vetorTag = new Array();		 			
 			if(idTag)
 			var vetorTag = idTag.split("_");
 			
 			if(vetorTag[0] == menuTerm){
 				//alert(menuOn+"::"+idTag+ " : "+ n + " = "+vetorTag[0]+"=="+menuTerm);
	 			switch(idTag){
	 					
	 				case menuOn:
	 				$Peg(idTag).className = nomeClasse2;	 				
	 				//alert(idTag+ " : "+ n + " = "+vetorTag[0]);
	 				break;
	 				default:
	 				$Peg(idTag).className = nomeClasse1;	 				
	 				//alert(idTag+ " : "+ n + " = "+vetorTag[0]);
	 			}
 			}
 		}
 	}
 	
 	////////////SEPARAR DIVS QUE PRECISAM OCULTAR E ABRIR
	if(divDisplay){
		var divsInline = divDisplay.split(",");
		//////////////SEMPRE O PRIMEIRO DO VETOR
		var divPaiInline = divsInline[0];
		for(j=0;j<divsInline.length;j++){
			if(divsInline[j] != divPaiInline){
				//$Peg(divsInline[j]).style.display = 'none';
				var divalt = "#"+divsInline[j];
				$(divalt).hide("slow");	
			}
		}
		//$Peg(divsInline[0]).style.display = 'block';
		var divalt = "#"+divsInline[0];
		$(divalt).slideDown("slow");
	}	
}


/**
* @abstract Mascara Genérica e simples
* parametros src = [Object] O elemento que sofrerá as alterações da mascara; mask = [String] Formato da mascara Ex. ##/##/#### dentre outros
* onde # é onde entrará as letras digitadas e (/ ou ; ou . ) serão as mascaras do campo.
*
* @since 10/05/2010
**/
mascaraGeneric = function(src, mask,e){
	
	var code = 0 ;
	
	if(e){ 
			code = e.keyCode;
	}else if(this.event){
			code = this.event.keyCode;
	}
	
	if(code != 8 && code != 13){
		var i = src.value.length;
		var saida = mask.substring(0,1);
		var texto = mask.substring(i)
		if (texto.substring(0,1) != saida)
		{
		src.value += texto.substring(0,1);
		}
	}

}

/**
* @abstract 
* parametros
*
* @since 07/05/2010
**/
SgiApagaAllOption = function (objeto1){
	
	/** FORMA DE APAGAR TODOS DA LISTA OPTION **/
		while(objeto1.firstChild){
			objeto1.removeChild(objeto1.firstChild);
		}
}

/**
* @abstract 
* parametros
*
* @since 07/05/2010
**/
SgiToogleHidde = function (idImg,idDiv){
	
	if ($(idDiv+":first").is(":hidden")) {

        $(idDiv).html("");
        $Peg(idImg).src = "img/close_div.gif";
        
      } else {

        $(idDiv).html("");
        $Peg(idImg).src = "img/close_div.gif";
      }
}
///////////ITEGRACAO COM JQUERY

/**
* @abstract 
* parametros
*
* @since 07/05/2010
**/
SgiToogle = function (idImg,idDiv){
	
	if ($(idDiv+":first").is(":hidden")) {
        $(idDiv).show("fast");
        $Peg(idImg).src = "img/open_div.gif";
      } else {
        $(idDiv).slideUp();
        $Peg(idImg).src = "img/close_div.gif";
      }
}

/**
* @abstract 
* parametros
*
* @since 07/05/2010
**/
SgiToogleImg = function (idImg,idDiv,img1,img2){
	
	if ($(idDiv+":first").is(":hidden")) {
        $(idDiv).show("slow");
        $Peg(idImg).src = img1;
      } else {
        $(idDiv).slideUp();        
        $Peg(idImg).src = img2;
      }
}

/**
* @abstract 
* parametros
*
* @since 07/05/2010
**/
SgiToogleAjax = function (idImg,idDiv,URL,METODO, IDFORM,DIV,IMAGEM,JSON){

	if ($(idDiv+":first").is(":hidden")) {
        $(idDiv).show("slow");
        $Peg(idImg).src = "img/open_div.gif";
        //chamar o ajax
         $Aja2(URL,METODO,IDFORM,DIV,IMAGEM,JSON);

      } else {

      	//////////////nao chamar ajax
        $(idDiv).slideUp('fast',function(){

        	$(idDiv).html("");
        	$Peg(idImg).src = "img/close_div.gif";

        } );
      }
}

SgiListaMenuGrupo = function (id)
{
	var obj = $Peg('menu_'+id);
	if(obj.style.display=="none"){
		obj.style.display="";
		$Peg('img_'+id).src = 'img/minus.gif';
	}else{
		obj.style.display="none";
		$Peg('img_'+id).src = 'img/plus.gif';
	}
}

SgiAjaxAtualizaGeneric = function (table,field,value,where_field,id,caixa,p){
	
	if(!p){
		p = 'ajax_modulos/AjaxAtualizaValor';
	}
	if(!caixa) caixa = '';
	
	path = p+'?table='+table+"&field="+field+"&value="+value+"&where_field="+where_field+"&id="+id+'&caixa='+caixa;
	$.get(path);
	
}