﻿var is_ie = true;
var hlp_layer;
var hlp;
function Init(){
	var agt = navigator.userAgent.toLowerCase();
    is_ie = (agt.indexOf("msie")!=-1 && document.all);
    var h = '<div id="hlp_layer" style="position:absolute;z-index:100;display:none;background-color:#FFF;">';
        h += '<table cellspacing="0" cellpadding="0" style="border:1px solid #7E98D6;width:142px">';

        ///h += '<!--tr><td>';
       /// h += '<div style="color:#1A9100;font-size:12px;background-color:#C8DAF3;"> <img src=help.gif> 帮助</div>';
        ///h += '</td></tr-->';

        h += '<tr><td id="hlp" style="padding:3px;font-size:12px;"></td></tr>';

        h += '</table>';
        h += '</div>';
    document.write(h);
    hlp_layer = document.getElementById('hlp_layer');
    hlp = document.getElementById('hlp');
    if (is_ie){
      document.attachEvent("onmousemove", getpos);
    }
    else{
       document.addEventListener("mousemove", getpos, true);
    }
}
function getpos(e) {
	obj=e.target?e.target:e.srcElement;
	//alert(obj.src);
	if(obj.className!="small_pic"){
		hlp_layer.style.display="none";
		return;
	}
	try{
			
    if(obj.src){
    	///hlp.innerHTML='<img src="'+obj.src+'">';
    	var image=new Image(); 
			image.src=obj.src; 
			sWH="";
			if(image.width >image.height && image.width>200){
				sWH='width="350px"';
			}
			else{
				if(image.height>200)
					sWH='height="350px"';
			}
			hlp.innerHTML='<img src="'+obj.src+'" '+sWH+'>';	///<br>'+image.width+'px×'+image.height+'px';
    	hlp_layer.style.display="";
    }
    else{hlp_layer.style.display="none";}

    }
    catch(e){hlp_layer.style.display="none";return false;}
		var r = new Array();
		r['x'] = obj.offsetLeft;
		r['y'] = obj.offsetTop;
		while(obj = obj.offsetParent) {
			r['x'] += obj.offsetLeft;
			r['y'] += obj.offsetTop;
		}

	  if (is_ie) {

    r['x'] = window.event.clientX + document.documentElement.scrollLeft+ document.body.scrollLeft;

    r['y'] = window.event.clientY + document.documentElement.scrollTop+ document.body.scrollTop;

  }else {

    r['x'] = e.clientX + window.scrollX;

    r['y'] = e.clientY + window.scrollY;

  }

	hlp_layer.style.left = r['x']+50+'px';

	if(r['x']+hlp_layer.scrollWidth>document.body.clientWidth){
		hlp_layer.style.left = r['x']-300+'px';
	}
//hlp.innerHTML=hlp_layer.scrollWidth+''+document.body.scrollWidth+''+document.body.clientWidth;

    hlp_layer.style.top = r['y']+'px';
}
Init();

















