/*
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
::: Validar Formulario com campos obrigatorios
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
// Modo de Usar: onSubmit="return ValForm(this);"
// Modo de Usar: onSubmit="return ValForm(this);"
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

	//if (document.referrer.indexOf('admin') == -1) msg_intro   = '';



	for (var i=0; i<objetos; i++)
	{
		if (theForm.elements[i].type != undefined){
			// 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))
			{
				nome_campo = theForm.elements[i].name;
				qtd_opcoes = eval('theForm.'+nome_campo); //by Tiago
				//qtd_opcoes = document.getElementsByName(nome_campo); by Tiago
				tmpChecked = false;

				if (qtd_opcoes.length > 1)
				{
					for (j=0;j<qtd_opcoes.length;j++)
					{
						if (eval("theForm."+nome_campo+"[j].checked == true"))
						{
							tmpChecked = true;
							break;
						}
					}
				}

				if (tmpChecked == 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 uma opcao valida no 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))
			{
				nome_campo = theForm.elements[i].name;
				qtd_opcoes = eval('theForm.'+nome_campo); //by Tiago
				//qtd_opcoes = document.getElementsByName(nome_campo); 
				tmpChecked = false;
		
				if (qtd_opcoes.length > 1)
				{
					for (j=0;j<qtd_opcoes.length;j++)
					{
						if (eval("theForm."+nome_campo+"[j].checked == true"))
						{
							tmpChecked = true;
							break;
						}
					}
				}

				if (tmpChecked == 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, true);
		window.alert(msg_intro + msg_campos);
		destReq(theForm, false);
		if (foco_campo.length != 0)
		{
			eval("foco_campo.focus()")
		}
		return false;
	}
	else
	{
		return true;
	}

}


function comboConteudo(combo,congresso,AreCodigo)
{
	if (congresso == null || congresso == '') 
		window.location = '../Conteudos/pgpadrao.asp?ConCodigo=' + combo.value+'&AreCodigo='+AreCodigo
	else
		window.location = '../Conteudos/pgpadrao_congresso.asp?ConCodigo=' + combo.value+'&AreCodigo='+AreCodigo
}

// 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;
	  }
    else { // Nestcape
      nTecla = evtKeyPress.which;
    }

    sValue = objForm[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++;
    }

    objForm[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;
    }
  }

 function formatar(src, mask) {
		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);
		}
	}


/*
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
::: 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;
}

/*
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
::: Função de Máscaras para campos compatível com o Firefox
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
// Modo de Usar: http://jsfromhell.com/forms/masked-input

MaskInput = function(f, m){ //v1.0
	function mask(e){
		var patterns = {"1": /[A-Z]/i, "2": /[0-9]/, "4": /[À-ÿ]/i, "8": /./ },
			rules = { "a": 3, "A": 7, "9": 2, "C":5, "c": 1, "*": 8};
		function accept(c, rule){
			for(var i = 1, r = rules[rule] || 0; i <= r; i<<=1)
				if(r & i && patterns[i].test(c))
					break;
				return i <= r || c == rule;
		}
		var k, mC, r, c = String.fromCharCode(k = e.key), l = f.value.length;
		(!k || k == 8 ? 1 : (r = /^(.)\^(.*)$/.exec(m)) && (r[0] = r[2].indexOf(c) + 1) + 1 ?
			r[1] == "O" ? r[0] : r[1] == "E" ? !r[0] : accept(c, r[1]) || r[0]
			: (l = (f.value += m.substr(l, (r = /[A|9|C|\*]/i.exec(m.substr(l))) ?
			r.index : l)).length) < m.length && accept(c, m.charAt(l))) || e.preventDefault();
	}
	for(var i in !/^(.)\^(.*)$/.test(m) && (f.maxLength = m.length), {keypress: 0, keyup: 1})
		addEvent(f, i, mask);
};


// Event Listener Function v1.4
addEvent = function(o, e, f, s){
	var r = o[r = "_" + (e = "on" + e)] = o[r] || (o[e] ? [[o[e], o]] : []), a, c, d;
	r[r.length] = [f, s || o], o[e] = function(e){
		try{
			(e = e || event).preventDefault || (e.preventDefault = function(){e.returnValue = false;});
			e.stopPropagation || (e.stopPropagation = function(){e.cancelBubble = true;});
			e.target || (e.target = e.srcElement || null);
			e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0;
		}catch(f){}
		for(d = 1, f = r.length; f; r[--f] && (a = r[f][0], o = r[f][1], a.call ? c = a.call(o, e) : (o._ = a, c = o._(e), o._ = null), d &= c !== false));
		return e = null, !!d;
    }
};

removeEvent = function(o, e, f, s){
	for(var i = (e = o["_on" + e] || []).length; i;)
		if(e[--i] && e[i][0] == f && (s || o) == e[i][1])
			return delete e[i];
	return false;
};


/*
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
::: 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 - 5).toLowerCase() + ",";
	
	if (extensao.substr(1,1) == '.') {
		//alert('extensao com 4 char')
	} else {
		//alert('extensao com 3 char')
		extensao = ","+extensao.substr(2, extensao.length-2);
	}
	if (field.value.length != 0) {
		if( extensoesOk.indexOf( extensao ) == -1 ) {
			alert( field.value + "\nO arquivo não possui uma extensão válida ("+extensoesOk+")! 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 Campo Numérico
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
// Modo de Usar: http://www.mredkj.com/tutorials/validate2.html

function extractNumber(obj, decimalPlaces, allowNegative)
{
	var temp = obj.value;
	
	// avoid changing things if already formatted correctly
	var reg0Str = '[0-9]*';
	if (decimalPlaces > 0) {
		reg0Str += '\\.?[0-9]{0,' + decimalPlaces + '}';
	} else if (decimalPlaces < 0) {
		reg0Str += '\\.?[0-9]*';
	}
	reg0Str = allowNegative ? '^-?' + reg0Str : '^' + reg0Str;
	reg0Str = reg0Str + '$';
	var reg0 = new RegExp(reg0Str);
	if (reg0.test(temp)) return true;

	// first replace all non numbers
	var reg1Str = '[^0-9' + (decimalPlaces != 0 ? '.' : '') + (allowNegative ? '-' : '') + ']';
	var reg1 = new RegExp(reg1Str, 'g');
	temp = temp.replace(reg1, '');

	if (allowNegative) {
		// replace extra negative
		var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
		var reg2 = /-/g;
		temp = temp.replace(reg2, '');
		if (hasNegative) temp = '-' + temp;
	}
	
	if (decimalPlaces != 0) {
		var reg3 = /\./g;
		var reg3Array = reg3.exec(temp);
		if (reg3Array != null) {
			// keep only first occurrence of .
			//  and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0
			var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
			reg3Right = reg3Right.replace(reg3, '');
			reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
			temp = temp.substring(0,reg3Array.index) + '.' + reg3Right;
		}
	}
	
	obj.value = temp;
}
function blockNonNumbers(obj, e, allowDecimal, allowNegative)
{
	var key;
	var isCtrl = false;
	var keychar;
	var reg;
		
	if(window.event) {
		key = e.keyCode;
		isCtrl = window.event.ctrlKey
	}
	else if(e.which) {
		key = e.which;
		isCtrl = e.ctrlKey;
	}
	
	if (isNaN(key)) return true;
	
	keychar = String.fromCharCode(key);
	
	// check for backspace or delete, or if Ctrl was pressed
	if (key == 8 || isCtrl)
	{
		return true;
	}

	reg = /\d/;
	var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
	var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;
	var isFirstD = allowDecimal ? keychar == ',' && obj.value.indexOf(',') == -1 : false;

	
	return isFirstN || isFirstD || reg.test(keychar);
}


/*
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
::: Validar CNPJ
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
// Modo de Usar: onBlur="javascript:valCNPJCPF(this, 1);"

// 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 (text, textarea)
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
// 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;
    }
}

/*
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
::: Validar Campo Numérico -alf
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
//Example usage
// <input type="text"
//   onblur="SomenteNumeros(this,2,true);"
//   onkeyup="SomenteNumeros(this,2,true);"
//   onkeypress="return bloquearNaoNumeros(this, event, true, true);" />
// Mais Modos de Usar: http://www.mredkj.com/tutorials/validate2.html

	function SomenteNumeros(obj, casasDecimais, permitirNegativo)
	{
		var temp = obj.value;
		
		// avoid changing things if already formatted correctly
		var reg0Str = '[0-9]*';
		if (casasDecimais > 0) {
			reg0Str += '\\.?[0-9]{0,' + casasDecimais + '}';
		} else if (casasDecimais < 0) {
			reg0Str += '\\.?[0-9]*';
		}
		reg0Str = permitirNegativo ? '^-?' + reg0Str : '^' + reg0Str;
		reg0Str = reg0Str + '$';
		var reg0 = new RegExp(reg0Str);
		if (reg0.test(temp)) return true;
	
		// first replace all non numbers
		var reg1Str = '[^0-9' + (casasDecimais != 0 ? '.' : '') + (permitirNegativo ? '-' : '') + ']';
		var reg1 = new RegExp(reg1Str, 'g');
		temp = temp.replace(reg1, '');
	
		if (permitirNegativo) {
			// replace extra negative
			var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
			var reg2 = /-/g;
			temp = temp.replace(reg2, '');
			if (hasNegative) temp = '-' + temp;
		}
		
		if (casasDecimais != 0) {
			var reg3 = /\./g;
			var reg3Array = reg3.exec(temp);
			if (reg3Array != null) {
				// keep only first occurrence of .
				//  and the number of places specified by casasDecimais or the entire string if casasDecimais < 0
				var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
				reg3Right = reg3Right.replace(reg3, '');
				reg3Right = casasDecimais > 0 ? reg3Right.substring(0, casasDecimais) : reg3Right;
				temp = temp.substring(0,reg3Array.index) + '.' + reg3Right;
			}
		}
		
		obj.value = temp;
	}

	function bloquearNaoNumeros(obj, e, permitirDecimais, permitirNegativo)
	{
		var key;
		var isCtrl = false;
		var keychar;
		var reg;
			
		if(window.event) {
			key = e.keyCode;
			isCtrl = window.event.ctrlKey
		}
		else if(e.which) {
			key = e.which;
			isCtrl = e.ctrlKey;
		}
		
		if (isNaN(key)) return true;
		
		keychar = String.fromCharCode(key);
		
		// check for backspace or delete, or if Ctrl was pressed
		if (key == 8 || isCtrl)
		{
			return true;
		}
	
		reg = /\d/;
		var isFirstN = permitirNegativo ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
		var isFirstD = permitirDecimais ? keychar == '.' && obj.value.indexOf('.') == -1 : false;
		
		return isFirstN || isFirstD || reg.test(keychar);
	}
	
/*
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
::: Fim - Validar Campo Numérico -alf
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/	

/*
=== Temas ========================================================================================================================
*/

