// Browser Lib
/**
 * @objetivo	: Detecta Navegador 
 * @parametro	: sem parâmetros
 * @retorno		: Data
 * @autor       : Desconhecido
 * @versão		: 1, 11  de Junho de 2004
 */					
function xbDetectBrowser()
{
 var platform;
 var oldOnError 	   	  = window.onerror;
 var element    	   	  = null;
	 window.onerror 	  = null;
	 window.saveNavigator = window.navigator;// work around bug in xpcdom Mozilla 0.9.1
	 navigator.OS    	  = '';
	 navigator.version    = parseFloat( navigator.appVersion );
	 navigator.org    	  = '';
	 navigator.family  	  = '';
	  
	 if( typeof( window.navigator.platform ) != 'undefined')
	 {
	   platform = window.navigator.platform.toLowerCase();
	   
	   if( platform.indexOf('win') != -1 )
		   navigator.OS = 'win';
	   else if( platform.indexOf('mac') != -1 )
		   navigator.OS = 'mac';
	   else if( platform.indexOf('unix') != -1 || platform.indexOf('linux') != -1 || platform.indexOf('sun') != -1 )
		   navigator.OS = 'nix';
	 }
	
	  var i  = 0;
	  var ua = window.navigator.userAgent.toLowerCase();
	  
	  if( ua.indexOf('opera') != -1 )
	  {
		i 				   = ua.indexOf('opera');
		navigator.family   = 'opera';
		navigator.org      = 'opera';
		navigator.version  = parseFloat('0' + ua.substr( i + 6 ), 10);
		
	  } else if( ( i = ua.indexOf('msie') ) != -1 ) {
		
		navigator.org      = 'microsoft';
		navigator.version  = parseFloat('0' + ua.substr( i + 5 ), 10);
		navigator.family   = ( navigator.version < 4  )? 'ie3':'ie4';
	  } else if( ua.indexOf('gecko') != -1 ) {
		  
		navigator.family   = 'gecko';
		var rvStart        = ua.indexOf('rv:');
		var rvEnd   	   = ua.indexOf(')', rvStart);
		var rv      	   = ua.substring(rvStart + 3, rvEnd );
		var rvParts 	   = rv.split('.');
		var rvValue 	   = 0;
		var exp     	   = 1;
	
		for( var i = 0; i < rvParts.length; i++ )
		{
		  var val  = parseInt( rvParts[ i ] );
		  rvValue += val / exp;
		  exp 	  *= 100;
		}
		navigator.version   = rvValue;
	
		if( ua.indexOf('netscape') != -1 )
		  navigator.org = 'netscape';
		else if(ua.indexOf('compuserve') != -1)
		  navigator.org = 'compuserve';
		else
		  navigator.org = 'mozilla';
		  
	  } else if( ( ua.indexOf('mozilla') !=-1) && (ua.indexOf('spoofer')==-1) && (ua.indexOf('compatible') == -1) && (ua.indexOf('opera')==-1)&& (ua.indexOf('webtv')==-1) && (ua.indexOf('hotjava')==-1)) {
		
		var is_major = parseFloat(navigator.appVersion);
			if( is_major < 4 )
			  navigator.version = is_major;
			else
			{
			  i = ua.lastIndexOf('/')
			  navigator.version = parseFloat('0' + ua.substr( i + 1 ), 10);
			}
			  navigator.org    = 'netscape';
			  navigator.family = 'nn' + parseInt( navigator.appVersion );
			  
	 } else if((i = ua.indexOf('aol')) != -1 )  {
		// aol
			  navigator.family   	   = 'aol';
			  navigator.org      	   = 'aol';
			  navigator.version  	   = parseFloat('0' + ua.substr( i + 4 ), 10);
			  
	  } else if( ( i = ua.indexOf('hotjava') ) != -1 )  {
		// hotjava
			  navigator.family  	   = 'hotjava';
			  navigator.org    		   = 'sun';
			  navigator.version  	   = parseFloat(navigator.appVersion);
	  }
	   window.onerror = oldOnError;
}
// Detecta navegador
xbDetectBrowser();


var cor_primaria  = 'F4F5F7';
/**
 * @objetivo	: ProtoType Datas
 * @retorno		: data
 * @autor       : João Neto
 * @versão		: 2, 10 de Dezembro  de  2003
 */					