function ValForm( theForm )
{
	var val_id      = 'REQ';
	var msg_intro   = 'Os campos abaixo são requeridos:\n';
	var msg_campos  = ''; // nome dos campos requeridos
	var foco_campo  = ''; // foco no primeiro campo requerido
	var msg_req     = '- ';
	var msg_req2    = '\n';
	var objetos     = theForm.length;
	var cont_campos = 0;  // contador de campos requeridos
	var tt_campos   = 10; // total de campos exibidos como requerido

	for (var i=0; i<objetos; i++)
	{

		// tirar espacos do campo
		while(''+theForm.elements[i].value.charAt(theForm.elements[i].value.length-1)==' ')theForm.elements[i].value=theForm.elements[i].value.substring(0,theForm.elements[i].value.length-1);

		// tirar apostrofes do campo
		//while(''+theForm.elements[i].value.charAt(theForm.elements[i].value.length-1)=="'")theForm.elements[i].value=theForm.elements[i].value.substring(0,theForm.elements[i].value.length-1);

		// obrigar campo texto
		if ((theForm.elements[i].type == 'text') && (theForm.elements[i].id.indexOf(val_id) != -1) && (theForm.elements[i].disabled == false) && (theForm.elements[i].value.length == 0))
		{
				if (cont_campos < tt_campos) {msg_campos = msg_campos + msg_req + verNomeCampo(theForm.elements[i]) + msg_req2};
				cont_campos = cont_campos + 1;
				if (foco_campo.length == 0) {foco_campo = theForm.elements[i]}
		}

		// obrigar campo password
		if ((theForm.elements[i].type == 'password') && (theForm.elements[i].id.indexOf(val_id) != -1) && (theForm.elements[i].disabled == false) && (theForm.elements[i].value.length == 0))
		{
				if (cont_campos < tt_campos) {msg_campos = msg_campos + msg_req + verNomeCampo(theForm.elements[i]) + msg_req2};
				cont_campos = cont_campos + 1;
				if (foco_campo.length == 0) {foco_campo = theForm.elements[i]}
		}

		// obrigar campo textarea
		else if ((theForm.elements[i].type == 'textarea') && (theForm.elements[i].id.indexOf(val_id) != -1) && (theForm.elements[i].disabled == false) && (theForm.elements[i].value.length == 0))
		{
				if (cont_campos < tt_campos) {msg_campos = msg_campos + msg_req + verNomeCampo(theForm.elements[i]) + msg_req2};
				cont_campos = cont_campos + 1;
				if (foco_campo.length == 0) {foco_campo = theForm.elements[i]}
		}

		// obrigar campo hidden
		if ((theForm.elements[i].type == 'hidden') && (theForm.elements[i].id.indexOf(val_id) != -1) && (theForm.elements[i].disabled == false) && (theForm.elements[i].value.length == 0))
		{
				if (cont_campos < tt_campos) {msg_campos = msg_campos + msg_req + verNomeCampo(theForm.elements[i]) + msg_req2};
				cont_campos = cont_campos + 1;
		}

		// obrigar campo combobox (listbox)
		else if ((theForm.elements[i].type == 'select-one') && (theForm.elements[i].id.indexOf(val_id) != -1) && (theForm.elements[i].disabled == false) && (theForm.elements[i].selectedIndex == 0))
		{
				if (cont_campos < tt_campos) {msg_campos = msg_campos + msg_req + verNomeCampo(theForm.elements[i]) + msg_req2};
				cont_campos = cont_campos + 1;
				if (foco_campo.length == 0) {foco_campo = theForm.elements[i]}
		}

		// obrigar campo combobox multiple (listbox multiple)
		else if ((theForm.elements[i].type == 'select-multiple') && (theForm.elements[i].id.indexOf(val_id) != -1) && (theForm.elements[i].disabled == false) && (theForm.elements[i].value.length == 0))
		{
				if (cont_campos < tt_campos) {msg_campos = msg_campos + msg_req + verNomeCampo(theForm.elements[i]) + msg_req2};
				cont_campos = cont_campos + 1;
				if (foco_campo.length == 0) {foco_campo = theForm.elements[i]}
		}

		// obrigar campo checkbox
		else if ((theForm.elements[i].type == 'checkbox') && (theForm.elements[i].id.indexOf(val_id) != -1) && (theForm.elements[i].disabled == false) && (theForm.elements[i].checked == false))
		{
				if (cont_campos < tt_campos) {msg_campos = msg_campos + msg_req + verNomeCampo(theForm.elements[i]) + msg_req2};
				cont_campos = cont_campos + 1;
				if (foco_campo.length == 0) {foco_campo = theForm.elements[i]}
		}

		// obrigar campo radio
		else if ((theForm.elements[i].type == 'radio') && (theForm.elements[i].id.indexOf(val_id) != -1) && (theForm.elements[i].disabled == false) && (theForm.elements[i].checked == false))
		{
				if (cont_campos < tt_campos) {msg_campos = msg_campos + msg_req + verNomeCampo(theForm.elements[i]) + msg_req2};
				cont_campos = cont_campos + 1;
				if (foco_campo.length == 0) {foco_campo = theForm.elements[i]}
		}

		// obrigar campo file
		if ((theForm.elements[i].type == 'file') && (theForm.elements[i].id.indexOf(val_id) != -1) && (theForm.elements[i].disabled == false) && (theForm.elements[i].value.length == 0))
		{
				if (cont_campos < tt_campos) {msg_campos = msg_campos + msg_req + verNomeCampo(theForm.elements[i]) + msg_req2};
				cont_campos = cont_campos + 1;
				if (foco_campo.length == 0) {foco_campo = theForm.elements[i]}
		}

    	else if ((theForm.elements[i].type == 'submit') && (msg_campos.length == 0))
        	{theForm.elements[i].disabled=true;}
	}


	if (msg_campos.length != 0)
	{
		if (cont_campos > tt_campos) // ha mais campos que a variavel tt_campos
		{
			msg_campos = msg_campos + '- entre outros.';
		}

		destReq(theForm, val_id, true);
		window.alert(msg_intro + msg_campos);
		destReq(theForm, val_id, false);
		if (foco_campo.length != 0)
		{
			eval("foco_campo.focus()")
		}
		return false;
	}
	else
	{
		return true;
	}

}

// funcao para a ValForm buscar o nome do campo pelo id="REQ|Nome do Campo"
function verNomeCampo(campo)
{
	if (campo.id.indexOf('|') != -1)
	{
			var arr_id = campo.id.split('|');
			return arr_id[1];
	}
	else
	{
			return campo.name;
	}
}

// funcao para a Abrir foto"

function AbrirFoto(foto)
{
	var w2 = (screen.width / 2);
	var h2 = (screen.height / 2);

	winPopup('../admin/show_image.asp?f='+foto, 'FotoGrande', w2, h2, 1, 'status=yes');
}