var total = 0;
var totalUtilizado = 0;
var tabelaTema = 0;
var Tema_Instituicoes = 0;
var Tema_Resumo = 0;
var Nome = 0;
var imagem1 = 0;
var imagem2 = 0;
var valorLinha = 0;
var imagemCar = 0;
var l = 0;
var c = 0;
var titulo = '';
var instituicoes = '';
var resumo = '';
var coAutores = '';
var tabV = '';
var imgAlt = 0;
var imgLar = 0;

function resetaCampos()
{
	document.getElementById('total').innerHTML = 0;
	document.getElementById('total2').innerHTML = 0;
	
	document.getElementById('totalUtilizado').innerHTML = 0;
	document.getElementById('totalUtilizado2').innerHTML = 0;
	
	document.getElementById('divTabela').innerHTML = '';
	document.getElementById('linhaTabela').style.display = 'none';	
	
	document.getElementById('tema_titulo').value = ''; 
	document.getElementById('Tema_Instituicoes').value = '';
	
	for (i=1;i<=9;i++)
	{
		document.getElementById('Nome' + i ).value = '';
		document.getElementById('SobreNome' + i ).value = '';
	}
	
	document.getElementById('Tema_Resumo').value = '';
	document.getElementById('qtLinhas').value = '';
	document.getElementById('qtColunas').value = '';
	document.getElementById('Area_Codigo').value = '-1';
}