Date.prototype.Dtos = function()
{
  var dd = this.getDate();
  var mm = this.getMonth() + 1;
  var yy = this.getFullYear();
	
  return( [ yy , ( mm < 10 ? '0' : '' ) + mm , ( dd < 10 ? '0' : '' ) + dd ].join( '' ) );
}
/**
 * @objetivo	: ProtoType Elementos em Branco
 * @retorno		: booleano
 * @autor       : João Neto
 * @versão		: 2, 10 de Dezembro  de  2003
 */					
Array.prototype.hasEmptyElements = function()
{
  for( var i = 0 ; i < this.length ; i++ )
   if( ( this[ i ] == '' ) || ( this[ i ] == null ) || ( this[ i ] == undefined ) )
	  return( true );
			
   return( false );
}
/**
 * @objetivo	: ProtoType Numero
 * @retorno		: booleano
 * @autor       : João Neto
 * @versão		: 2, 10 de Dezembro  de  2003
 */					
String.prototype.isNumber = function()
{
  return( !isNaN( this.split( '.' ).join( '' ).split( ',' ).join( '' ).split( '-' ).join( '' ) ) );
}
/**
 * @objetivo	: ProtoType Date
 * @retorno		: booleano 
 * @autor       : Jefferson Petilo( jefferson@netdom.com.br ) 
 * @versão		: 2, 10 de Agosto  de  2004
 */					
String.prototype.isDate = function()
{
  if( this.split( '/' ).length != 3 ) return( false );

   var dd = Number( this.split( '/' )[ 0 ] );
   var mm = Number( this.split( '/' )[ 1 ] );
   var yy = Number( this.split( '/' )[ 2 ] );
   var dt = new Date( yy , mm -1 , dd  );
	 
  return( [ yy , ( mm < 10 ? '0' : '' ) + mm , ( dd < 10 ? '0' : '' ) + dd ].join( '' ) == dt.Dtos() );
}
/**
 * @objetivo	: ProtoType Email
 * @retorno		: booleano
 * @autor       : João Neto
 * @versão		: 2, 10 de Dezembro  de  2003
 */					
String.prototype.isMail = function()
{
 var test;
 var pt1    = this.split( '@' );
 var valid  = '.-_@';
		
	if( ( pt1.length != 2 ) || ( pt1[ 0 ].length == 0 ) || ( pt1[ 1 ].length == 0 ) ) 
		return( false );
	else
	{
	  for( var i = 0 ; i < valid.length - 1 ; i++ )
	  {
		if( pt1[ 0 ].split( valid.charAt( i ) ).hasEmptyElements() ) return( false );
		if( pt1[ 1 ].split( valid.charAt( i ) ).hasEmptyElements() ) return( false );
	   }			
	}
	for( var i = 0 ; i < this.length ; i++ )
	{
	  var charac = this.toUpperCase().charCodeAt( i );
	  
		if( valid.indexOf( String.fromCharCode( charac ) ) == -1 )
		if(!( ( ( charac >= 65 ) && ( charac <= 90 ) ) || ( ( charac >= 48 ) && ( charac <= 57 ) ) ) ) 
		   return( false );
	}	
	
  return( true );
}
/**
 * @objetivo	: ProtoType CNPJ
 * @parametro	: sem parâmetros
 * @retorno		: data
 * @autor       : João Neto
 * @versão		: 2, 10 de Dezembro  de  2003
 */					
String.prototype.isCNPJ = function()
{
    var b = [6,5,4,3,2,9,8,7,6,5,4,3,2], c = this;
    if((c = c.replace(/[^\d]/g,"").split("")).length != 14) return false;
    for(var i = 0, n = 0; i < 12; n += c[i] * b[++i]);
    if(c[12] != (((n %= 11) < 2) ? 0 : 11 - n)) return false;
    for(var i = 0, n = 0; i <= 12; n += c[i] * b[i++]);
    if(c[13] != (((n %= 11) < 2) ? 0 : 11 - n)) return false;
    return true;
}

/**
 * @objetivo	: Mostra Hint de Coment' + String.fromCharCode( 224 ) + 'rio ( Definitivo )
 * @parametro	: current     : objeto. ( Requerido )
 * @parametro	: e   		  : objeto. ( Requerido )
 * @parametro	: comentario  : objeto. ( Requerido )
 * @retorno		: void 
 * @autor   	: Jefferson Petilo( jefferson@netdom.com.br )
 * @versão		: 1, 03 de Março de  2004
 */					