/*
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
::: Destacar campos obrigatorios
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
// Modo de Usar: destReq(document.nome_form, true)
// true = destacar, false = normal

function destReq(theForm, val_id, dest)
{
	//var val_id = 'REQ';
	var objetos = theForm.length;

	for (var i=0; i<objetos; i++)
	{
		if (theForm.elements[i].id.indexOf(val_id) != -1)
		{
			if (dest)
			{
				theForm.elements[i].style.background='#F0F0F0';
			}
			else
			{
				theForm.elements[i].style.background='#FFFFFF';
			}
		}
	}
}

/*
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
::: Formatar Text com Mascaras
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
// Modo de Usar: onKeyPress="return txtBoxFormat(document.nomeform, 'NOMECAMPO', '99/99/9999', event);"

  function txtBoxFormat(objForm, strField, sMask, evtKeyPress) {
    var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

    if(document.all) { // Internet Explorer
      nTecla = evtKeyPress.keyCode;
	  sValue = objForm[strField].value;
	}
    else if(document.layers) { // Nestcape
      nTecla = evtKeyPress.which;
	  sValue = objForm.strField.value;
    }
	else { // Firefox
		sValue = eval("document.all."+strField+".value");
	}

    // Limpa todos os caracteres de formatação que
    // já estiverem no campo.
    sValue = sValue.toString().replace( "-", "" );

    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( ":", "" );
    sValue = sValue.toString().replace( ":", "" );
    sValue = sValue.toString().replace( "|", "" );
    sValue = sValue.toString().replace( "|", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( " ", "" );
    sValue = sValue.toString().replace( " ", "" );
    fldLen = sValue.length;
    mskLen = sMask.length;

    i = 0;
    nCount = 0;
    sCod = "";
    mskLen = fldLen;

    while (i <= mskLen) {
      bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/"))
      bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))
      bolMask = bolMask || ((sMask.charAt(i) == ":") || (sMask.charAt(i) == "|"))

      if (bolMask) {
        sCod += sMask.charAt(i);
        mskLen++; }
      else {
        sCod += sValue.charAt(nCount);
        nCount++;
      }

      i++;
    }

	if(document.all)
	{
    	objForm[strField].value = sCod;
	}
	else
	{
		eval("document.all."+strField+".value") = sCod;
	}

    if (nTecla != 8) { // backspace
      if (sMask.charAt(i-1) == "9") { // apenas números...
        return ((nTecla > 47) && (nTecla < 58)); } // números de 0 a 9
      else { // qualquer caracter...
        return true;
      } }
    else {
      return true;
    }
  }


/*
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
::: Comparar Horas
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
// Modo de Usar: "javascript:comparaHora(campo_hora1, campo_hora2)"

  function comparaHora(campo_hora1, campo_hora2) { // funcao para comparar 2 campos hora

    if ((campo_hora1.value.length != 0) && (campo_hora2.value.length != 0))
    {
      var hora1		= campo_hora1.value.substring(0, 2); // pegar hora1
      var minuto1	= campo_hora1.value.substring(3, 5); // pegar minuto1
      var hora2		= campo_hora2.value.substring(0, 2); // pegar hora2
      var minuto2	= campo_hora2.value.substring(3, 5); // pegar minuto2

      hora1 = hora1 + minuto1; //une hora com numero para formar um numero inteiro
      hora2 = hora2 + minuto2;

      if (hora2 <= hora1) //hora termino menos que hora inicio
      {
        window.alert('A Hora de Término não pode ser igual ou menor que a Hora de Início.');
		campo_hora2.value='';
		campo_hora2.focus();
      }

    }

  }

/*
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
::: Preload Images
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
// Modo de Usar: preloadImages('http://www.site.com/img1.gif','http://www.site.com/img2.gif')

	function preloadImages() { //v3.0
  		var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    		var i,j=d.MM_p.length,a=preloadImages.arguments; for(i=0; i<a.length; i++)
    		if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
	}

/*
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
:::Filtrando as extensões de arquivo no upload: (gif, jpg, png)
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
// Modo de Usar: onBlur="ChecaExtensaoArquivo(this, ',.doc,.rtf,')"

function ChecaExtensaoArquivo(field, extensoesOk){
	//var extensoesOk = ",.doc,.rtf,";
	var extensao    = "," + field.value.substr( field.value.length - 4 ).toLowerCase() + ",";

	if (field.value.length != 0) {
		if( extensoesOk.indexOf( extensao ) == -1 )
		{
			alert( field.value + "\nO arquivo não possui uma extensão válida! Selecione novamente." )
			field.value = '';field.focus();
			return false;
		}
	}
	return true;
}

/*
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
::: Validar E-mail
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
// Modo de Usar: onBlur="ValEmail(this)"

	 function ValEmail(field) { // validar campo email
	 if (field.value.length != 0)
	 {
		if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(field.value)){
		return (true)
		}
		field.value = '';
		alert("O E-mail é inválido! Digite novamente.")
		field.focus();
		field.select();
		return (false)
	 }
	}

/*
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
::: Validar Campo Numérico com : (dois pontos)
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
// Modo de Usar: onKeyPress="return ValNumero_DP(event, this);"

  function ValNumero_DP(e, campo) {

	if (document.all) // Internet Explorer
	{
		var tecla = event.keyCode;
	}
	else if (document.layers) // Nestcape
	{
		var tecla = e.which;
	}

	if (campo.value.length == 2)
	{
		campo.value = campo.value + ':'; // adiciona : (dois pontos)
	}

	if (tecla > 47 && tecla < 58) // numeros de 0 a 9 e : (dois pontos)
	{
		return true;
	}
	else
	{
		if (tecla != 8) // backspace
		{
			return false;
		}
		else
		{
			return true;
		}
	}
  }


/*
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
::: Validar CNPJ
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
// Modo de Usar: onBlur="javascript:valCNPJCPF(this);"

// CNPJ TEM ENTRE 7 A 15 CARACTERES
// CPF TEM 11 CARACTERES

function valCNPJCPF(valor, tipo)
{
	var tipomsg = 'CNPJ';

	if (tipo == 2)
	{
		tipomsg = 'CPF';
	}

	if ( (valor.value.length > 0) && (isCPFCNPJ(valor.value, tipo) == false) )
	{
		valor.value = '';
		window.alert(tipomsg+' inválido! Digite novamente.');
		valor.focus();
	}

	function isCPFCNPJ(campo,pType){
	   if( campo.length == 0 ){return false;}

	   var campo_filtrado = "", valor_1 = " ", valor_2 = " ", ch = "";
	   var valido = false;

	   for (i = 0; i < campo.length; i++){
	      ch = campo.substring(i, i + 1);
	      if (ch >= "0" && ch <= "9"){
	         campo_filtrado = campo_filtrado.toString() + ch.toString()
	         valor_1 = valor_2;
	         valor_2 = ch;
	      }
	      if ((valor_1 != " ") && (!valido)) valido = !(valor_1 == valor_2);
	   }
	   if (!valido) campo_filtrado = "12345678912";

	   if (campo_filtrado.length < 11){
	      for (i = 1; i <= (11 - campo_filtrado.length); i++){campo_filtrado = "0" + campo_filtrado;}
	   }

	   if(pType == 2){
	      if ( ( campo_filtrado.substring(9,11) == checkCPF( campo_filtrado.substring(0,9) ) ) && ( campo_filtrado.substring(11,12)=="") ){return true;}
	   }

	   if((pType <= 1) || (pType == 0)){
	      if (campo_filtrado.length >= 14){
	         if ( campo_filtrado.substring(12,14) == checkCNPJ( campo_filtrado.substring(0,12) ) ){ return true;}
	      }
	   }

	   return false;
	}

	function checkCNPJ(vCNPJ){
	   var mControle = "";
	   var aTabCNPJ = new Array(5,4,3,2,9,8,7,6,5,4,3,2);
	   for (i = 1 ; i <= 2 ; i++){
	      mSoma = 0;
	      for (j = 0 ; j < vCNPJ.length ; j++)
	         mSoma = mSoma + (vCNPJ.substring(j,j+1) * aTabCNPJ[j]);
	      if (i == 2 ) mSoma = mSoma + ( 2 * mDigito );
	      mDigito = ( mSoma * 10 ) % 11;
	      if (mDigito == 10 ) mDigito = 0;
	      mControle1 = mControle ;
	      mControle = mDigito;
	      aTabCNPJ = new Array(6,5,4,3,2,9,8,7,6,5,4,3);
	   }
	   return( (mControle1 * 10) + mControle );
	}

	function checkCPF(vCPF){
	   var mControle = ""
	   var mContIni = 2, mContFim = 10, mDigito = 0;
	   for (j = 1 ; j <= 2 ; j++){
	      mSoma = 0;
	      for (i = mContIni ; i <= mContFim ; i++)
	         mSoma = mSoma + (vCPF.substring((i-j-1),(i-j)) * (mContFim + 1 + j - i));
	      if (j == 2 ) mSoma = mSoma + ( 2 * mDigito );
	      mDigito = ( mSoma * 10 ) % 11;
	      if (mDigito == 10) mDigito = 0;
	      mControle1 = mControle;
	      mControle = mDigito;
	      mContIni = 3;
	      mContFim = 11;
	   }
	   return( (mControle1 * 10) + mControle );
	}
}


/*
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
::: Campo Hora
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
// Modo de Usar: OnBlur="txtHora(this)"

  function txtHora(campo_hora) { // funcao para validar hora/minuto

    if ((campo_hora.value.length != 5) && (campo_hora.value.length != 0))
    {
      window.alert('Campo Hora Incorreto. Digite Novamente.\nUtilize o formato hh:mm.');
      campo_hora.value = '';campo_hora.focus();
    }
    else
    {
      var hora		= campo_hora.value.substring(0, 2); // pegar hora
      var minuto	= campo_hora.value.substring(3, 5); // pegar minuto
      var erro = 0;

      if ( (campo_hora.value.substring(2, 3) != ':') && (campo_hora.value.length != 0) ) // dois pontos (invalido)
      {
        erro = 1;
      }

      if ((parseInt(hora) < 0) || (parseInt(hora) > 23)) // hora invalida
      {
        erro = 1;
      }

      if ((parseInt(minuto) < 0) || (parseInt(minuto) > 59)) // minuto invalido
      {
        erro = 1;
      }

      if (erro == 1)
      {
        window.alert('Campo Hora Incorreto. Digite Novamente.\nUtilize o formato hh:mm.');
	campo_hora.value = '';campo_hora.focus();
      }

    }

  }

/*
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
::: Comparar Horas
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
// Modo de Usar: "javascript:comparaHora(campo_hora1, campo_hora2)"

  function comparaHora(campo_hora1, campo_hora2) { // funcao para comparar 2 campos hora

    if ((campo_hora1.value.length != 0) && (campo_hora2.value.length != 0))
    {
      var hora1		= campo_hora1.value.substring(0, 2); // pegar hora1
      var minuto1	= campo_hora1.value.substring(3, 5); // pegar minuto1
      var hora2		= campo_hora2.value.substring(0, 2); // pegar hora2
      var minuto2	= campo_hora2.value.substring(3, 5); // pegar minuto2

      hora1 = hora1 + minuto1; //une hora com numero para formar um numero inteiro
      hora2 = hora2 + minuto2;

      if (hora2 <= hora1) //hora termino menos que hora inicio
      {
        window.alert('A Hora de Término não pode ser igual ou menor que a Hora de Início.');
		campo_hora2.value='';
		campo_hora2.focus();
      }

    }

  }

/*
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
::: Janela Pop Up Centralizada
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
// Modo de Usar: javascript:winPopup('pagina', 'nome', largura, altura, centralizar, 'propriedades da janela')
//pagina = caminho da pagina ou site para abrir na popup
//nome = nome da janela
//largura = largura da janela em px | altura = altura da janela em px
//centralizar = 1 ou 2 (1 = centralizada | 2 = sem centralizar)
//propriedades da janela = scrollbars=yes, status=no, etc etc

    function winPopup(pag, nome, larg, alt, centralizar, opcoes) { // abrir janela popup

  	  if (centralizar == 1)
	  {
	    var winl = (screen.width - larg) / 2;
	    var wint = (screen.height - alt) / 2;
			if ((alt >= 500) && (alt <= 540)) { wint = wint - 20;}
	  }
	  else
	  {
	    var winl = 0;
	    var wint = 0;
	  }

	  if (opcoes != '')
	  {
	    opcoes = ', ' + opcoes;
      }
	  newWindow = window.open('' + pag + '',''+nome+'','width=' + larg + ',height=' + alt + ',top='+wint+',left='+winl+'' + opcoes + '');
	  newWindow.focus();
    }


/*
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
::: Voltar Quantas Telas for Necessário
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
// Modo de Usar: OnBlur="GoBack(Número) onde Número é a quantidade de telas que deseja voltar o padrão é 1"

function GoBack(Qtde)
{
	if (Qtde==null)
		Qtde=1;
	if (Qtde>0)
		Qtde *= (-1);
	history.go(Qtde);
}


/*

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
::: Validar Data
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
// Modo de Usar: OnBlur="ValData(this)"

    function ValData(field) { // campo data (dd/mm/aaaa)

	var checkstr = "0123456789";
	var DateField = field;
	var Datevalue = "";
	var DateTemp = "";
	var separador = "/";
	var day; var month; var year;
	var leap = 0;
	var err = 0;
	var i;

	err = 0;
	DateValue = DateField.value;

	/* Deletar todos os caracteres que nao forem numeros (0-9) */
	for (i = 0; i < DateValue.length; i++) {
		if (checkstr.indexOf(DateValue.substr(i,1)) >= 0) {
			DateTemp = DateTemp + DateValue.substr(i,1);
		}
	}

	DateValue = DateTemp;

	/* Always change date to 8 digits - string*/
	/* if year is entered as 2-digit / always assume 20xx */
	if (DateValue.length == 6) {
		DateValue = DateValue.substr(0,4) + '20' + DateValue.substr(4,2); }
	if (DateValue.length != 8) {
		err = 19;}
	/* year is wrong if year = 0000 */
	year = DateValue.substr(4,4);
	if (year == 0) {
		err = 20;
	}

	/* Validation of month*/
	month = DateValue.substr(2,2);
	if ((month < 1) || (month > 12)) {
		err = 21;
	}

	/* Validation of day*/
	day = DateValue.substr(0,2);

	if (day < 1) {
		err = 22;
	}

	/* Validation leap-year / february / day */
	if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) {
		leap = 1;
	}
	if ((month == 2) && (leap == 1) && (day > 29)) {
		err = 23;
	}
	if ((month == 2) && (leap != 1) && (day > 28)) {
		err = 24;
	}

	/* Validation of other months */
	if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) {
		err = 25;
	}
	if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) {
		err = 26;
	}

	/* if 00 ist entered, no error, deleting the entry */
	if ((day == 0) && (month == 0) && (year == 00)) {
		err = 0; day = ""; month = ""; year = ""; separador = "";
	}
	/* if no error, write the completed date to Input-Field (e.g. 13/12/2001) */
	if (err == 0) {
		DateField.value = day + separador + month + separador + year;
	}
	/* Error-message if err != 0 */
	else if (field.value.length > 0) {
		field.value = '';
		alert("Campo Data Incorreto! Digite Novamente.\nUtilize o formato dd/mm/aaaa.");
		DateField.select();
		DateField.focus();
	}
}