function validacaoTema(form,pagina)
{
	var evento = document.getElementById('Evt_Codigo').value;
	var area = document.getElementById('Area_Codigo').value;
	var titulo = document.getElementById('Tema_Titulo').value;
	var instituicao = document.getElementById('Tema_Instituicoes').value;
	var resumo = document.getElementById('Tema_Resumo').value;
	var nome = 0;
	
	for(i=1;i<10;i++)
	{
		if(TrimJs(document.getElementById('Nome' + i).value))
		{
			if(!TrimJs(document.getElementById('SobreNome' + i).value))
				nome += 1
		}		
	}
	
	var retorno  = false;
	if(evento == -1)
		alert('Selecione um evento!');
		//document.getElementById('btnalterar').disabled = false;
		//document.getElementById('btnalterar').value = "Gravar/Alterar";
		//document.getElementById('btnjulgamento').disabled = false;
	else if(area == -1)
		alert('Selecione a área do seu tema!');
		//document.getElementById('btnalterar').disabled = false;
		//document.getElementById('btnalterar').value = "Gravar/Alterar";
		//document.getElementById('btnjulgamento').disabled = false;
	else if(!TrimJs(titulo))
		alert('Informe o título do seu tema!');
		//document.getElementById('btnalterar').disabled = false;
		//document.getElementById('btnalterar').value = "Gravar/Alterar";
		//document.getElementById('btnjulgamento').disabled = false;
	else if(!TrimJs(resumo))
		alert('Digite seu tema(resumo)!');
		//document.getElementById('btnalterar').disabled = false;
		//document.getElementById('btnalterar').value = "Gravar/Alterar";
		//document.getElementById('btnjulgamento').disabled = false;
	else if(nome > 0)
		alert('Preencha o campo nome e sobrenome!');
		//document.getElementById('btnalterar').disabled = false;
		//document.getElementById('btnalterar').value = "Gravar/Alterar";
		//document.getElementById('btnjulgamento').disabled = false;
	else
	{
		//fImg.form0.Concluir.value = '1'; 
		//fImg.form0.submit(); 
		retorno = true;
	}
	return retorno;
}

function exibeTabVisualizacao(l,c)
{
	if(l > 0)
	{
		tabV = '<table>'
		for (i=1;i<(l+1);i++)
		{
			tabV += '<tr>'		
			for (j=1;j<(c+1);j++)
			{
				if (i==1){
					if(document.getElementById('celula' + i + j).value != ''){
						tabV += '<td width="' + 100/c + '%" style="font-size:11px; font-weight:bold;">' + document.getElementById('celula' + i + j).value + '</td>'	
					}
					else{
						tabV += '<td width="' + 100/c + '%">&nbsp;</td>'	
					}
				}
				else{
					if(document.getElementById('celula' + i + j).value != ''){
						tabV += '<td width="' + 100/c + '%">' + document.getElementById('celula' + i + j).value + '</td>'	
					}
					else{
						tabV += '<td width="' + 100/c + '%">&nbsp;</td>'	
					}
				}
				
			}
			tabV += '</tr>'
		}
		tabV += '</table>'

		//alert(tabV)
	}
}

function visualizacaoTema()
{
	titulo 			= window.opener.form1.Tema_Titulo.value;
	instituicoes	= window.opener.form1.Tema_Instituicoes.value;
	resumo 			= window.opener.form1.Tema_Resumo.value;
	
	for (i=1;i<10;i++)
	{
		if (TrimJs(window.opener.document.getElementById('nome' + i).value))
		{
			if(coAutores == '')
				coAutores = window.opener.document.getElementById('nome' + i).value + ' ' + window.opener.document.getElementById('sobrenome' + i).value;
			else
				coAutores += ', ' + window.opener.document.getElementById('nome' + i).value + ' ' + window.opener.document.getElementById('sobrenome' + i).value;
		}
	}
}

function resetaVariaveis()
{
	total = 0;
	totalUtilizado = 0;
	tabelaTema = 0;
	Tema_Instituicoes = 0;
	Tema_Resumo = 0;
	Nome = 0;
	imagem1 = 0;
	imagem2 = 0;
	valorLinha = 0;
	imagemCar = 0;
	l = 0;
	c = 0;
	titulo = '';
	instituicoes = '';
	resumo = '';
	coAutores = '';
	tabV = '';
	imgAlt = 0;
	imgLar = 0;
}

//Função de inserção da tabela
function exibeTabela()
{
	erro = true;
	qtColunas = document.getElementById('qtColunas').value;
	qtLinhas = document.getElementById('qtLinhas').value;
	
	if(!TrimJs(qtLinhas) || isNaN(qtLinhas))
	{
		alert('Informe a quantidade válida de Linhas!');
		return false;
	}
	else if(!TrimJs(qtColunas) || isNaN(qtColunas))
	{
		alert('Informe a quantidade válida de Colunas!');
		return false;
	}	
	else if(qtColunas == 0 || qtLinhas == 0)
	{
		document.getElementById('linhaTabela').style.display = 'none';
		qtLinhas = 0;
		return false;
	}
	else
	{
		/*
			Verificação se tabela pode ser inserida.
			Se a quantidade de caracteres ultrapassar o total de caracteres
			disponíveis. Alerta.
		*/
		valorLinha 	= parseInt(document.getElementById('valorLinha').value);
		total 		= parseInt(document.getElementById('total').innerHTML);
		
		if((qtLinhas * valorLinha) > (total - (totalUtilizado - tabelaTema)))
		{
			alert('Sua tabela pode ter no máximo ' + parseInt((total - (totalUtilizado - tabelaTema))/100) + ' linhas!');
			return false;
		}
		
		//Exibe linha da tabela que contém o div
		document.getElementById('linhaTabela').style.display = 'inline';
		
		tabela = document.createElement('table');
		tabela.setAttribute('width','100%');	
		tabela.setAttribute('id','TabTema');	
		//tabela.setAttribute('border','1');	
		for(l=0;l<=qtLinhas;l++)
		{	
			linha = document.createElement('tr');
			totalColunas = parseInt(qtColunas) + 1
			
			for(c=1;c<=totalColunas;c++)
			{
				coluna = document.createElement('td');
				coluna.setAttribute('width',(100/qtColunas) + '%');	
				coluna.setAttribute('id','coluna' + l + c);	
				
				if(l==0 && c != (totalColunas))
				{
					span = document.createElement('span');
					span.setAttribute('id','tcoluna' + c);
					span.style.width = '100%';
					span.style.textAlign = 'center';
					span.appendChild(document.createTextNode('0'));
					coluna.appendChild(span);	
				}
				else if(c != (totalColunas))
				{
					campoTexto = document.createElement('input');
					campoTexto.setAttribute('type','text');
					campoTexto.setAttribute('id','celula' + l + c);
					campoTexto.name = 'celula' + l + c;
					campoTexto.setAttribute('onKeyUp','totalCarColuna(' + l +','+ c +')');
					campoTexto.setAttribute('onKeyDown','totalCarColuna(' + l +','+ c +')');
					campoTexto.setAttribute('onKeyPress','return limitaDigitacaoColuna(' + l +','+ c +')');
					campoTexto.style.width = 420/qtColunas;
					campoTexto.className = 'campo';
					coluna.appendChild(campoTexto);
				}
				else if(l==1)
				{
					span = document.createElement('span');
					span.setAttribute('id','tlinha' + l);
					span.style.width = '18';
					span.style.textAlign = 'center';
					span.appendChild(document.createTextNode(document.getElementById('valorLinha').value));
					coluna.appendChild(span);
				}				
				linha.appendChild(coluna);
			}
			tabela.appendChild(linha);
		}		
	
		//Inseri HTML da tabela no div
		document.getElementById('divTabela').innerHTML = tabela.outerHTML;
	}

	//Soma quantidade de linhas ao total de caracteres
	somaCaracteres();
	
	for (l=1;l<=parseInt(qtLinhas);l++)
	{
		for (c=1;c<=parseInt(qtColunas);c++)
		{
			document.getElementById('celula' + l + c).name = 'celula' + l + c;			
		}
	}
}