function showPopup( current , e , comentario )
{
  var oPopup = window.createPopup();	
  var oPopupBody						 = oPopup.document.body;
	  oPopupBody.style.backgroundColor 	 = cor_primaria;
	  oPopupBody.style.border 		 	 = 'solid black 1px';    
	  oPopupBody.style.fontFamily 	 	 = 'Tahoma';
	  oPopupBody.style.fontSize 		 = '11px';
	  oPopupBody.style.marginleft 		 = '5px';
	  
  var altura 		= 1;
  var largura 	 	= 320;
  var deslocamento  = ( parseInt( current.offsetHeight ) + 5 );
	
	 if( comentario.length > 50 )
	  altura  = Math.ceil( comentario.length / 50 );
	else
	  largura = Math.ceil( comentario.length * 10 );
 
	oPopupBody.innerHTML = comentario; 
	
	switch( current.type )
	{
		case 'select-one': 
		case 'select-multiple': 
			  deslocamento = ( altura == 1 )? ( -1 * ( parseInt( current.offsetHeight  )+ 5 ) ) : ( -1 * ( parseInt( current.offsetHeight ) + ( 10 * altura ) ) );
		break;
	}
	
   oPopup.show( 0 , deslocamento , largura, 15 * altura , current );
}

/**
 * @objetivo	: Controla Campos do Formul' + String.fromCharCode( 224 ) + 'rio ( Validação )
 * @parametro	: num_forms   : objeto. ( Requerido )
 * @retorno		: void 
 * @autor       : Jefferson Petilo( jefferson@netdom.com.br )
 * @versão		: 1, 5 de Fevereiro  de  2003
 * @sintaxe 	: window.onload = function(){ fnc_controla_campos( 1 ); }
 */					
function fnc_controla_campos( num_forms )
{
  var v_funcao    = '';
  var v_tab_index = ( fnc_controla_campos.arguments.length > 1 )? true:false;
			
  for( var j = 0; j < num_forms; j++ ) 
  { 
	 var formulario = eval( document.forms[ j ] );
	 
	 for( var i = 0; i < formulario.length; i++ )
	 {		
		//inicializa contagem de tab_index
		if( v_tab_index )  formulario.elements[ i ].tabIndex = 0;		
		
		//OnFocus()
		if( formulario.elements[ i ].onfocus )
		{
			// adiciona nova função no evento onFocus() (caso já exista alguma função nela )
			formulario.elements[ i ].v_funcao_focus = formulario.elements[ i ].onfocus;
			formulario.elements[ i ].onfocus 		= function()
			{ 
				// adiciona nova função
				v_funcao = String( this.v_funcao_focus ).replace('function anonymous()','');
				v_funcao = String( v_funcao ).replace('}','');
				v_funcao = String( v_funcao ).replace('{','');																
				v_funcao = Trim( v_funcao ); 
				
				eval( v_funcao );											
				
				 // pinta a cor da célula
				 if( fnc_verifica_tipo( this ) ) event.srcElement.style.backgroundColor = cor_primaria ;  
				 
				 if( event.srcElement.hint )
				 {
					// cria layer caso navegador seja internet explorer atualizado, caso contrário utiliza a opção title html
					if(  window.xbDetectBrowser && navigator.org == 'microsoft' && navigator.version >=6 ) 
						showPopup( event.srcElement , event , event.srcElement.hint );
						
					 else 
						event.srcElement.title = event.srcElement.hint;
					 
					 // mostra texto na barra de status
					 window.status 	 = event.srcElement.hint; 
				 }
			  }
 		 } else {

			// adiciona nova função no evento onFocus() 
			 formulario.elements[ i ].onfocus 		= function()
			 { 
				// pinta a cor da célula
				if( fnc_verifica_tipo( this ) )  event.srcElement.style.backgroundColor = cor_primaria; 
			    if( event.srcElement.hint )
				{
					// cria layer caso navegador seja internet explorer atualizado, caso contrário utiliza a opção title html
					if(  window.xbDetectBrowser && navigator.org == 'microsoft' && navigator.version >=6 ) 
						showPopup( event.srcElement , event , event.srcElement.hint );
					else 
						event.srcElement.title = event.srcElement.hint;
					 
					 // mostra texto na barra de status
					 window.status 	 = event.srcElement.hint; 
			    }
			}
	 	}
		//OnBlur()
		if( fnc_verifica_tipo( formulario.elements[ i ] ) )
		{
			//incrementa contagem de tab_index
			if( v_tab_index ) formulario.elements[ i ].tabIndex = i + 1;   

			// quando pressiona help na showModal mostra popup customizado ou texto na barra de status 
			formulario.elements[ i ].onhelp = function()
			{ 
				// cria layer caso navegador seja internet explorer atualizado, caso contrário utiliza a opção title html
				if( window.xbDetectBrowser && navigator.org == 'microsoft' && navigator.version >=6 ) 
					showPopup( event.srcElement , event , event.srcElement.hint );
				else 
					window.status 	 = event.srcElement.hint; 
			}
					
			if ( formulario.elements[ i ].onblur )
			{
				// adiciona nova função no evento onBlur() (caso já exista alguma função nela )
				formulario.elements[ i ].v_funcao   = formulario.elements[ i ].onblur;
				formulario.elements[ i ].onblur 	= function()
				{ 
 				  // adiciona nova função
					v_funcao = String( this.v_funcao ).replace('function anonymous()','');
					v_funcao = String( v_funcao ).replace('}','');
					v_funcao = String( v_funcao ).replace('{','');																
					v_funcao = Trim( v_funcao );
					
					eval( v_funcao );																
					
					event.srcElement.style.backgroundColor = '';
				}
			}  else { 
				// adiciona nova função no evento onBlur() 
				formulario.elements[ i ].onblur = function()
				{ 
				  event.srcElement.style.backgroundColor = ''; 
				}															   
			}
  	     }										 
	 }	
  }
}	