/*
::: Limitar Quantidade de Caracteres em um Campo
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
// Modo de Usar: <input type="text" onKeyDown="limCampo(this, 8000);" onKeyUp="limCampo(this, 8000);">
function limCampo(campo, maxlimit) {
	if (campo.value.length > maxlimit)
	{
		campo.value = campo.value.substring(0, maxlimit);
	}
}


/*
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
::: Title
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
// Modo de Usar: <a href="?" class="helpLink" onclick="showHelpTip(event, 'Texto do title', true); return false">link</a>

	function Title(e, sHtml, bHideSelects) {

		// find anchor element
		var el = e.target || e.srcElement;
		while (el.tagName != "A")
			el = el.parentNode;

		// is there already a tooltip? If so, remove it
		if (el._helpTip) {
			helpTipHandler.hideHelpTip(el);
		}

		helpTipHandler.hideSelects = Boolean(bHideSelects);

		// create element and insert last into the body
		helpTipHandler.createHelpTip(el, sHtml);

		// position tooltip
		helpTipHandler.positionToolTip(e);

		// add a listener to the blur event.
		// When blurred remove tooltip and restore anchor
		el.onblur = helpTipHandler.anchorBlur;
		el.onkeydown = helpTipHandler.anchorKeyDown;
	}

	var helpTipHandler = {
		hideSelects:	false,

		helpTip:		null,

		showSelects:	function (bVisible) {
			if (!this.hideSelects) return;
			// only IE actually do something in here
			var selects = [];
			if (document.all)
				selects = document.all.tags("SELECT");
			var l = selects.length;
			for	(var i = 0; i < l; i++)
				selects[i].runtimeStyle.visibility = bVisible ? "" : "hidden";
		},

		create:	function () {
			var d = document.createElement("DIV");
			d.className = "help-tooltip";
			d.onmousedown = this.helpTipMouseDown;
			d.onmouseup = this.helpTipMouseUp;
			document.body.appendChild(d);
			this.helpTip = d;
		},

		createHelpTip:	function (el, sHtml) {
			if (this.helpTip == null) {
				this.create();
			}

			var d = this.helpTip;
			d.innerHTML = sHtml;
			d._boundAnchor = el;
			el._helpTip = d;
			return d;
		},

		// Allow clicks on A elements inside tooltip
		helpTipMouseDown:	function (e) {
			var d = this;
			var el = d._boundAnchor;

			if (!e) e = event;
			var t = e.target || e.srcElement;
			while (t.tagName != "A" && t != d)
				t = t.parentNode;
			if (t == d) return;

			el._onblur = el.onblur;
			el.onblur = null;
		},

		helpTipMouseUp:	function () {
			var d = this;
			var el = d._boundAnchor;
			el.onblur = el._onblur;
			el._onblur = null;
			el.focus();
		},

		anchorBlur:	function (e) {
			var el = this;
			helpTipHandler.hideHelpTip(el);
		},

		anchorKeyDown:	function (e) {
			if (!e) e = window.event
			if (e.keyCode == 27) {	// ESC
				helpTipHandler.hideHelpTip(this);
			}
		},

		removeHelpTip:	function (d) {
			d._boundAnchor = null;
			d.style.filter = "none";
			d.innerHTML = "";
			d.onmousedown = null;
			d.onmouseup = null;
			d.parentNode.removeChild(d);
			//d.style.display = "none";
		},

		hideHelpTip:	function (el) {
			var d = el._helpTip;
			d.style.visibility = "hidden";
			d.style.top = - el.offsetHeight - 100 + "px"
			d._boundAnchor = null;

			el.onblur = null;
			el._onblur = null;
			el._helpTip = null;
			el.onkeydown = null;

			this.showSelects(true);
		},

		positionToolTip:	function (e) {
			this.showSelects(false);
			var scroll = this.getScroll();
			var d = this.helpTip;

			var dw = (window.innerWidth || document.documentElement.offsetWidth) - 25;

			if (d.offsetWidth >= dw)
				d.style.width = dw - 10 + "px";
			else
				d.style.width = "";

			if (e.clientX > dw - d.offsetWidth)
				d.style.left = dw - d.offsetWidth + scroll.x + "px";
			else
				d.style.left = e.clientX - 2 + scroll.x + "px";
			d.style.top = e.clientY + 18 + scroll.y + "px";

			d.style.visibility = "visible";
		},

		// returns the scroll left and top for the browser viewport.
		getScroll:	function () {
			if (document.all && typeof document.body.scrollTop != "undefined") {	// IE model
				var ieBox = document.compatMode != "CSS1Compat";
				var cont = ieBox ? document.body : document.documentElement;
				return {x : cont.scrollLeft, y : cont.scrollTop};
			}
			else {
				return {x : window.pageXOffset, y : window.pageYOffset};
			}

		}

	};


/*
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
::: CurrencyFormat
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
// Modo de Usar: onKeyPress="return(currencyFormat(this,'.',',',event, 9))
// This script and many more are available free online at
// The JavaScript Source!! http://javascript.internet.com
// Ultimo Escopo define o tamanho máx de caracteres para valores

function currencyFormat(fld, milSep, decSep, e, maxchr) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;
	if (whichCode == 13) return true;  // Enter
	key = String.fromCharCode(whichCode);  // Get key value from key code
	if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
	len = fld.value.length;
	for(i = 0; i < len; i++)
	if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
	aux = '';
	for(; i < len; i++)
	if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
	aux += key;
	len = aux.length;
	if (len == 0) fld.value = '';
	if (len == 1) fld.value = '0'+ decSep + '0' + aux;
	if (len == 2) fld.value = '0'+ decSep + aux;
	if (len > 2 && len < (maxchr + 1)) {
	aux2 = '';
	for (j = 0, i = len - 3; i >= 0; i--) {
	if (j == 3) {
	aux2 += milSep;
	j = 0;
	}
	aux2 += aux.charAt(i);
	j++;
	}
	fld.value = '';
	len2 = aux2.length;
	for (i = len2 - 1; i >= 0; i--)
	fld.value += aux2.charAt(i);
	fld.value += decSep + aux.substr(len - 2, len);
	}
	return false;
}


/*
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
::: Desabilitar teclas [Backspace] e [Delete] em um campo
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
// Modo de Usar: onKeyDown="myKeyHandler();"

function myKeyHandler() {
	document.onKeyDown = myKeyHandler;

    if ((window.event && window.event.keyCode == 8) || (window.event && window.event.keyCode == 46)) {
        // try to cancel the backspace and delete
        window.event.cancelBubble = true;
        window.event.returnValue = false;
        return false;
    }
}



/*----------------------------------------------------------------------------\
|                            Sortable Table 1.04                              |
|-----------------------------------------------------------------------------|
|                         Created by Erik Arvidsson                           |
|                  (http://webfx.eae.net/contact.html#erik)                   |
|                      For WebFX (http://webfx.eae.net/)                      |
|-----------------------------------------------------------------------------|
| A DOM 1 based script that allows an ordinary HTML table to be sortable.     |
|-----------------------------------------------------------------------------|
|                  Copyright (c) 1998 - 2002 Erik Arvidsson                   |
|-----------------------------------------------------------------------------|
| This software is provided "as is", without warranty of any kind, express or |
| implied, including  but not limited  to the warranties of  merchantability, |
| fitness for a particular purpose and noninfringement. In no event shall the |
| authors or  copyright  holders be  liable for any claim,  damages or  other |
| liability, whether  in an  action of  contract, tort  or otherwise, arising |
| from,  out of  or in  connection with  the software or  the  use  or  other |
| dealings in the software.                                                   |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| This  software is  available under the  three different licenses  mentioned |
| below.  To use this software you must chose, and qualify, for one of those. |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| The WebFX Non-Commercial License          http://webfx.eae.net/license.html |
| Permits  anyone the right to use the  software in a  non-commercial context |
| free of charge.                                                             |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| The WebFX Commercial license           http://webfx.eae.net/commercial.html |
| Permits the  license holder the right to use  the software in a  commercial |
| context. Such license must be specifically obtained, however it's valid for |
| any number of  implementations of the licensed software.                    |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| GPL - The GNU General Public License    http://www.gnu.org/licenses/gpl.txt |
| Permits anyone the right to use and modify the software without limitations |
| as long as proper  credits are given  and the original  and modified source |
| code are included. Requires  that the final product, software derivate from |
| the original  source or any  software  utilizing a GPL  component, such  as |
| this, is also licensed under the GPL license.                               |
|-----------------------------------------------------------------------------|
| 2003-01-10 | First version                                                  |
| 2003-01-19 | Minor changes to the date parsing                              |
| 2003-01-28 | JScript 5.0 fixes (no support for 'in' operator)               |
| 2003-02-01 | Sloppy typo like error fixed in getInnerText                   |
| 2003-07-04 | Added workaround for IE cellIndex bug.                         |
|-----------------------------------------------------------------------------|
| Created 2003-01-10 | All changes are in the log above. | Updated 2003-07-04 |
\----------------------------------------------------------------------------*/