//Exibe dados da tabela na alteração do Tem
function sbeDadosTabela(tab, lin, col)
{
	if (document.getElementById("TabTema")!=null){
		//Corre por todas as linhas das tabela
		for(line=1;line<=lin;line++)
		{
			//Linha completa da tabela
			liCompleta = tab.substring(tab.indexOf('<tr>'),tab.indexOf('</tr>') + 5);
			li = liCompleta;
			
			
			//Corre por todas as colunas da Linha
			for(c=1;c<=col;c++)
			{
				//Coluna completa da linha
				co = li.substring(li.indexOf('<td>'),li.indexOf('</td>') + 5);
				
				//Atribuindo da célula ao valor do campo de texto
				if(co.substring(4,co.length - 5) != '&nbsp;' && co.length > 4)
					document.getElementById('celula' + line + c).value = co.substring(4,co.length - 5);
				
				//Função para subtrair caracteres do total
				totalCarColuna(line, c);
				//Linha, sem as colunas já vistas
				li = li.substring(0,li.indexOf(co)) + li.substring(li.indexOf(co) + co.length, li.length);
			}
			//Tabela, sem as linhas já vistas
			
			tab = tab.substring(0,tab.indexOf(liCompleta)) + tab.substring(tab.indexOf(liCompleta) + liCompleta.length, tab.length);		
		}
	}
}
function exibeDadosTabela1(tab, lin, col)
{
	if (document.getElementById("TabTema")!=null){
		//Corre por todas as linhas das tabela
		for(line=1;line<=lin;line++)
		{
			//Linha completa da tabela
			liCompleta = tab.substring(tab.indexOf('<tr>'),tab.indexOf('</tr>') + 5);
			li = liCompleta;
			
			if (line==1){
				//Corre por todas as colunas da Linha
				for(c=1;c<=col;c++)
				{
					//Coluna completa da linha
					co = li.substring(li.indexOf('<th>'),li.indexOf('</th>') + 5);
					
					//Atribuindo da célula ao valor do campo de texto
					if(co.substring(4,co.length - 5) != '&nbsp;' && co.length > 4)
						document.getElementById('celula' + line + c).value = co.substring(4,co.length - 5);
					
					//Função para subtrair caracteres do total
					totalCarColuna(line, c);
					//Linha, sem as colunas já vistas
					li = li.substring(0,li.indexOf(co)) + li.substring(li.indexOf(co) + co.length, li.length);
				}
			}
			else{
				for(c=1;c<=col;c++)
				{
					//Coluna completa da linha
					co = li.substring(li.indexOf('<td>'),li.indexOf('</td>') + 5);
					
					//Atribuindo da célula ao valor do campo de texto
					if(co.substring(4,co.length - 5) != '&nbsp;' && co.length > 4)
						document.getElementById('celula' + line + c).value = co.substring(4,co.length - 5);
					
					//Função para subtrair caracteres do total
					totalCarColuna(line, c);
					//Linha, sem as colunas já vistas
					li = li.substring(0,li.indexOf(co)) + li.substring(li.indexOf(co) + co.length, li.length);
				}
			}
			

			
			//Tabela, sem as linhas já vistas
			
			tab = tab.substring(0,tab.indexOf(liCompleta)) + tab.substring(tab.indexOf(liCompleta) + liCompleta.length, tab.length);		
		}
	}
}

//Conta Caracteres da tabela
function totalCarColuna(linha, coluna)
{
	totalColunas = (parseInt(document.getElementById("TabTema").cells.length) / parseInt(document.getElementById("TabTema").rows.length));
	if(linha == 1)
	{
		somaTotal = 0;
		for(i=1;i<totalColunas;i++)
		{
			somaTotal += document.getElementById('celula' + linha + i).value.length;	
		}
		document.getElementById('tlinha' + linha).innerHTML = parseInt(document.getElementById('valorLinha').value) - somaTotal;
		document.getElementById('tcoluna' + coluna).innerHTML = document.getElementById('celula' + linha + coluna).value.length;
	}
}

function limitaDigitacaoColuna(linha, coluna)
{
	if(linha == 1)
	{
		if(parseInt(document.getElementById('tlinha1').innerHTML) <= 0)
			return false;
	}
	else
	{
		while (document.getElementById('celula' + linha + coluna).value.length >= document.getElementById('tcoluna' + coluna).innerHTML)
		{
			document.getElementById('celula' + linha + coluna).value = document.getElementById('celula' + linha + coluna).value.substring(0, document.getElementById('celula' + linha + coluna).value.length-1);
			somaCaracteres();
		}
	}
}

