/***
* Descrição.: formata um campo do formulário de
* acordo com a máscara informada...
* Parâmetros: - objForm (o Objeto Form)
* - strField (string contendo o nome
* do textbox)
* - sMask (mascara que define o
* formato que o dado será apresentado,
* usando o algarismo "9" para
* definir números e o símbolo "!" para
* qualquer caracter...
* - evtKeyPress (evento)
* Uso.......: <input type="textbox"
* name="xxx".....
* onkeypress="return txtBoxFormat(document.rcfDownload, 'str_cep', '99999-999', event);">
* Observação: As máscaras podem ser representadas como os exemplos abaixo:
* CEP -> 99.999-999
* CPF -> 999.999.999-99
* CNPJ -> 99.999.999/9999-99
* Data -> 99/99/9999
* Tel Resid -> (99) 999-9999
* Tel Cel -> (99) 9999-9999
* Processo -> 99.999999999/999-99
* C/C -> 999999-!
* E por aí vai...
***/

function txtBoxFormat(objForm, strField, sMask, evtKeyPress) {
	var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;
	
	if(document.all) { // Internet Explorer
		nTecla = evtKeyPress.keyCode; }
	else if(document.layers) { // Nestcape
		nTecla = evtKeyPress.which;
	} else {
		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( " ", "" );
	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) == " "))
		
		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;
	}
}
//Fim da Função Máscaras Gerais
function currencyFormat(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 == 13) return true;  // Enter
	if (whichCode == 8) return true;  // Delete
	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) {
		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;
}

function verifica(campo){
	i = 0;
	while(campo[i].name != "Submit"){
		if (campo[i].id != "") {
		 	if (campo[i].value == "" || campo[i].value == "OBRIGATÓRIO") {
      			alert('Campo '+campo[i].id+" é de preenchimento obrigatório!");
				if(campo[i].disabled == true){
					campo[i].disabled = false;
				}
				if(campo[i].name != "estado" && campo[i].name != "end_estado" && campo[i].name != "info_busca"){
					campo[i].value = "OBRIGATÓRIO";
					campo[i].focus();
					campo[i].select();
      				return false;
				} else {
					campo[i].focus();
      				return false;
				}
				return false;
			}
			if(campo[i].name == "phone"){
				if(document.getElementById('Telefone').value.length!=14){
					alert('Telefone incompleto');
					campo[i].focus();
					campo[i].select();
      				return false;
				}
			}
			if(campo[i].name == "celular"){
				if(document.getElementById('Celular').value.length!=14){
					alert('Celular incompleto');
					campo[i].focus();
					campo[i].select();
      				return false;
				}
			}
			if(campo[i].name == "email"){
				//email
				if(document.getElementById('E-mail').value!=''){
					validaEmail(document.getElementById('E-mail'), true);
				}
				if(document.getElementById('E-mail').value==''){
				  	return false;
				}
			}
	   		i++;
		} else {
			i++;
		}
	}
}

//validação email
function validaEmail(obj, alerta)
{
	var str = obj.value;

	// @ deve estar pelo menos na posição 1 de str,
	// deve estar pelo menos na posição 3 de str e não pde pode estar na última posição de str.
	if(str.length>0 && (str.indexOf('@') < 1 || str.indexOf('.') < 3 || (str.length < 5) || (str.substr(str.length-1, 1) == '.')))
	{
		// exibe mensagem ao usuário.
		if(alerta)
		{
			alert('E-mail inválido: ' + str);
			obj.value=''			
		}
		if(obj != null)
		{
			obj.focus();
		}
		return false;
	} else {
		return true;
	}
}
//CEP
function Mascara_CEP (formato, objeto) {
	campo = eval (objeto);
	if (formato=='CEP') {
		caracteres = '01234567890';
		separacoes = 2;
		separacao2 = '-';
		conjuntos = 2;
		conjunto1 = 5;
		conjunto2 = 9;
		if ((caracteres.search(String.fromCharCode (window.event.keyCode))!=-1) && campo.value.length < (conjunto2)) {
			if (campo.value.length == conjunto1) campo.value = campo.value + separacao2;
		}
		else  event.returnValue = false;
	} 
}
function Mascara_DATA (formato, objeto) {
	campo = eval (objeto);
	if (formato=='DATA') {
		caracteres = '01234567890';
		separacoes = 2;
		separacao1 = '\/';
		conjuntos = 3;
		conjunto1 = 2;
		conjunto2 = 5;
		conjunto3 = 10;
		if ((caracteres.search(String.fromCharCode (tecla))!=-1) && campo.value.length < (conjunto3)) {
			if (campo.value.length == conjunto1 || campo.value.length == conjunto2) campo.value = campo.value + separacao1;
		}
		else e.returnValue = false;
	}
}
//CPF
function Mascara_CPF (formato, objeto) {
	campo = eval(objeto);
	if (formato=='CPF') {
		caracteres = '01234567890';
		separacoes = 3;
		separacao1 = '.';
		separacao2 = '-';
		conjuntos = 4;
		conjunto1 = 3;
		conjunto2 = 7;
		conjunto3 = 11;
		conjunto4 = 14;
		if ((caracteres.search(String.fromCharCode (window.event.keyCode))!=-1) && campo.value.length < (conjunto4)) {
			if (campo.value.length == conjunto1) campo.value = campo.value + separacao1;
			else if (campo.value.length == conjunto2) campo.value = campo.value + separacao1;
			else if (campo.value.length == conjunto3) campo.value = campo.value + separacao2;
		}
		else event.returnValue = false;
	} 
}

function FormataCpf(c) {
	vr = c;
	vr = vr.replace (".","");
	vr = vr.replace (".","");
	vr = vr.replace (".","");
	vr = vr.replace (",","");
	vr = vr.replace (",","");
	vr = vr.replace (",","");
	vr = vr.replace ("-","");
	return vr;
}

function getCheckedValue(radioObj) {
	if(!radioObj)
	return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
	if(radioObj.checked)
	return radioObj.value;
	else
	return "";
	for(var i = 0; i < radioLength; i++){
		if(radioObj[i].checked){
			return radioObj[i].value;
		}
	}
	return "";
} 

function testWin(myform, windowname){
	if (! window.focus)return true;
	//window.open('', windowname, 'top=100,left=100,height=400,width=500,location=no,resizable=no,scrollbars=yes,status=yes');
	//myform.target=windowname;
	return true;
}

function envia(){
	//document.getElementById('bt_confirma').style.display = 'none';
	document.Pagamento.forma.value = getCheckedValue(document.Pagamento.pagamento.value);
	document.Pagamento.submit();
}

function completa(){
	document.Form2.first_name_s.value=document.Form2.first_name.value;
	document.Form2.last_name_s.value=document.Form2.last_name.value;
	document.Form2.data_nasc_s.value=document.Form2.data_nasc.value;
	document.Form2.street_s.value=document.Form2.street.value;
	document.Form2.bairro_s.value=document.Form2.bairro.value;
	document.Form2.city_s.value=document.Form2.city.value;
	document.Form2.state_s.value=document.Form2.state.value;
	document.Form2.zip_s.value=document.Form2.zip.value;
	document.Form2.country_s.value=document.Form2.country.value;
}
function NewWindow(mypage, myname, w, h, scroll) {
    var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable, statusbar=1'
	win = window.open(mypage, myname, winprops)
	if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}
function fecha(div) {
    document.getElementById(div).style.display = "none";
}
function controla_div(div) {
    document.getElementById(div).style.display = "";
}