function SortableTable(oTable, oSortTypes) {

	this.element = oTable;
	this.tHead = oTable.tHead;
	this.tBody = oTable.tBodies[0];
	this.document = oTable.ownerDocument || oTable.document;

	this.sortColumn = null;
	this.descending = null;

	var oThis = this;
	this._headerOnclick = function (e) {
		oThis.headerOnclick(e);
	};


	// only IE needs this
	var win = this.document.defaultView || this.document.parentWindow;
	this._onunload = function () {
		oThis.destroy();
	};
	if (win && typeof win.attachEvent != "undefined") {
		win.attachEvent("onunload", this._onunload);
	}

	this.initHeader(oSortTypes || []);
}

SortableTable.gecko = navigator.product == "Gecko";
SortableTable.msie = /msie/i.test(navigator.userAgent);
// Mozilla is faster when doing the DOM manipulations on
// an orphaned element. MSIE is not
SortableTable.removeBeforeSort = SortableTable.gecko;

SortableTable.prototype.onsort = function () {};

// adds arrow containers and events
// also binds sort type to the header cells so that reordering columns does
// not break the sort types
SortableTable.prototype.initHeader = function (oSortTypes) {
	var cells = this.tHead.rows[0].cells;
	var l = cells.length;
	var img, c;
	for (var i = 0; i < l; i++) {
		c = cells[i];
		img = this.document.createElement("IMG");
		img.src = "images/spacer.gif";
		c.appendChild(img);
		if (oSortTypes[i] != null) {
			c._sortType = oSortTypes[i];
		}
		if (typeof c.addEventListener != "undefined")
			c.addEventListener("click", this._headerOnclick, false);
		else if (typeof c.attachEvent != "undefined")
			c.attachEvent("onclick", this._headerOnclick);
	}
	this.updateHeaderArrows();
};