//Função que soma o total de caracteres
function somaCaracteres()
{
	if (document.getElementById('qtLinhas').value != ''){		
		if (document.getElementById('qtLinhas').value=='-1'){
			tabelaTema = 0;
		}
		else{
			tabelaTema = parseInt(document.getElementById('qtLinhas').value) * parseInt(document.getElementById('valorLinha').value);
		}
		
	}
	if (document.getElementById('TxtImg1').value=='1' && document.getElementById('TxtImg2').value == '1'){
		TamanhoImgCar = parseInt(document.getElementById('imagemCar').value)/2;
	}
	else{
		TamanhoImgCar = parseInt(document.getElementById('imagemCar').value);
	}	
	if (document.getElementById('TxtImg1').value == '1'){
		imagem1 = TamanhoImgCar;
		
	}
	else{
		imagem1 = parseInt(document.getElementById('imagemCar').value) - TamanhoImgCar;
	}

	if (document.getElementById('TxtImg2').value == '1'){
		imagem2 = TamanhoImgCar;
	}
	else{
		imagem2 = parseInt(document.getElementById('imagemCar').value) - TamanhoImgCar;
	}
	Tema_Instituicoes = parseInt(document.getElementById('Tema_Instituicoes').value.length);
	Nome = 0;
	for(i=1;i<10;i++){
		Nome += parseInt(document.getElementById('Nome' + i).value.length);
		Nome += parseInt(document.getElementById('SobreNome' + i).value.length);
	}
	Tema_Resumo = parseInt(document.getElementById('Tema_Resumo').value.length);
	totalUtilizado = tabelaTema + imagem1 + imagem2 + Tema_Instituicoes + Nome + Tema_Resumo;
	//alert( tabelaTema+' + '+imagem1+' + '+imagem2+' + '+Tema_Instituicoes+' + '+Nome+' + '+Tema_Resumo )
	document.getElementById('totalUtilizado').innerHTML = totalUtilizado;
	document.getElementById('totalUtilizado2').innerHTML = totalUtilizado;
}

//Função que define total (Valor vem do Ajax)
function defineTotal()
{
		
	var arrVar = defineTotal.arguments;
	retorno = arrVar[0];
	//Geral, Titulo, Imagem, Tabela
	total		= parseInt(retorno.substring(0,retorno.indexOf(',')));
	retorno 	= retorno.substring(retorno.indexOf(',') + 1,retorno.length);
		
	titulo		= parseInt(retorno.substring(0,retorno.indexOf(',')));
	document.getElementById('Tema_Titulo').maxLength = titulo;
	retorno 	= retorno.substring(retorno.indexOf(',') + 1,retorno.length);
	document.getElementById('DivTemaTitulo').innerHTML = "&nbsp;&nbsp;  máximo <b>"+titulo+"</b> caracteres";
	document.getElementById('DivTemaTitulo').style.display='inline';
	imagemCar	= parseInt(retorno.substring(0,retorno.indexOf(',')));
	document.getElementById('imagemCar').value = imagemCar;
	retorno 	= retorno.substring(retorno.indexOf(',') + 1,retorno.length);
	
	
	valorLinha 	= parseInt(retorno.substring(0,retorno.indexOf(',')));
	document.getElementById('valorLinha').value = valorLinha;
	retorno 	= retorno.substring(retorno.indexOf(',') + 1,retorno.length);

//	alert(valorLinha)
	
	imgAlt		= parseInt(retorno.substring(0,retorno.indexOf(',')));
	document.getElementById('ImgA').value = imgAlt;
	retorno 	= retorno.substring(retorno.indexOf(',') + 1,retorno.length);
	
	imgLar		= parseInt(retorno.substring(0,retorno.length));
	document.getElementById('ImgL').value = imgLar;
	retorno 	= retorno.substring(retorno.indexOf(',') + 1,retorno.length);
	
	document.getElementById('total').innerHTML = total;
	document.getElementById('total2').innerHTML = total;	
	document.getElementById('TextExplica').innerHTML = '<i>"O Nome do Autor será capturado automaticamente através do login do usuário que estiver inscrevendo o Tema. O total de caracteres disponíveis para Co-Autores, Instituição e Resumo está limitado em <b>'+total+'</b> caracteres.Tabelas e figuras reduzirão este limite. Podem ser incluídos até 9 co-autores, digite cada co-autor em uma linha separando o Nome e Sobrenome, em caso de múltiplos sobrenomes, abrevie os intermediários e informe o último sobrenome sem abreviações. Você pode "Copiar" (Ctrl+C) e "Colar" (Ctrl+V) de seu editor de texto. Não use formatações no texto e no resumo."</i>'
	document.getElementById('TabelaExplica').innerHTML = '"<i>Cada Linha da Tabela consome <b>'+valorLinha+'</b> caracteres do texto. O tamanho de cada coluna é definido pelo número de caracteres preenchidos na primeira linha.</i>"'
	document.getElementById('textImg').innerHTML = '"<i>Inserir todas as figuras simultaneamente. Utilize somente imagens "JPG". Se você inseriu um arquivo diferente, apague o texto da caixa de entrada do arquivo. Área total das imagens <b>'+imgLar+'x'+imgAlt+'</b> pixels correspondente a <b>'+imagemCar+'</b> caracteres. Ao apagar as imagens não esqueça de clicar em Alterar para gravar as alterações </i>"'
	fImg.location.href = fImg.location.href;
	somaCaracteres();
}

//Função que verifica se o limite de caracteres foi atingido, caso tenha sido, bloqueia a digitação
/*function limitaDigitacao()
{
	if(parseInt(document.getElementById('total').innerHTML) == 0 || parseInt(document.getElementById('totalUtilizado').innerHTML) >= parseInt(document.getElementById('total').innerHTML))
		return false;
}*/

function limitaDigitacao(campo) {
	if (parseInt(document.getElementById('total').innerHTML) != 0 && parseInt(document.getElementById('totalUtilizado').innerHTML)!=0){
		if(parseInt(document.getElementById('total').innerHTML) == 0 || parseInt(document.getElementById('totalUtilizado').innerHTML) >= parseInt(document.getElementById('total').innerHTML)){
					
			
			var tamanhogeral = parseInt(document.getElementById('total').innerHTML) - parseInt(document.getElementById('totalUtilizado').innerHTML)
			if (tamanhogeral<0){
				texto = campo.value;
				tamanho = campo.value.length
				alert('Você ultrapassou o limite máximo de caracteres !\nO sistema irá retornar o texto inserido até o último caracter disponível')
				campo.value = texto.substring(0, tamanho+(tamanhogeral))
			}
			somaCaracteres();
		}
	}	
 }

//Função que verifica se pode ou não ser inserida uma imagem
function imagemInsere(tmpCar)
{	
	//Verifica se pode ser inserida uma imagem
	if (document.getElementById('TxtImg1').value == '1'){
		imagem1 = parseInt(document.getElementById('imagemCar').value);
	}
	
	if((parseInt(document.getElementById('total').innerHTML) - (parseInt(document.getElementById('totalUtilizado').innerHTML) - (imagem1))) < tmpCar)
	{
		alert('Não há espaço para imagem!');
			return false;
	}
}

