// Adiciona novas constantes para a classe String
String.PAD_LEFT  = 0;
String.PAD_RIGHT = 1;
String.PAD_BOTH  = 2;

// Adiciona o método pad() para a clase String
String.prototype.pad = function(size, pad, side) 
{
	var str = this, append = '', size = (size - str.length);
	var pad = ((pad!=null)?pad:' ');
	if((typeof size!='number')||((typeof pad!='string')||(pad==''))) 
	{
		throw new Error('Wrong parameters for String.pad() method.');
	}
	if(side==String.PAD_BOTH)
	{
		str = str.pad((Math.floor(size/2) + str.length),pad,String.PAD_LEFT);
		return str.pad((Math.ceil(size/2) + str.length),pad,String.PAD_RIGHT);
	}
	while((size -= pad.length)>0) 
	{
		append += pad;
	}
	append += pad.substr(0,(size + pad.length));
	return ((side==String.PAD_LEFT)?append.concat(str):str.concat(append));
}

// Adiciona o método trim() para a classe String
String.prototype.trim = function()
{ 
	return this.replace(/(^\s*)|(\s*$)/g, '');
}

// Mantém o menu sempre na mesma posiçao
function window_onscroll()
{
	divMenu.style.top = document.body.scrollTop;	
	return true;
}

// Vai para determinada página
function go_to(pagina)
{
	location='spes_tr.php?pagina='+pagina;
}

// Classe CallBack
var _xmlhttp_obj = null;
var _http_response_func = null;
var _http_debug_func = null;
var _element_cold = null;
// Constructor - chamada da classe
function CallBack(url)
{
	var i = null;
	this.params = new Array();
	this.http_url = url;
	return this;
}
// setURL(String) - indica para a classe qual a url a ser chamada
CallBack.prototype.setURL = function()
{
	this.http_url = arguments[0];
}
// setParameters(Array[2], Array[2],...) - indica os parâmetros httprequest a serem enviados
CallBack.prototype.setParameters = function()
{
	var param = new Array();
	for(i=0;i<arguments.length;i++)
	{
		param[i] = arguments[i]
	}
	this.params = param;
}
// addParameters(String,String) - adiciona um parâmetro (chave,valor) httprequest individualmente
CallBack.prototype.addParameters = function()
{
	if(arguments.length==2)
	{
		this.params[this.params.length] = new Array(arguments[0],arguments[1]);
	}
}
// setTargetResponse(Object) - indica o objeto function a ser executado ao retornar o resultado
CallBack.prototype.setTargetResponse = function ()
{
	_http_response_func = arguments[0];
}
// setDebugTarget(Function) - indica uma funçao que receberá o objeto XMLHTTP
CallBack.prototype.setTargetDebug = function()
{
	_http_debug_func = arguments[0];
}
// sendRequest - envia a requisição
CallBack.prototype.sendRequest = function()
{
	try
	{
		_xmlhttp_obj = new ActiveXObject('Microsoft.XMLHTTP');
		if(_xmlhttp_obj)
		{
			_xmlhttp_obj.onReadyStateChange = this._getResponse;
			_xmlhttp_obj.open(this.http_url.indexOf('?')==-1?'POST':'GET',this.http_url,true);
			if(this.http_url.indexOf('?')==-1)
			{
				_xmlhttp_obj.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
				_xmlhttp_obj.setRequestHeader('Cache-Control','no-store,no-cache,must-revalidate');
				_xmlhttp_obj.setRequestHeader('Cache-Control','post-check=0,pre-check=0');
				_xmlhttp_obj.setRequestHeader('Pragma','no-cache');
				var strpost = '';
				var charspc = '';
				for(i=0;i<this.params.length;i++)
				{
					try
					{
						charspc = this.params[i][1].toString();
						while(charspc.indexOf('&')>-1)
						{
							charspc = charspc.replace('&','%26');
						}
						while(charspc.indexOf('+')>-1)
						{
							charspc = charspc.replace('+','%2B');
						}
						strpost += this.params[i][0]+'='+escape(charspc)+'&';
					}
					catch(exc)
					{
						alert(exc.message);
						return false;
					}
				}
				strpost = strpost.substr(0,strpost.length-1);//.replace('+','%2B');
			}
			else
				var strpost = null;
			if(_element_cold!=null) _element_cold.disabled = true;
			_xmlhttp_obj.send(strpost);
		}
		else
		{
			alert('Seu navegador não suporta AJAX');
			return false;
		}
		return true;
	}
	catch(e)
	{
		alert(e.message);
		return false;
	}
}
// coldElement - Desabilita um elemento enquanto o sendRequest está rodando
CallBack.prototype.coldElement = function(obj)
{
	_element_cold = obj;
}
// _getResponse - função interna que trata o retorno e executa a função indicada em setTargetResponse
CallBack.prototype._getResponse = function()
{
	if(_http_debug_func!=null)
	{
		_http_debug_func(_xmlhttp_obj);
	}
	if(_xmlhttp_obj.readyState==4)
	{
		if(_xmlhttp_obj.status==200)
		{
			
			var text = _xmlhttp_obj.responseText;
			text = text.replace(/\+/g,' ');
			text = unescape(text);
			_http_response_func(text);
			//_http_response_func = null;
			if(_element_cold!=null)
			{
				_element_cold.disabled = false;
				_element_cold = null;
			}
			_http_debug_func = null;
		}
		else
		{
			alert('Nao foi possível responder a requisiçao\nErro HTTP: '+_xmlhttp_obj.status+'\n'+_xmlhttp_obj.statusText);
		}
	}
}