// remove arrows and events
SortableTable.prototype.uninitHeader = function () {
	var cells = this.tHead.rows[0].cells;
	var l = cells.length;
	var c;
	for (var i = 0; i < l; i++) {
		c = cells[i];
		c.removeChild(c.lastChild);
		if (typeof c.removeEventListener != "undefined")
			c.removeEventListener("click", this._headerOnclick, false);
		else if (typeof c.detachEvent != "undefined")
			c.detachEvent("onclick", this._headerOnclick);
	}
};

SortableTable.prototype.updateHeaderArrows = function () {
	var cells = this.tHead.rows[0].cells;
	var l = cells.length;
	var img;
	for (var i = 0; i < l; i++) {
		img = cells[i].lastChild;
		if (i == this.sortColumn)
			img.className = "sort-arrow " + (this.descending ? "descending" : "ascending");
		else
			img.className = "sort-arrow";
	}
};

SortableTable.prototype.headerOnclick = function (e) {
	// find TD element
	var el = e.target || e.srcElement;
	while (el.tagName != "TD")
		el = el.parentNode;

	this.sort(SortableTable.msie ? SortableTable.getCellIndex(el) : el.cellIndex);
};

// IE returns wrong cellIndex when columns are hidden
SortableTable.getCellIndex = function (oTd) {
	var cells = oTd.parentNode.childNodes
	var l = cells.length;
	var i;
	for (i = 0; cells[i] != oTd && i < l; i++)
		;
	return i;
};