/**
 * @objetivo	: Mostra Mensagem de Erro
 * @parametro	: p_mensagem  : string. ( Requerido )
 * @parametro	: p_campo     : objeto. ( Requerido )
 * @parametro	: form   	  : objeto. ( Requerido )
 * @retorno		: booleano
 * @autor       : Jefferson Petilo( jefferson@netdom.com.br )  
 * @versão		: 1, 5 de Fevereiro  de  2003
 */					
function fnc_erro( p_mensagem, p_campo, form )
{
  alert( p_mensagem );
  
  if( !p_campo.readOnly )
  {
    switch( p_campo.type )
    {
		case 'select-one' :
		case 'select-multiple' :
		case 'text' :
		case 'textarea' :
		case 'radio' 	   	   : 
		case 'checkbox' 	   : 
		case 'password' :
						 p_campo.focus();
		break;	
	}
  }
}	

/**
 * @objetivo	: Descrição da Função
 * @parametro	: param1   : tipo. ( Requerido )
 * @retorno		: returntype 
 * @autor       : Jefferson Petilo( jefferson@netdom.com.br )
 * @versão		: 1, 31 de Março  de  2004
 */					
function fnc_verifica_tipo( p_campo )
{
  if( !p_campo.readOnly )
  {
	switch( p_campo.type ) 
	{
		case 'text' 		   : 
		case 'select-one' 	   : 
		case 'select-multiple' : 
		case 'textarea' 	   : 
		case 'radio' 	   	   : 
		case 'file'			   : 
		case 'checkbox' 	   : 
		case 'password' 	   : return ( true ); 	break;
		default 			   : return ( false );  break;
	}
  }
}

/**
 * @objetivo	: Valida Formul' + String.fromCharCode( 224 ) + 'rio
 * @parametro	: form   : objeto. ( Requerido )
 * @retorno		: void
 * @autor       : Jefferson Petilo( jefferson@netdom.com.br )
 * @versão		: 1, 5 de Fevereiro  de  2003
 */					