// Funçao para retornar só números
function onlyNumbers(text)
{
	var chr;
	var buffer = '';
	for(var i=0;i<text.length;i++)
	{
		chr = text.substr(i,1);
		if(chr>='0' && chr<='9')
		{
			buffer += chr;
		}
	}
	
	return buffer;
}

// Funçao para validar CPF
function validarCPF(obj)
{
	var cpf = obj.value.trim();
	
	if(cpf=='')
		return true;
	else
		cpf = onlyNumbers(cpf);
	
	if(cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" ||
		cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" ||
	  	cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" ||
	  	cpf == "88888888888" || cpf == "99999999999")
	{
	  	window.alert("CPF inválido");
		obj.focus();
	  	return false;
	}

   soma = 0;
   for(i = 0; i < 9; i++)
   	 soma += parseInt(cpf.charAt(i)) * (10 - i);
   resto = 11 - (soma % 11);
   if(resto == 10 || resto == 11)
	 resto = 0;
   if(resto != parseInt(cpf.charAt(9))){
	 window.alert("CPF inválido");
	 obj.focus();
	 return false;
   }
   soma = 0;
   for(i = 0; i < 10; i ++)
	 soma += parseInt(cpf.charAt(i)) * (11 - i);
   resto = 11 - (soma % 11);
   if(resto == 10 || resto == 11)
	 resto = 0;
   if(resto != parseInt(cpf.charAt(10))){
     window.alert("CPF inválido");
	 obj.focus();
	 return false;
   }
   return true;
 }

function mascara(Campo,mascara,auto) 
{ 
	if(auto==null)
		auto = true;
	if(auto)
	{
		// Adiciona o evento que trata o ano	
		Campo.onblur = function ()
		{
			if(mascara=='99/99/99')
			{
				var data = new Date();
				if(Campo.value.trim().length==1 || Campo.value.trim().length==2)
				{
					Campo.value = (Campo.value.trim().length==1?'0':'')+Campo.value+'/'+(data.getMonth()+1).toString().pad(2,'0',String.PAD_LEFT)+'/'+data.getFullYear().toString().substr(2,2).pad(2,'0',String.PAD_LEFT);
				}
				if(Campo.value.trim().length==5)
				{
					Campo.value += '/'+data.getFullYear().toString().substr(2,2).pad(2,'0',String.PAD_LEFT);
				}
				if(!CheckDate(Campo))
				{
					alert('Data inválida');
					Campo.focus();
				}
			}
		};
	};
	document.selection.createRange().text = '';
	teclapres = event;
	strtext = Campo.value;
    tamtext = strtext.length; 
    //pegando o tamanho da mascara 
    tammask = mascara.length;
    //criando um array para guardar cada caractere da mscara 
    arrmask = new Array(tammask);     
    //jogando os caracteres para o vetor 
    for (var i=0;i<tammask;i++)
	{ 
        arrmask[i] = mascara.slice(i,i+1); 
    } 
	ctrl = teclapres.ctrlKey; // CTRL
    //inicia a formatacao 
	if (((teclapres.keyCode>=65 && teclapres.keyCode<=90) || // 0 a 9 (tecl. sup.)
		(teclapres.keyCode>=97 && teclapres.keyCode<=122) && (arrmask[tamtext]=='A' || arrmask[tamtext]=='#' || arrmask[tamtext+1]=='A' || arrmask[tamtext+1]=='#')) || // 0 a 9 (tecl. sup.)
		((teclapres.keyCode>=37 && teclapres.keyCode<=40) || // 0 a 9 (tecl. sup.)
		(teclapres.keyCode>=48 && teclapres.keyCode<=57) && (arrmask[tamtext]=='9' || arrmask[tamtext]=='#' || arrmask[tamtext+1]=='9' || arrmask[tamtext+1]=='#')) || // %, &, ', (
//        	(teclapres.keyCode >= 96 && teclapres.keyCode <= 105) || // 0 a 9 (tecl. num.)
		(ctrl && teclapres.keyCode==67) ||  // ctrl + c  
		(ctrl && teclapres.keyCode==99) ||  // ctrl + c     	
		(ctrl && teclapres.keyCode==86) ||  // ctrl + v
		(ctrl && teclapres.keyCode==118) || // ctrl + v      	
		(teclapres.keyCode==8) ||  // backspace
		(teclapres.keyCode==9) ||  // tab
		(teclapres.keyCode==46) || // delete
		(teclapres.keyCode==13))  // Enter
	{
		organize(Campo,arrmask[tamtext],teclapres.keyCode,strtext);
		if ((ctrl && teclapres.keyCode==67) ||  // ctrl + c  
			(ctrl && teclapres.keyCode==99) ||  // ctrl + c     	
			(ctrl && teclapres.keyCode==86) ||  // ctrl + v
			(ctrl && teclapres.keyCode==118))   // ctrl + v                    
			ctrl = false;
	} 
	else 
	{ // ignora outro evento
		event.returnValue = false;
		if (strtext != "") 
		{
			Campo.value = strtext;
		} 
	}
}

// Mtodo utilizado com o formatField
// Organiza o campo de acordo com a mscara
function organize(Campo,arrpos,teclapres_key,strtext)
{ 
    if (((arrpos=='/') || 
    	 (arrpos=='.') || 
    	 (arrpos==',') || 
    	 (arrpos==':') || 
    	 (arrpos==' ') || 
    	 (arrpos=='-')) && 
    	 teclapres_key!=8) // backspace 
	{
        separador = arrpos ;
        masktext = strtext+separador ;
        Campo.value = masktext ;
    }
} 

// Limpa listbox
function resetList(list)
{
	if(list.type=='select-one')
		while(list.options.length>0)
			list.options.remove(0);
}