SortableTable.prototype.getSortType = function (nColumn) {
	var cell = this.tHead.rows[0].cells[nColumn];
	var val = cell._sortType;
	if (val != "")
		return val;
	return "String";
};

// only nColumn is required
// if bDescending is left out the old value is taken into account
// if sSortType is left out the sort type is found from the sortTypes array

SortableTable.prototype.sort = function (nColumn, bDescending, sSortType) {
	if (sSortType == null)
		sSortType = this.getSortType(nColumn);

	// exit if None
	if (sSortType == "None")
		return;

	if (bDescending == null) {
		if (this.sortColumn != nColumn)
			this.descending = true;
		else
			this.descending = !this.descending;
	}

	this.sortColumn = nColumn;

	if (typeof this.onbeforesort == "function")
		this.onbeforesort();

	var f = this.getSortFunction(sSortType, nColumn);
	var a = this.getCache(sSortType, nColumn);
	var tBody = this.tBody;

	a.sort(f);

	if (this.descending)
		a.reverse();

	if (SortableTable.removeBeforeSort) {
		// remove from doc
		var nextSibling = tBody.nextSibling;
		var p = tBody.parentNode;
		p.removeChild(tBody);
	}

	// insert in the new order
	var l = a.length;
	for (var i = 0; i < l; i++)
		tBody.appendChild(a[i].element);

	if (SortableTable.removeBeforeSort) {
		// insert into doc
		p.insertBefore(tBody, nextSibling);
	}

	this.updateHeaderArrows();

	this.destroyCache(a);

	if (typeof this.onsort == "function")
		this.onsort();
};

SortableTable.prototype.asyncSort = function (nColumn, bDescending, sSortType) {
	var oThis = this;
	this._asyncsort = function () {
		oThis.sort(nColumn, bDescending, sSortType);
	};
	window.setTimeout(this._asyncsort, 1);
};

SortableTable.prototype.getCache = function (sType, nColumn) {
	var rows = this.tBody.rows;
	var l = rows.length;
	var a = new Array(l);
	var r;
	for (var i = 0; i < l; i++) {
		r = rows[i];
		a[i] = {
			value:		this.getRowValue(r, sType, nColumn),
			element:	r
		};
	};
	return a;
};

SortableTable.prototype.destroyCache = function (oArray) {
	var l = oArray.length;
	for (var i = 0; i < l; i++) {
		oArray[i].value = null;
		oArray[i].element = null;
		oArray[i] = null;
	}
}

SortableTable.prototype.getRowValue = function (oRow, sType, nColumn) {
	var s;
	var c = oRow.cells[nColumn];
	if (typeof c.innerText != "undefined")
		s = c.innerText;
	else
		s = SortableTable.getInnerText(c);
	return this.getValueFromString(s, sType);
};

SortableTable.getInnerText = function (oNode) {
	var s = "";
	var cs = oNode.childNodes;
	var l = cs.length;
	for (var i = 0; i < l; i++) {
		switch (cs[i].nodeType) {
			case 1: //ELEMENT_NODE
				s += SortableTable.getInnerText(cs[i]);
				break;
			case 3:	//TEXT_NODE
				s += cs[i].nodeValue;
				break;
		}
	}
	return s;
}

SortableTable.prototype.getValueFromString = function (sText, sType) {
	switch (sType) {
		case "Number":
			return Number(sText);
		case "CaseInsensitiveString":
			return sText.toUpperCase();


		case "Date":
					if (sText.length > 10) // data + hora/min
					{
						var sText = sText.substring(0, 10);
		      	var parts = sText.split("/");
					}
					else // somente data
					{
		      	var parts = sText.split("/");
					}
		      var d = new Date(0);
		      d.setFullYear(parts[2]);
		      d.setDate(parts[0]);
		      d.setMonth(parts[1] - 1);
		   return d.valueOf();
	}
	return sText;
};