function fnc_verifica_form( formulario )
{
 var args	= fnc_verifica_form.arguments;
 var secao 	= false;
	
 if( args.length == 2 ) secao = true;	
	
	for( var i = 0; i < formulario.length; i++ )
	{
  	  if( secao )
	  {
	    if( args[ 1 ] == formulario.elements[ i ].secao ) 
			if( ( formulario.elements[ i ].obrigatorio == 1 ) && (! formulario.elements[ i ].value ) )
			{
			    mensagem = 'O campo ' + formulario.elements[ i ].display + ' ' + String.fromCharCode( 233 ) + '  requerido.';
				return 	 ( fnc_erro( mensagem , formulario.elements[ i ], formulario ) );
			}
	  } else {
		    if( ( formulario.elements[ i ].obrigatorio == 1 ) && ( !formulario.elements[ i ].value ) )
		    {
				mensagem = 'O campo ' + formulario.elements[ i ].display + ' ' +  String.fromCharCode( 233 ) + '  requerido.';
				return fnc_erro( mensagem , formulario.elements[ i ], formulario );
		     }
	  }
	  if( secao )
	  {
		 // verifica se existe seção
		 if( args[ 1 ] == formulario.elements[ i ].secao) 
		 {
			// verifica se é numérico 
			if( ( formulario.elements[ i ].value ) && ( formulario.elements[ i ].tipo == 'numerico') && ( !formulario.elements[ i ].value.isNumber() ) )
			{
				mensagem = 'O valor do campo ' + formulario.elements[ i ].display + ' deve ser num' + String.fromCharCode( 233 ) + 'rico.';
				return fnc_erro( mensagem , formulario.elements[ i ], formulario )
		    }			
			// verifica se é data
			if( ( formulario.elements[ i ].value) && ( formulario.elements[ i ].tipo == 'data') && (!formulario.elements[ i ].value.substr(0,10 ).isDate() ) )
			{
				mensagem = 'O valor do campo ' + formulario.elements[ i ].display + ' deve ser uma data v' + String.fromCharCode( 224 ) + 'lida.';
				return fnc_erro( mensagem , formulario.elements[ i ], formulario )
		    }			
			// verifica se é e-mail
			if( ( formulario.elements[ i ].value ) && ( formulario.elements[ i ].tipo == 'email') && ( !formulario.elements[ i ].value.isMail() ) )
			{
				mensagem = 'O valor do campo ' + formulario.elements[ i ].display + ' deve ser um e-mail v'+ String.fromCharCode( 225 )+'lido.';
				return fnc_erro( mensagem , formulario.elements[ i ], formulario )
			}			
			
			// verifica se é CNPJ
			if( ( formulario.elements[ i ].value ) && ( formulario.elements[ i ].tipo == 'cnpj') && ( !formulario.elements[ i ].value.isCNPJ() ) )
			{
				mensagem = 'O valor do campo ' + formulario.elements[ i ].display + ' deve ser um nº v' + String.fromCharCode( 224 ) + 'lido de CNPJ.';
				return fnc_erro( mensagem , formulario.elements[ i ], formulario )
			}			
			
		  }
	    } else {
		  // verifica se é numérico 
		  if( ( formulario.elements[ i ].value ) && ( !formulario.elements[ i ].secao ) && ( formulario.elements[ i ].tipo == 'numerico' ) && ( !formulario.elements[ i ].value.isNumber() ) )
	      {
				mensagem = 'O valor do campo ' + formulario.elements[ i ].display + ' deve ser num' + String.fromCharCode( 233 ) + 'rico.';
				return fnc_erro( mensagem , formulario.elements[ i ], formulario )
		  }			
		  // verifica se é data
		  if( ( formulario.elements[ i ].value ) && ( !formulario.elements[ i ].secao ) && ( formulario.elements[ i ].tipo == 'data') && (!formulario.elements[ i ].value.substr(0,10 ).isDate() ) )
		  {
				mensagem = 'O valor do campo ' + formulario.elements[ i ].display + ' deve ser uma data v' + String.fromCharCode( 224 ) + 'lida.';
				return fnc_erro( mensagem , formulario.elements[ i ], formulario )
	      }			
		 // verifica se é e-mail
		 if( ( formulario.elements[ i ].value ) && ( !formulario.elements[ i ].secao ) && ( formulario.elements[ i ].tipo == 'email') && ( !formulario.elements[ i ].value.isMail() ) )
	     {
				mensagem = 'O valor do campo '+formulario.elements[ i ].display+' deve ser um e-mail.';
				return fnc_erro(mensagem,formulario.elements[ i ], formulario)
	     }			
		 // verifica se é CNPJ
		 if( ( formulario.elements[ i ].value ) && ( !formulario.elements[ i ].secao ) && ( formulario.elements[ i ].tipo == 'cnpj') && ( !formulario.elements[ i ].value.isCNPJ() ) )
		 {
				mensagem = 'O valor do campo '+formulario.elements[ i ].display+' deve ser um CNPJ v' + String.fromCharCode( 224 ) + 'lido.';
				return fnc_erro(mensagem,formulario.elements[ i ], formulario)
	     }		
	   }
	}
  return ( true );
}