function imagem(file)
{	
	somaCaracteres();
	if (file == 1) 
		var campoImagem = fImg.form0.imagem1;
	else
		var campoImagem = fImg.form0.imagem2;
		
	if(campoImagem.value.length > 0)
	{
		if(file == 1)
			imagem1 = parseInt(document.getElementById('imagemCar').value);	
		else
			imagem2 = parseInt(document.getElementById('imagemCar').value);	
	}			
	else
	{
		if(file == 1)
			imagem1 = 0;
		else
			imagem2 = 0;	
	}
	totalUtilizado = Tema_Instituicoes + Nome + Tema_Resumo + tabelaTema + imagem1 + imagem2;
	document.getElementById('totalUtilizado').innerHTML = totalUtilizado;	
	document.getElementById('totalUtilizado2').innerHTML = totalUtilizado;
}

function temaDetalhes(tema, aval)
{
	//alert(aval);
	conteudo.document.location = '../conteudos/pgpadrao_congresso.asp?conCodigo=58&Tema_Codigo=' + tema + '&aval=' + aval;
}

function TrimJs(texto)
{
	while (texto.indexOf(" ") != -1)
	{
		indice = texto.indexOf(" ");
		texto = texto.substring(0,indice) + texto.substring(indice + 1,texto.length);		
	}
	if (texto.length > 0)
		return true;
	else
		return false;
}

function exibeTema(Tema_Codigo)
{
	window.open('../conteudos/x_temas_visualizacao.asp?Tema_Aprovado=ok&Tema_Codigo=' + Tema_Codigo ,'tema','width=508 height=600');
}
	
function irpara(form) 
{
	var assunto = form.dest.selectedIndex;
	var assunto2 = form.SelTratamento.selectedIndex;
	if (form.SelTratamento.options[assunto2].value == 'a')
	{
		form.Tratamento[0].disabled = true;
		form.Tratamento[1].disabled = true;
		form.Tratamento[2].disabled = true;
		form.Tratamento[3].disabled = true;
		form.Tratamento[4].disabled = true;
		form.Tratamento[5].disabled = true;
		form.Tratamento[6].disabled = true;
		form.Tratamento[7].disabled = true;
		form.Tratamento[8].disabled = true;
		form.Tratamento[9].disabled = true;
	
	}
	if (form.SelTratamento.options[assunto2].value == 'b')
	{
		form.Tratamento[0].disabled = false;
		form.Tratamento[1].disabled = false;
		form.Tratamento[2].disabled = false;
		form.Tratamento[3].disabled = false;
		form.Tratamento[4].disabled = false;
		form.Tratamento[5].disabled = false;
		form.Tratamento[6].disabled = false;
		form.Tratamento[7].disabled = false;
		form.Tratamento[8].disabled = false;
		form.Tratamento[9].disabled = false;
	
	}
	if (form.dest.options[assunto].value == 'a')
	{
		form.delineamento[0].disabled = true;
		form.delineamento[1].disabled = true;
		form.delineamento[2].disabled = true;
		form.delineamento[3].disabled = true;
		form.delineamento[4].disabled = true;
		form.delineamento[5].disabled = true;
		form.delineamento[6].disabled = true;
		form.delineamento[7].disabled = true;
		form.delineamento[8].disabled = true;
		form.delineamento[9].disabled = true;
	
	}
	if (form.dest.options[assunto].value == 'b')
	{
		form.delineamento[0].disabled = false;
		form.delineamento[1].disabled = false;
		form.delineamento[2].disabled = false;
		form.delineamento[3].disabled = true;
		form.delineamento[4].disabled = true;
		form.delineamento[5].disabled = true;
		form.delineamento[6].disabled = true;
		form.delineamento[7].disabled = true;
		form.delineamento[8].disabled = true;
		form.delineamento[9].disabled = true;
	}
	if (form.dest.options[assunto].value == 'c')
	{
		form.delineamento[0].disabled = false;
		form.delineamento[1].disabled = false;
		form.delineamento[2].disabled = false;
		form.delineamento[3].disabled = false;
		form.delineamento[4].disabled = false;
		form.delineamento[5].disabled = true;
		form.delineamento[6].disabled = true;
		form.delineamento[7].disabled = true;
		form.delineamento[8].disabled = true;
		form.delineamento[9].disabled = true;
	}
	if (form.dest.options[assunto].value == 'd')
	{
		form.delineamento[0].disabled = false;
		form.delineamento[1].disabled = false;
		form.delineamento[2].disabled = false;
		form.delineamento[3].disabled = false;
		form.delineamento[4].disabled = false;
		form.delineamento[5].disabled = false;
		form.delineamento[6].disabled = false;
		form.delineamento[7].disabled = true;
		form.delineamento[8].disabled = true;
		form.delineamento[9].disabled = true;
	}
	if (form.dest.options[assunto].value == 'e')
	{
		form.delineamento[0].disabled = false;
		form.delineamento[1].disabled = false;
		form.delineamento[2].disabled = false;
		form.delineamento[3].disabled = false;
		form.delineamento[4].disabled = false;
		form.delineamento[5].disabled = false;
		form.delineamento[6].disabled = false;
		form.delineamento[7].disabled = false;
		form.delineamento[8].disabled = false;
		form.delineamento[9].disabled = false;
	}
	if (form.dest.options[assunto].value == 'f')
	{
		form.delineamento[0].disabled = false;
		form.delineamento[1].disabled = false;
		form.delineamento[2].disabled = false;
		form.delineamento[3].disabled = false;
		form.delineamento[4].disabled = false;
		form.delineamento[5].disabled = false;
		form.delineamento[6].disabled = false;
		form.delineamento[7].disabled = false;
		form.delineamento[8].disabled = false;
		form.delineamento[9].disabled = false;
	}
}

function alteraEvento(Con_Codigo,Evt_Codigo)
{
	window.location='../menu/pgmenu_congresso.asp?c='+Evt_Codigo+'&AreCodigo=3';	
}


function exibeDados(Pes_Cpf_Cnpj, AreCodigo)
{
	window.location = '../conteudos/pgsocios_form.asp?Pes_Cpf_Cnpj=' + Pes_Cpf_Cnpj+'&AreCodigo='+AreCodigo
}

