//\\//\\//\\//\\//\\//\\//\\//\\
//     ENP javascript api     \\
//\\//\\//\\//\\//\\//\\//\\//\\

//------------------------------------------------------------------------------
// Asinchronous JavaScript And XML functions
//------------------------------------------------------------------------------
try{
    xmlhttp = new XMLHttpRequest();
}catch(ee){
    try{
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }catch(e){
        try{
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }catch(E){
            xmlhttp = false;
        }
    }
}

//------------------------------------------------------------------------------
// Main menu functions
//------------------------------------------------------------------------------
function show( obj ){
	if( document.getElementById( obj ).style.display == "none" ){
		document.getElementById( obj ).style.display = "block";
	}else{
		document.getElementById( obj ).style.display = "none";
	}
}

function hide( obj ){
	document.getElementById( obj ).style.display = "none";
}

//------------------------------------------------------------------------------
// Tabs functions
//------------------------------------------------------------------------------
function setTabs(){
	alert("ok");
}

function set_active( tab ){
	//set active tab and tabpanel as inactive
	//set_inactive();

	//change class of tab and tabpanel clicked
	document.getElementById( tab ).className = "tabtab";
	document.getElementById( tab+"panel" ).className = "tabpanel";
}

function set_inactive( tab, tabpanel ){
}

//called when mouse is over a tab
function tabOver( obj, classe ){
	//document.getElementById( obj ).onmouseout = tabOut(obj, classe);
	if( document.getElementById( obj ).className != "tabtab" ){
		document.getElementById( obj ).className = "tabover";
	}
}

function tabOut( obj, oldclass ){
	if( oldclass == "tabtab"){
		document.getElementById( obj ).className = "tabtab";
	}else{
		document.getElementById( obj ).className = "tabinactive";
	}
}

function tabClick( item ){
	divs = document.getElementsByTagName('div');

	for(i = 0; i < divs.length; i++){
		//var divname = divs[i].id;
		//var divtab = divs[i].className =;
		if( divs[i].className == "tabtab" ){
			divs[i].className = "tabinactive";
		}

		if( divs[i].className == "tabpanel" ){
			divs[i].style.display = "none";
		}
		//mostra tab clicada
		if( divs[i].id == item.id){
			divs[i].className = "tabtab";
		}
		//mostra div conteudo
		if( divs[i].id == (item.id+"panel") ){
			divs[i].className = "tabpanel";
			divs[i].style.display = "block";
		}
	}
}

//------------------------------------------------------------------------------
// Messages function
// maybe you must say what kind of callback this will handle
//------------------------------------------------------------------------------
function message_info( msg, callback ){
	//mount message

	//write text

	//show it
}

function message_error( msg, callback ){
	//mount message

	//write text

	//show it
}

function message_ask( msfg, callOK, callNO){
	//mount message

	//write text

	//show it
}

//------------------------------------------------------------------------------
// Mask function
// each type of field has its mask
//------------------------------------------------------------------------------
function formatar(o, f){
	v_obj=o
	v_fun=f
	setTimeout("execmascara()",1)
}
	
function execmascara(){
	v_obj.value=v_fun(v_obj.value)
}

function maskDate( v ){
	//usage: onKeyPress
	// <input type='text' name='teste' id='teste' onKeyPress="formatar(this,maskDate)" size='30' maxlength='10'>
	v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
	v=v.replace(/(\d{2})(\d)/,"$1/$2")       //Coloca uma barra entre o segundo dígitos
	v=v.replace(/(\d{2})(\d)/,"$1/$2")       //Coloca uma barra antes dos 4 ultimos digitos
	return v
}

function maskTime( v ){
	//usage: onKeyDown
	//<input type='text' name='teste' id='teste' onKeyPress="formatar(this,maskTime)" size='30' maxlength='8'>
	v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
	v=v.replace(/(\d{2})(\d)/,"$1:$2")       //Coloca uma barra entre o segundo dígitos
	v=v.replace(/(\d{2})(\d)/,"$1:$2")       //Coloca uma barra antes dos 4 ultimos digitos
	v=v.replace(/(\d{2})(\d)/,"$1:$2")
	return v
}

//Começa a função para verificação de valores em reais.
//<input type='text' name='teste' id='teste' onkeypress="maskValue(this,event)" onkeydown="backspace(this,event)" size='30' maxlength='14'>
documentall = document.all;

function formatamoney(c) {
    var t = this; if(c == undefined) c = 2;		
    var p, d = (t=t.split("."))[1].substr(0, c);
    for(p = (t=t[0]).length; (p-=3) >= 1;) {
	        t = t.substr(0,p) + "." + t.substr(p);
    }
    return t+","+d+Array(c+1-d.length).join(0);
}