SortableTable.prototype.getSortFunction = function (sType, nColumn) {
	return function compare(n1, n2) {
		if (n1.value < n2.value)
			return -1;
		if (n2.value < n1.value)
			return 1;
		return 0;
	};
};

SortableTable.prototype.destroy = function () {
	this.uninitHeader();
	var win = this.document.parentWindow;
	if (win && typeof win.detachEvent != "undefined") {	// only IE needs this
		win.detachEvent("onunload", this._onunload);
	}
	this._onunload = null;
	this.element = null;
	this.tHead = null;
	this.tBody = null;
	this.document = null;
	this._headerOnclick = null;
	this.sortTypes = null;
	this._asyncsort = null;
	this.onsort = null;
};


/* ============ SCRIPTS REFERENTE A SELECAO MULTIPLA, ORDEM, ETC ============ */
function expiracao_cookie()
{
	// Duracao do cookie (1 ano)
	var DataExp = new Date();
	DataExp.setFullYear(DataExp.getFullYear() + 1);
	return "expires=" + DataExp.toGMTString();
}

function Ordenacao(coluna) // Realiza a ordenacao de listagens ao abrir a pagina
{
	var ORDEM1 = document.all.ORDEM1;
	var ORDEM2 = document.all.ORDEM2;

	if ((ORDEM1.value == coluna) && (ORDEM2.value == 1))
	{
		ORDEM2.value = 2;
	}
	else if ((ORDEM1.value == coluna) && (ORDEM2.value == 0))
	{
		ORDEM2.value = 1;
	}
	else
	{
		ORDEM2.value = 1;
	}
	ORDEM1.value = coluna; // ordenar coluna
	Cookie_Ordem(1); // ler, alterar, gravar cookie de ordenacao
}


function selTodos(opcao) // (des)marcar todos os registros
{
	var todos = document.getElementsByName('TOTAL_REG')[0].value; // total de registros

	for (var i=0; i<todos; i++)
	{
		if (opcao.checked == true)
		{
			if (todos == 1) // se tiver 1 registro, nao tem vetor no campo Codigo
			{
				document.getElementsByName('Codigo')[0].checked = true;
			}
			else
			{
				document.all.Codigo[i].checked = true; // marcar todos
				//document.all.Codigo[i].parentNode.parentNode.className="tdover"
			}
		}
		else
		{
			if (todos == 1) // se tiver 1 registro, nao tem vetor no campo Codigo
			{
				document.getElementsByName('Codigo')[0].checked = false;
			}
			else
			{
				document.all.Codigo[i].checked = false; // (des)marcar todos
				//document.all.Codigo[i].parentNode.parentNode.className="tdnormal"
			}
		}
	}
}


function excSel(total, msg) // excluir todos os registros selecionados
{
	var codigo_sel = 0; // total de campos checkbox selecionados para excluir

	for (var i=0; i<total; i++)
	{
		if (total == 1) // se tiver 1 registro, nao tem vetor no campo Codigo
		{
			if (document.getElementsByName('Codigo')[0].checked == true)
			{
				codigo_sel = codigo_sel + 1;
			}
		}
		else
		{
			if (document.all.Codigo[i].checked == true)
			{
				codigo_sel = codigo_sel + 1;;
			}
		}
	}

	if (codigo_sel > 0) // exibe confirmacao se tiver pelo menos 1 checkbox selecionado
	{
		// msg de confirmacao
		if (confirm(msg) == true)
		{
			//window.alert(document.all.Codigo[1].value);
			document.form_list.submit();
		}
	}
	else
	{
		window.alert('Selecione o(s) registro(s) a ser(em) excluído(s).');
	}
};


function checkClick(obj,colour)
{
if (obj.checked)
{
obj.parentNode.parentNode.style.backgroundColor=colour;
obj.parentNode.parentNode.className="tdover";
}
else
{
obj.parentNode.parentNode.style.backgroundColor="#F8F8F8";
obj.parentNode.parentNode.className="tdnormal";
}
}
function checkTD(obj1)
{
if (obj1.style.backgroundColor=="")
{
obj1.style.backgroundColor='#D9E9F8';
}
else if (obj1.style.backgroundColor='#D9E9F8')
{
obj1.style.backgroundColor='';
}
else {}
}


/*  Funções responsáveis pela marcação de registro nas listagens */
function marcaLinha(tmpLinha){
	if (document.getElementById('check'+tmpLinha).disabled == false){
		if(document.getElementById('check'+tmpLinha).checked){
			document.getElementById('linha'+tmpLinha).style.backgroundColor = adminColorOver;
		} else {
			document.getElementById('linha'+tmpLinha).style.backgroundColor = '#FFFFFF';
		}
		tmpCor = document.getElementById('linha'+tmpLinha).style.backgroundColor;
	} else {
		alert('checkbox disabled');
	}
}
function comCor(tmpLinha){
	if (checkLocal == 2){
		tmpCor = document.getElementById('linha'+tmpLinha).style.backgroundColor;
		document.getElementById('linha'+tmpLinha).style.backgroundColor = adminColorOver;
		checkLocal = 1
	}
}
function semCor(tmpLinha){
	if (checkLocal == 1){
		document.getElementById('linha'+tmpLinha).style.backgroundColor = tmpCor;
		checkLocal = 2
	}
}
function marcaTotos(){
	objetos = document.getElementsByName('Codigo').length;
	for(count = 0; count < objetos; count++){
		tmpLinha = document.getElementsByName('Codigo')[count].id.replace('check', '');
		marcaLinha(tmpLinha);
	}
}
/*---------------------------- FIM ------------------------------*/