function exibeDadosR(Pes_Cpf_Cnpj, AreCodigo, refer)
{
	window.location = '../conteudos/pgsocios_form.asp?Pes_Cpf_Cnpj=' + Pes_Cpf_Cnpj+'&AreCodigo='+AreCodigo+'&referencia='+refer
}

function camposObrigatorios()
{	
	if (document.getElementById('Pes_Socio1').checked)
	{
		//Sócio
		document.getElementsByName('Pes_CRM')[0].id 		= 'REQ|Numero do conselho de classe';
		document.getElementsByName('Pes_CRM_Estado')[0].id 	= 'REQ|Estado do conselho de classe';
		document.getElementsByName('Pes_Comercial1')[0].id 	= 'REQ|Telefone Comercial';
		document.getElementsByName('Pes_Celular')[0].id 	= 'REQ|Celular';
		document.getElementsByName('Soc_Endereco')[0].id 	= 'REQ|Endereço comercial';
		document.getElementsByName('Soc_Bairro')[0].id 		= 'REQ|Bairro Comercial';
		document.getElementsByName('Soc_Cidade')[0].id 		= 'REQ|Cidade Comercial';
		document.getElementsByName('Soc_CEP')[0].id 		= 'REQ|Cep Comercial';
		document.getElementsByName('Soc_Estado')[0].id 		= 'REQ|Estado comercial';
		document.getElementsByName('Pes_Crm')[0].id 		= 'REQ|Numero do conselho de classe';
		document.getElementsByName('Pes_Crm_Estado')[0].id 		= 'REQ|Estado do conselho de classe';
		
		parametros = 'Pes_socio='+ escape(1)+'&Pes_Cpf_Cnpj='+ escape(document.getElementsByName('Pes_Cpf_Cnpj')[0].value);
		Ajax("../admin/x_socioscategoria.asp", parametros, 1, 'XPes_Categoria', 1, 0);
		
		document.getElementById('sConselho').innerHTML 	= '* ';
		document.getElementById('sTelCom').innerHTML 	= '* ';
		document.getElementById('sCel').innerHTML 		= '* ';
		document.getElementById('sEndCom').innerHTML 	= '* ';
		document.getElementById('sBairroCom').innerHTML = '* ';
		document.getElementById('sCEPCom').innerHTML 	= '* ';
		document.getElementById('sEstadoCom').innerHTML	= '* ';
		document.getElementById('sCidadeCom').innerHTML = '* ';
	}
	else
	{
		//Não sócio
		document.getElementsByName('Pes_CRM')[0].id 		= '';
		document.getElementsByName('Pes_CRM_Estado')[0].id 	= '';
		document.getElementsByName('Pes_Comercial1')[0].id 	= '';
		document.getElementsByName('Pes_Celular')[0].id 	= '';
		document.getElementsByName('Soc_Endereco')[0].id 	= '';
		document.getElementsByName('Soc_Bairro')[0].id 		= '';
		document.getElementsByName('Soc_Cidade')[0].id 		= '';
		document.getElementsByName('Soc_CEP')[0].id 		= '';
		document.getElementsByName('Soc_Estado')[0].id 		= '';
		parametros = 'Pes_socio='+ escape(0)+'&Pes_Cpf_Cnpj='+ escape(document.getElementsByName('Pes_Cpf_Cnpj')[0].value);
		Ajax("../admin/x_socioscategoria.asp", parametros, 1, 'XPes_Categoria', 1, 0);
		document.getElementById('sConselho').innerHTML 	= '';
		document.getElementById('sTelCom').innerHTML 	= '';
		document.getElementById('sCel').innerHTML 		= '';
		document.getElementById('sEndCom').innerHTML 	= '';
		document.getElementById('sBairroCom').innerHTML = '';
		document.getElementById('sCEPCom').innerHTML 	= '';
		document.getElementById('sEstadoCom').innerHTML	= '';
		document.getElementById('sCidadeCom').innerHTML = '';
	}
	
	/*if (document.getElementsByName('Pes_Conselho')[0].value == "0")
	{
		//Com CRM		
		document.getElementsByName('Pes_CRM')[0].id = "";
		document.getElementsByName('Pes_CRM_Estado')[0].id = "";
		document.getElementById('sConselho').innerHTML 	= '';
	}
	else
	{
		//Sem CRM
		document.getElementsByName('Pes_CRM')[0].id = "REQ|Numero do conselho de classe";
		document.getElementsByName('Pes_CRM_Estado')[0].id = "REQ|Estado do conselho de classe";
		document.getElementById('sConselho').innerHTML 	= '* ';
	}*/
}