String.prototype.formatCurrency=formatamoney

function demaskvalue(valor, currency){
	/*
		* Se currency é false, retorna o valor sem apenas com os números. Se é true, os dois últimos caracteres são considerados as 
		* casas decimais
	*/
	var val2 = '';
	var strCheck = '0123456789';
	var len = valor.length;
	if (len== 0){
		return 0.00;
	}

	if (currency ==true){	
		/* Elimina os zeros à esquerda 
		* a variável  <i> passa a ser a localização do primeiro caractere após os zeros e 
		* val2 contém os caracteres (descontando os zeros à esquerda)
		*/
		
		for(var i = 0; i < len; i++){
			if ((valor.charAt(i) != '0') && (valor.charAt(i) != ',')) break;
		}
		
		for(; i < len; i++){
			if (strCheck.indexOf(valor.charAt(i))!=-1) val2+= valor.charAt(i);
		}

		if(val2.length==0) return "0.00";
		if (val2.length==1)return "0.0" + val2;
		if (val2.length==2)return "0." + val2;
		
		var parte1 = val2.substring(0,val2.length-2);
		var parte2 = val2.substring(val2.length-2);
		var returnvalue = parte1 + "." + parte2;
		return returnvalue;
		
	}
	else{
		/* currency é false: retornamos os valores COM os zeros à esquerda, 
			* sem considerar os últimos 2 algarismos como casas decimais 
		*/
		val3 ="";
		for(var k=0; k < len; k++){
			if (strCheck.indexOf(valor.charAt(k))!=-1) val3+= valor.charAt(k);
			}			
		return val3;
	}
}

function maskValue(obj,event){
	var whichCode = (window.Event) ? event.which : event.keyCode;
	/*
		Executa a formatação após o backspace nos navegadores !document.all
	*/
	if (whichCode == 8 && !documentall) {	
		/*
			Previne a ação padrão nos navegadores
		*/
		if (event.preventDefault){ //standart browsers
				event.preventDefault();
		}
		else{ // internet explorer
			event.returnValue = false;
		}
		var valor = obj.value;
		var x = valor.substring(0,valor.length-1);
		obj.value= demaskvalue(x,true).formatCurrency();
		return false;
	}
	/*
		Executa o Formata Reais e faz o format currency novamente após o backspace
	*/
	FormataReais(obj,'.',',',event);
} // end reais


function backspace(obj,event){
	/*
		Essa função basicamente altera o  backspace nos input com máscara reais para os navegadores IE e opera.
		O IE não detecta o keycode 8 no evento keypress, por isso, tratamos no keydown.
		Como o opera suporta o infame document.all, tratamos dele na mesma parte do código.
	*/
	
	var whichCode = (window.Event) ? event.which : event.keyCode;
	if (whichCode == 8 && documentall) {
		var valor = obj.value;
		var x = valor.substring(0,valor.length-1);
		var y = demaskvalue(x,true).formatCurrency();
		
		obj.value =""; //necessário para o opera
		obj.value += y;
		
		if (event.preventDefault){ //standart browsers
				event.preventDefault();
		}
		else{ // internet explorer
			event.returnValue = false;
		}
		return false;
		
	}// end if		
}// end backspace

function FormataReais(fld, milSep, decSep, e) {
	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 == 8 ) return true; //backspace - estamos tratando disso em outra função no keydown
	if (whichCode == 0 ) return true;
	if (whichCode == 9 ) return true; //tecla tab
	if (whichCode == 13) return true; //tecla enter
	if (whichCode == 16) return true; //shift internet explorer
	if (whichCode == 17) return true; //control no internet explorer
	if (whichCode == 27 ) return true; //tecla esc
	if (whichCode == 34 ) return true; //tecla end
	if (whichCode == 35 ) return true;//tecla end
	if (whichCode == 36 ) return true; //tecla home
	
	/*
		O trecho abaixo previne a ação padrão nos navegadores. Não estamos inserindo o caractere normalmente, mas via script
	*/
	
	if (e.preventDefault){ //standart browsers
		e.preventDefault()
	}
	else{ // internet explorer
		e.returnValue = false;
	}
	
	var key = String.fromCharCode(whichCode);  // Valor para o código da Chave
	if (strCheck.indexOf(key) == -1) return false;  // Chave inválida
	
	/*
		Concatenamos ao value o keycode de key, se esse for um número
	*/
	fld.value += key;
	
	var len = fld.value.length;
	var bodeaux = demaskvalue(fld.value,true).formatCurrency();
	fld.value=bodeaux;
	
	/*
	Essa parte da função tão somente move o cursor para o final no opera. Atualmente não existe como movê-lo no konqueror.
	*/
	if (fld.createTextRange) {
		var range = fld.createTextRange();
		range.collapse(false);
		range.select();
	}
	else if (fld.setSelectionRange) {
		fld.focus();
		var length = fld.value.length;
		fld.setSelectionRange(length, length);
	}
	return false;
}