function camposObrigatoriosL(tmpCad)
{	
	if (document.getElementById('Pes_Socio1').checked)
	{
		//Sócio
		document.getElementsByName('Pes_CRM')[0].id 		= 'REQ|Numero do conselho de classe';
		document.getElementsByName('Pes_CRM_Estado')[0].id 	= 'REQ|Estado do conselho de classe';
		document.getElementsByName('Pes_Comercial1')[0].id 	= '';
		document.getElementsByName('Pes_Celular')[0].id 	= '';
		document.getElementsByName('Soc_Endereco')[0].id 	= '';
		document.getElementsByName('Soc_Bairro')[0].id 		= '';
		document.getElementsByName('Soc_Cidade')[0].id 		= '';
		document.getElementsByName('Soc_CEP')[0].id 		= '';
		document.getElementsByName('Soc_Estado')[0].id 		= '';
		document.getElementsByName('Pes_Crm')[0].id 		= 'REQ|Numero do conselho de classe';
		document.getElementsByName('Pes_Crm_Estado')[0].id 		= 'REQ|Estado do conselho de classe';
		
		parametros = 'Pes_socio='+ escape(1)+'&Pes_Cpf_Cnpj='+ escape(document.getElementsByName('Pes_Cpf_Cnpj')[0].value);
		Ajax("../admin/x_socioscategoria.asp", parametros, 1, 'XPes_Categoria', 1, 0);
		
		document.getElementById('sConselho').innerHTML 	= '* ';
		document.getElementById('sTelCom').innerHTML 	= '';
		document.getElementById('sCel').innerHTML 		= '';
		document.getElementById('sEndCom').innerHTML 	= '';
		document.getElementById('sBairroCom').innerHTML = '';
		document.getElementById('sCEPCom').innerHTML 	= '';
		document.getElementById('sEstadoCom').innerHTML	= '';
		document.getElementById('sCidadeCom').innerHTML = '';
	}
	else
	{
		//Não sócio
		if (tmpCad=="0"){
			document.getElementsByName('Pes_Email')[0].id 		= '';
		}
		document.getElementsByName('Pes_CRM')[0].id 		= '';
		document.getElementsByName('Pes_CRM_Estado')[0].id 	= '';
		document.getElementsByName('Pes_Comercial1')[0].id 	= '';
		document.getElementsByName('Pes_Celular')[0].id 	= '';
		document.getElementsByName('Soc_Endereco')[0].id 	= '';
		document.getElementsByName('Soc_Bairro')[0].id 		= '';
		document.getElementsByName('Soc_Cidade')[0].id 		= '';
		document.getElementsByName('Soc_CEP')[0].id 		= '';
		document.getElementsByName('Soc_Estado')[0].id 		= '';
		parametros = 'Pes_socio='+ escape(0)+'&Pes_Cpf_Cnpj='+ escape(document.getElementsByName('Pes_Cpf_Cnpj')[0].value);
		Ajax("../admin/x_socioscategoria.asp", parametros, 1, 'XPes_Categoria', 1, 0);
		document.getElementById('sConselho').innerHTML 	= '';
		document.getElementById('sTelCom').innerHTML 	= '';
		document.getElementById('sCel').innerHTML 		= '';
		document.getElementById('sEndCom').innerHTML 	= '';
		document.getElementById('sBairroCom').innerHTML = '';
		document.getElementById('sCEPCom').innerHTML 	= '';
		document.getElementById('sEstadoCom').innerHTML	= '';
		document.getElementById('sCidadeCom').innerHTML = '';
		if (tmpCad=="0"){
			document.getElementById('sEmail').innerHTML = '';
		}
	}
	
	/*if (document.getElementsByName('Pes_Conselho')[0].value == "0")
	{
		//Com CRM		
		document.getElementsByName('Pes_CRM')[0].id = "";
		document.getElementsByName('Pes_CRM_Estado')[0].id = "";
		document.getElementById('sConselho').innerHTML 	= '';
	}
	else
	{
		//Sem CRM
		document.getElementsByName('Pes_CRM')[0].id = "REQ|Numero do conselho de classe";
		document.getElementsByName('Pes_CRM_Estado')[0].id = "REQ|Estado do conselho de classe";
		document.getElementById('sConselho').innerHTML 	= '* ';
	}*/
}

function infoCongresso(cat)
{
	document.getElementById('info').innerHTML = '';
	if (cat == "2")
		document.getElementById('info').innerHTML = '* Sua carterinha será solicitada no local do Congresso.';
	else if (cat == "3")
		document.getElementById('info').innerHTML = '* Será necessária comprovação de associação ao DECA no local do Congresso.';
}

function infoCongressoLocal(cat)
{
	document.getElementById('info').innerHTML = '';
	if (cat == "2")
		document.getElementById('info').innerHTML = '* Solicitar CARTEIRINHA DE ESTUDANTE ou ÚLTIMO BOLETO PAGO.';
	else if (cat == "3")
		document.getElementById('info').innerHTML = '* Sistema identifica automaticamente a associação ao DECA.';
}



//Função BUSCA ENDEREÇO DO SITE DOS CORREIOS
function Busca_Endereco(valorCEP) {
	if(document.formulario.ufremetente.value != "XX"){
		winPopup('http://www.correios.com.br/servicos/falecomoscorreios/ctBuscaEndereco.cfm?cep=' + valorCEP +'&orig=1', 'Selecao', 200, 300, 1, 'status=yes, menubar=yes')
	}
}

/*
::: Limitar Quantidade de Caracteres em um Campo (text, textarea)
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
// 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);
	}
}


function confSenha() // confirmacao de senha - intranet
{
		senha1 = document.forms[0].Usr_Senha;
		senha2 = document.forms[0].Usr_Senha_Conf;

		if ((senha1.value.length > 0) && (senha1.value.length < 6))
		{
			window.alert('A senha precisa ter, no mínimo, 6 caracteres.');senha1.value='';senha2.value='';
		}

		if ((senha1.value.length > 0) && (senha2.value.length > 0) && (senha1.value != senha2.value))
		{
				window.alert('A confirmação de senha difere da senha! Digite novamente.');
				senha1.value = '';senha2.value = '';senha1.focus();
		}
}

function Conselho_classe(Pcon_Codigo)
{
var xmlhttp=new http();
xmlhttp.open("GET", "../conteudos/pgsocios_form_ajax.asp?Pcon_Codigo="+Pcon_Codigo+"&h="+ Date(),true);
xmlhttp.onreadystatechange=function(){
  if (xmlhttp.readyState==4)
  {
  	var response = xmlhttp.responseText;
	document.getElementById("Atividades1").innerHTML = response.replace(/\n/g, "");	
  }	
}
xmlhttp.send(null);

return false;
}

function removeElement(ElementPai, ElementRemove){
  var d = document.getElementById(ElementPai);
  var olddiv = document.getElementById(ElementRemove);
  d.removeChild(olddiv);
	document.getElementById('qtColunas').value=-1
	document.getElementById('qtLinhas').value=-1
	exibeTabela()
}


function TrataInsert(nome){
var tmpNome='';
var tmpFull='';
tmpNome =nome.value;
tmpNome = tmpNome.toLowerCase();
tmpNome=tmpNome.split(" ");
for (d=0; d<tmpNome.length; d++){
	if (tmpNome[d].length>2){
	char1 = tmpNome[d].charAt(0)
	char2 = char1.toUpperCase();
	tmpNome[d] = tmpNome[d].replace(char1, char2)
	}
	if (tmpFull!=""){
	tmpFull = tmpFull + ' '
	}
	tmpFull = tmpFull + tmpNome[d];
}
nome.value = tmpFull;
}


/*
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
::: Visualizar Div On e Off
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
// Modo de Usar: jsCheckDiv=('NomeDoDiv', 'tmpForceOnOff');"

function jsCheckDiv(NomeDoDiv, tmpForceOn) {
	NomeDoDiv = document.getElementById(NomeDoDiv);
	if (NomeDoDiv == '[object]'){
		if (tmpForceOn == '') {
			if (NomeDoDiv.style.display == '') {
				NomeDoDiv.style.display = 'none';
			} else {
				NomeDoDiv.style.display = '';
			}
		} else { 
			if (tmpForceOn == 'On') {
				NomeDoDiv.style.display = '';
			} else if (tmpForceOn == 'Off') {
				NomeDoDiv.style.display = 'none';
			}
		}
	}
}