//Termina função para separação de valores reais.

function maskInteger( obj ){
	//usage: onKeyPress
	if (document.all) // Internet Explorer
		var tecla = event.keyCode;
	else
		if(document.layers) // Nestcape
			var tecla = e.which;
	if (tecla > 47 && tecla < 58) // numeros de 0 a 9
		return true;
	else{
		if ((tecla == 8) || (tecla == 13) || (tecla == 9)) // backspace, Enter, TAB
			return true;
		else
			event.keyCode = 0;//return false;
	}
}

function maskFone( v ){
	//usage: onKeyPress
	//<input type='text' name='teste' id='teste' onKeyPress="formatar(this,maskFone)" size='30' maxlength='13'>
	v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
	v=v.replace(/(\d{0})(\d)/,"$1($2")       //Coloca um ponto entre o terceiro e o quarto dígitos
	v=v.replace(/(\d{2})(\d)/,"$1)$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
	//de novo (para o segundo bloco de números)
	v=v.replace(/(\d{4})(\d{1,4})$/,"$1-$2") //Coloca um hífen entre o quarto digito
	return v
}

function maskSoNum(v){
	//<input type='text' name='teste' id='teste' onKeyPress="formatar(this,maskSoNum)" size='?' maxlength='?'>
    return v.replace(/\D/g,"")
}

function maskCEP( v ){
	//usage: onKeyPress
	//<input type='text' name='teste' id='teste' onKeyPress="formatar(this,maskCEP)" size='30' maxlength='10'>
		v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
		v=v.replace(/(\d{2})(\d)/,"$1.$2")       //Coloca um ponto entre o segundo dígitos
		v=v.replace(/(\d{3})(\d)/,"$1-$2")       //Coloca um traço antes dos 3 ultimos digitos
		return v
}

function maskCPF( v ){
	//usage: onKeyPress
	//<input type='text' name='teste' id='teste' onKeyPress="formatar(this,maskCPF)" size='30' maxlength='14'>
	v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
	v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
	v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
	//de novo (para o segundo bloco de números)
	v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2") //Coloca um hífen entre o terceiro e o quarto dígitos
	return v
}

function maskCNPJ( v ){
	//usage: onKeyPress
	//<input type='text' name='teste' id='teste' onKeyPress="formatar(this,maskCNPJ)" size='30' maxlength='18'>
	v=v.replace(/\D/g,"")                           //Remove tudo o que não é dígito
	v=v.replace(/^(\d{2})(\d)/,"$1.$2")             //Coloca ponto entre o segundo e o terceiro dígitos
	v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3") //Coloca ponto entre o quinto e o sexto dígitos
	v=v.replace(/\.(\d{3})(\d)/,".$1/$2")           //Coloca uma barra entre o oitavo e o nono dígitos
	v=v.replace(/(\d{4})(\d)/,"$1-$2")              //Coloca um hífen depois do bloco de quatro dígitos
	return v
}

function maskIE( obj ){
	//usage: onKeyDown
}

//------------------------------------------------------------------------------
// Validation functions
// params are the value of the field to be evaluated
//------------------------------------------------------------------------------
function evalDate( date ){
	//dd/mm/aaa
	var RegExPattern = /^((((0?[1-9]|[12]\d|3[01])[\.\-\/](0?[13578]|1[02])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|[12]\d|30)[\.\-\/](0?[13456789]|1[012])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|1\d|2[0-8])[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|(29[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))|(((0[1-9]|[12]\d|3[01])(0[13578]|1[02])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|[12]\d|30)(0[13456789]|1[012])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|1\d|2[0-8])02((1[6-9]|[2-9]\d)?\d{2}))|(2902((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00))))$/;

	if (!((data.match(RegExPattern)) && (data!=''))) {
		return false;
	}else{
		return true;
	}
}

function evalTime( time ){
}

function evalValue( val ){
}

function evalInteger( integer ){
}

function evalEmail( mail ){
}

function evalCPF( cpf ){
}

function evalCNPJ( cnpj ){
}

//

