/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

	Copyright (c) 2008 AgenciaWX Development Team
	Script com funções para envio de formulario via ajax

- Obrigatório a variavel ID	na tag do campo do form
- Obrigatório a variavel name para enviar o campo ao formulario

OBS:
"nos select multiplo se tiver o atributo 'tudo' configurado, ele enviará todo os dados mesmo q nao esteja selecionado"

=== VALIDACAMPOUNICO ===
Obrigatório resposta em XML com o seguinte layout:

$xml = "<?xml version='1.0' encoding='iso-8859-1'?>\n";
$xml .= "<wxval>\n";
	$xml .= "\t<erro></erro>\n";
	$xml .= "\t<msg></msg>\n";
$xml .= "</wxval>\n";

=== SUBMITAJAX ===
No Lado do servidor é obrigatório a resposta em XML com o seguinte layout:


// ERRO GERAL (OBRIGATORIO SEMPRE)

$xml = "<?xml version='1.0' encoding='iso-8859-1'?>\n";
	$xml .= "<wxval>\n";
		$xml .= "\t<errogeral>\n";
			$xml .= "\t\t<erro>1</erro>\n";
			$xml .= "\t\t<erro_numero>" . $conn->ErrorNo() . "</erro_numero>\n";
			$xml .= "\t\t<erro_desc>" . $conn->ErrorMsg() . "\n" . $sql_cadastro . "</erro_desc>\n";
		$xml .= "\t</errogeral>\n";
	$xml .= "</wxval>\n";
exit($xml);


// ERRO ESPECIFICO DO CAMPO

* Obrigatório apenas para campos q se deseja fazer a validação no lado do servidor

$xml = "<?xml version='1.0' encoding='iso-8859-1'?>\n";
$xml .= "<wxval>\n";
	$xml .= "\t<campo>\n";
		$xml .= "\t\t<id>CampoTeste1</id>\n";
		$xml .= "\t\t<erro></erro>\n";
		$xml .= "\t\t<msg>Usuário " . $valor ." já cadastrado</msg>\n";
	$xml .= "\t</campo>\n";
	$xml .= "\t<campo>\n";
		$xml .= "\t\t<id>CampoTeste2</id>\n";
		$xml .= "\t\t<erro></erro>\n";
		$xml .= "\t\t<msg>Usuário " . $valor ." já cadastrado</msg>\n";
	$xml .= "\t</campo>\n";
	$xml .= "\t<errogeral>\n";
		$xml .= "\t\t<erro>1</erro>\n";
		$xml .= "\t\t<erro_numero>" . $conn->ErrorNo() . "</erro_numero>\n";
		$xml .= "\t\t<erro_desc>" . $conn->ErrorMsg() . "\n" . $sql_cadastro . "</erro_desc>\n";
	$xml .= "\t</errogeral>\n";
$xml .= "</wxval>\n";

para ser tratado corretamento no lado do cliente

*/
// ======================================================================================================================
//                   				FORMULÁRIO AJAX
// ======================================================================================================================

// TODO: Refazer todo o script, otimizar, usar classe estilo wxupload e aumentar numero de metodos

// ======================================================================
// ENVIA FORMULARIO POR AJAX (REQUERIDO JQUERY)
// ======================================================================
function sendFormAjax(f_obj,function_return, debug){

   	var variaveis = "";
	var action = $(f_obj).attr('action');
	var method = new String($(f_obj).attr('method')).toUpperCase();
	var tag;
	var tipo;
	var nome;
	var valor;

	debug = (debug >= 2) ? true : false;

	// ===============================
	// Verificacao
	// ===============================

	// Padrão

	if (method == "UNDEFINED" || !method)
		method = "POST";

	if (method != "GET" && method != "POST"){
		//throw "Método deve ser GET ou POST";
		alert('ERRO NO FORM: "Método deve ser GET ou POST"')
		return false;

	}

	if (action == "undefined" || !action){
		alert('ERRO NO FORM: "Action não foi definido"')
		return false;
	}


	if (!f_obj.id){
		//throw "Id não definido";
		alert('ERRO NO FORM: "Id não definido"')
		return false;
	}



	// ===============================
	// Pega todos os elementos do Form
	// ===============================

	$('#' + f_obj.id + ' [on=1]').each(function(){
		tag = new String($(this).attr('tagName')).toUpperCase();
		tipo = new String($(this).attr('type')).toUpperCase();
		name = $(this).attr('name');
		valor = $(this).attr('value');
        on = $(this).attr('on');    // Se está 'ligado'



        //alert('name(' + name + ') tipo(' + tipo + ') tag(' + tag + ') valor(' + valor + ')');
		// ============================================================================
		// PEGA APENAS AS TAG INPUT, SELECT, TEXTAREA SE tiverem a tag name configurada
		// ============================================================================
		if ((tag == "INPUT" || tag == "SELECT" || tag == "TEXTAREA") && name && on)
		{

			// ================================================================
			// TIPO FILE
			// ================================================================
			if(tipo == "FILE")
				throw "sendFormAjax: Não é possível enviar arquivos por AJAX";

			// ================================================================
			// TIPO RADIO ou CHECKBOX
			// ================================================================
			if(tipo  == "RADIO" || tipo == "CHECKBOX" ){

				if($(this).attr('checked'))
                    valor = 1;
                else
                    valor = 0;

                variaveis += encodeURIComponent($(this).attr('name')) + "=" + encodeURIComponent(valor) + "&";

			// ================================================================
			// DEMAIS TIPOS
			// ================================================================
			}else{

				if (tag == "SELECT"){
					// ====================================
					// SELECT MULTIPLE
					// ====================================
					if ($(this).is('[multiple]')){
						for(var i = 0; i < this.length ; i++){
							if ($(this).attr('tudo')){
								if ($(this[i]).attr('value'))
									variaveis += encodeURIComponent($(this).attr('name')) + "[]=" + encodeURIComponent($(this[i]).attr('value')) + "&";
							}else{
								if ($(this[i]).attr('selected'))
									if ($(this[i]).attr('value'))
										variaveis += encodeURIComponent($(this).attr('name')) + "[]=" + encodeURIComponent($(this[i]).attr('value')) + "&";
							}
						}
					// ====================================
					// SELECT NORMAL
					// ====================================
					}else{
						variaveis += encodeURIComponent($(this).attr('name')) + "=" + encodeURIComponent(valor) + "&";
					}
				}else{

					// ====================================
					// OUTROS TEXT AREA
					// ====================================
					if (tag == "TEXTAREA" || tipo != 'UNDEFINED') //(outros tipos, como TEXT, HIDDEN)
						variaveis += encodeURIComponent($(this).attr('name')) + "=" + encodeURIComponent(valor) + "&";
				}

			}

        	}

	});

	// ====================================
	// ENVIA DADOS POR AJAX
	// ====================================

	//alert("var=" + variaveis);

	//alert("method:"+ method + "\nurl:" + action + "\ndata:" + variaveis + "\nsuccess:" + function_return	+ "\nerror:" + WXfa_erro);

	$.ajaxSetup({
		async: true,
		cache: false
	});

	$.ajax({
		type: method,
		url: action,
		data: variaveis,
		success: function_return,
		error: WXfa_erro
	});

	if (debug) alert("Finalizado");
	// Sempre deve retornar falso
	return false;

	// ====================================
	// CALLBACK -> ERRO
	// ====================================
	function WXfa_erro(XMLHttpRequest, textStatus, errorThrown){

		// Gerenciador de ERRO

		if (XMLHttpRequest.status == 404)
			//throw "ERRO DE CONEXÃO COM O SERVIDOR AJAX: Página \"" + action + "\" não encontrada";
			alert("ERRO DE CONEXÃO COM O SERVIDOR AJAX: Página \"" + action + "\" não encontrada");
		else
			//throw "ERRO DE CONEXÃO COM O SERVIDOR AJAX: " + XMLHttpRequest.status;
			alert ("ERRO DE CONEXÃO COM O SERVIDOR AJAX: " + XMLHttpRequest.status);

		return false;

	}
}



// ===================================================
// CALLBACK -> SUCESSO
// ===================================================
function responseForm(dados, status, debug){

    var debug = debug;
	var x_erro = false;
	var alerta = false;

	if (debug) alert("dados: '" + dados + "'\nstatus: " + status);


    // TODO: criar funcao disso já que é usado em varios lugares
	// -----------------------------------
	// Obtem dados do servidor
	// -----------------------------------
	if (!dados){
		alert("Nenhuma resposta obtida do servidor");
		return false;
	}
    // -----------------------------------
	// Verifica Tipo de dado vindo do servidor é XML
	// -----------------------------------
    // FIXME: remover de todo o site, é diferente para o Chrome e para o safari [object XMLDocument]
//  if (typeof(dados) == 'object' && dados != "[object XMLDocument]"){
//        alert("Retornado um objeto Desconhecido:" + dados);
//        return false;
//    }else
    if (typeof(dados) != 'object' && dados){
        alert(dados);
        return false;
    }
	// ----------------------------------
	// ERRO GERAL
	// ----------------------------------
    if ($(dados).find("error").text()){

        var errorMsg = $(dados).find("errorMsg").text();
        errorMsg += "\n"+$(dados).find("errorFileName").text();
        errorMsg += "\n"+$(dados).find("errorNum").text();

        alert(errorMsg);
        return false;
    }

	// ----------------------------------
	// ERRO DE CAMPO
	// ----------------------------------

    $(dados).find("campo").each(function(){

        campoName = $(this).find("id").text();
		erro = $(this).find("erro").text();
		erroDesc = $(this).find("msg").text();

		campo = $("[name='" + campoName + "']");

		if (erro){
            // Aplica foco apenas na primeira ocorrencia
            if (!x_erro)
                campo.focus();

            x_erro = true;
        }

		// -----------------------------------
		// Imprimir MSGBOX
		// -----------------------------------
		if (campo.attr('msgbox')){
			var msgBox = $('#'+campo.attr('msgbox')).find("[dono=formajax]");

			msgBox.each(function(){
				$(this).remove();
			});

			if (erro)
				$('#'+campo.attr('msgbox')).append('<div dono="formajax">' + erroDesc + '</p>');

		}

		// -----------------------------------
		// Alert
		// -----------------------------------
		if (alerta && erro){
			alert(erroDesc);
		}
		// -----------------------------------
		// Aplica Classe
		// -----------------------------------

        if(erro){
            $('#form-field-'+campoName).attr('classs', '1');
            $('#form-field-'+campoName).attr('class', 'wxform-field-invalido');
        }else{
            $('#form-field-'+campoName).attr('classs', '0');
            $('#form-field-'+campoName).attr('class', 'wxform-field-valido');
        }

    });

	// Verifica erro
	return !x_erro;

}
// ======================================================================================================================
//                   				VALIDACAO
// ======================================================================================================================
// ==============================================
// VALIDA CAMPO
// ==============================================
var tmpvalidateThisForm; // Problema do setTimeout que só enxerga variavel global
function validateThisForm(f_obj){

	tmpvalidateThisForm = f_obj;
	setTimeout('validateField(tmpvalidateThisForm)',100);

}
// ======================================================================
// VALIDA CAMPO
// ======================================================================
function validateForm(f_obj){

	var alerta = false;
	var erro = false;
	var erroDescText = '';
    var focusSet = false;

	// Procura todos os elementos validaveis
	$('#' + f_obj.id + ' [on=1][val=1]').each(function(){

		r_erro = validateField(this);

		if (r_erro[0]){
			erro = true;
            // Seta Focus apenas para o primeiro elemento com erro
            if(!focusSet){
                this.focus();
                focusSet = true;
            }
        }

		erroDesc = r_erro[1];
		for(var i = 0 ; i < erroDesc.length ; i++)
			erroDescText += erroDesc[i] + "\n";

	});

	// -----------------------------------
	// Alert
	// -----------------------------------
	if (alerta && erro){
		alert(erroDescText);
	}


	return !erro;

}

// ======================================================================
// VALIDA CAMPO ESPECIFICO
// 	obs: Se criar uma div com o nome + pai, será alterada pelo sistema tb
//
// 	Pode ser criado de fora
//
// 	<div id='id<?php echo $this->name?>pai'>
// 		<INPUT onkeypress="javascript:validateThisForm(this)" class="wxform-valido" msgbox="msg-<?php echo $this->name?>" val="1" requerido="1" id="id<?php echo $this->name?>" name="<?php echo $this->name?>" type="<?php echo $this->tipo?>" value="<?php echo $this->value?>">
// 	</div>
// ======================================================================
function validateField(f_obj){

	// Converte para o formato jquery
	var obj = $(f_obj);
	var alerta = false;


	// Verifica se o campo deve ser validado
	if (obj.attr('val') == "1"){

 		// -----------------------------------
 		// Executa filtros de validação
 		// -----------------------------------
 		var r_erro = validateFormFilter(f_obj);
		// -----------------------------------
		// Respostas
		// -----------------------------------
		erro = r_erro[0];
		erroDesc = r_erro[1];

		// -----------------------------------
		// Imprimir MSGBOX
		// -----------------------------------
		if (obj.attr('msgbox')){

			var msgBox = $('#' + obj.attr('msgbox')).find("[dono=validacampocliente]");

			msgBox.each(function(){
				$(this).remove();
			});

			for(var i = 0 ; i < erroDesc.length ; i++){
				$('#'+ obj.attr('msgbox')).append('<div dono="validacampocliente">' + erroDesc[i] + '</p>');
            }

		}
		// -----------------------------------
		// Alert
		// -----------------------------------
		if (alerta && erro){
			var erroDescText = '';
			for(var i = 0 ; i < erroDesc.length ; i++)
				erroDescText += $(f_obj).attr('name') + ": " +  erroDesc[i] + "\n";

			alert(erroDescText);
		}
		// -----------------------------------
		// Aplica Classe (VERIFICA SE TEM ELEMENTO COMO FILHO)
		// -----------------------------------

        if(erro){
            if (obj.parents('.wxform-field-valido').eq(0).attr('classs') != 1){
                obj.parents('.wxform-field-valido').eq(0).attr('class', 'wxform-field-invalido')
            }
        }else{
            if (obj.parents('.wxform-field-invalido').eq(0).attr('classs') != 1){
                obj.parents('.wxform-field-invalido').eq(0).attr('class', 'wxform-field-valido');
            }
        }
 		// -----------------------------------
 		// Retorna Função
 		// -----------------------------------
 		return Array(erro, erroDesc);

 	}else{

 		return Array(false, Array());
 	}
}


// ===========================================
//  Executa Filtro de Validacao (MENSAGENS EM lang_XX.js)
// ===========================================
function validateFormFilter(f_obj){

	// Converte para o formato jquery
	var obj = $(f_obj);

	// Valor a ser validado
	var string = (obj.attr('value'))? new String(obj.attr('value')) : '';
	// Retorna erro
	var erro = false;
	var erroDesc = Array();

	// ---------------------------------------------
	// REQUERIDO
	// ---------------------------------------------
	if ((obj.attr('requerido') == "1") && (string.length == 0)){
		erro = true;
		erroDesc.push(msgForm('requerido'));
	}

	// ---------------------------------------------
	// NÃO REQUERIDO
	// ---------------------------------------------
	if (string.length > 0){
		// ---------------------------------------------
		// EXPRESSÂO REGULAR
		// ---------------------------------------------
		if (obj.attr('regexp')){
			r_erro = validateFormFilterRegexp(obj.attr('regexp'), string);
			erro = !r_erro[0];
			if (!r_erro[0]){
				erroDesc.push(r_erro[1]);
			}
		}

		// ---------------------------------------------
		// TAMANHO MAXIMO
		// ---------------------------------------------
		if (obj.attr('tammax')){
			var tamMax = parseInt(removeZero(obj.attr('tammax')));
			if (string.length > tamMax){
				erro = true;
				erroDesc.push(msgForm("tammax", Array(obj.attr('name'), tamMax)));
			}
		}
		// ---------------------------------------------
		// TAMANHO MINIMO
		// ---------------------------------------------
		if (obj.attr('tammin')){
			var tamMin = parseInt(removeZero(obj.attr('tammin')));
			if (string.length < tamMin){
				erro = true;
				erroDesc.push(msgForm("tammin", Array(obj.attr('name'), tamMin)));
			}
		}
		// ---------------------------------------------
		// VALOR MAXIMO
		// ---------------------------------------------
		if (obj.attr('valmax')){
			var valMax = parseInt(removeZero(obj.attr('valmax')));
			if (parseInt(removeZero(string)) > valMax){
				erro = true;
				erroDesc.push(msgForm("valmax", Array(obj.attr('name'), valMax, parseInt(removeZero(string)))));
			}
		}
		// ---------------------------------------------
		// TAMANHO MINIMO
		// ---------------------------------------------
		if (obj.attr('valmin')){
			var valMin = parseInt(removeZero(obj.attr('valmin')));
			if (parseInt(removeZero(string)) < valMin){
				erro = true;
				erroDesc.push(msgForm("valmin", Array(obj.attr('name'), valMin, parseInt(removeZero(string)))));
			}
		}
		// ---------------------------------------------
		// IDENTICO (para senha)
		// ---------------------------------------------
		if (obj.attr('identico')){
			var stringElem = $('#'+obj.attr('identico')).attr('value');
			if (string != stringElem){
				erro = true;
                // Mensagem é tratada na classe
				erroDesc.push('');

			}
		}
		// ---------------------------------------------
		// Diferente de VARIAVEL
		// ---------------------------------------------
		if (obj.attr('diferente')){
			var stringElem = obj.attr('diferente');
			if (string == stringElem){
				erro = true;
				erroDesc.push(msgForm("diferente", Array(obj.attr('name'), stringElem)));
			}
		}
	}

	return Array(erro, erroDesc);
}


// ======================================================
// Expressões Regulares Pré Formatadas (MENSAGENS EM lang_XX.js)
// ======================================================
function validateFormFilterRegexp(regx, value){

	var retorno = new Array();

	switch (regx.toUpperCase()){
		case "EMAIL":
		case "MAIL":
			retorno[0] = (/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/).test(value);
			retorno[1] = msgForm('email');
			return (retorno);

		case "TEL":
        case "TELEFONE":
			retorno[0] = (/^1?[\- ]?\(?\d{2}\)?[\- ]?\d{4}[\- ]?\d{4}$/).test(value);
			retorno[1] = msgForm('telefone');
			return (retorno);

		case "ZIP":
			retorno[0] = (/^\d{5}$/).test(value);
			retorno[1] = msgForm('zip');
			return (retorno);

		case "MONEY":
		case "MONETARIO":
			retorno[0] = (/^\d+([\.]\d\d)?$/).test(value);
			retorno[1] = msgForm('monetario');
			return (retorno);

		case "MONEYBR":
		case "MONETARIOBR":
			retorno[0] = (/^\d+([\,]\d\d)?$/).test(value);
			retorno[1] = msgForm('monetariobr');
			return (retorno);


		case "NUMERO":
		case "VALOR":
			retorno[0] = !isNaN(value);
			retorno[1] = msgForm('numero');
			return (retorno);

		case "DATA":
		case "DATE":
			retorno[0] = (/^((0?[1-9]|[12]\d)\/(0?[1-9]|1[0-2])|30\/(0?[13-9]|1[0-2])|31\/(0?[13578]|1[02]))\/(19|20)?\d{2}$/).test(value);
			retorno[1] = msgForm('data');
			return (retorno);
			break;

		case "DATAHORA":
		case "HORADATA":
		case "DATETIME":
		case "TIMEDATE":
			retorno[0] = (/^((((([0-1]?\d)|(2[0-8]))\/((0?\d)|(1[0-2])))|(29\/((0?[1,3-9])|(1[0-2])))|(30\/((0?[1,3-9])|(1[0-2])))|(31\/((0?[13578])|(1[0-2]))))\/((19\d{2})|([2-9]\d{3}))|(29\/0?2\/(((([2468][048])|([3579][26]))00)|(((19)|([2-9]\d))(([2468]0)|([02468][48])|([13579][26]))))))\s(([01]?\d)|(2[0-3]))(:[0-5]?\d){2}$/).test(value);
			retorno[1] = msgForm('datahora');
			return (retorno);
			break;

		default:
            throw('erroJS:' + regx)
			retorno[0] = value;
			retorno[1] = msgForm('campoincorreto');
			return (retorno);
   break;
	};
};
// ==============================================
// Remove Zeros
// ==============================================
function removeZero(sStr){
   var i;
   for(i = 0; i < sStr.length ; i++)
      if(sStr.charAt(i)!='0')
         return sStr.substring(i);
   return sStr;
};

// ======================================================================================================================
//                   				MASCARA
// ======================================================================================================================
//
// ==============================================
// MASCARA NESTE CAMPO
// ==============================================
var tmpObjMaskForm; // Problema do setTimeout que só enxerga variavel global
var tmpMaskMaskForm;
function maskForm(f_obj, mask){

	if (mask){
		tmpObjMaskForm = f_obj;
		tmpMaskMaskForm = mask.toUpperCase()
		setTimeout('maskForm2()',1);
	}

}
function maskForm2(){

	tmpObjMaskForm.value = execMask(tmpObjMaskForm.value, tmpMaskMaskForm);

}

// =============================================
// MASCARAS
// =============================================
function execMask(value, mascara){

	switch (mascara){

		case "DIGITONUMERICO": 	// Apenas caracteres numerico
			value=value.replace(/\D/g,"");                 //Remove tudo o que não é dígito
			return value;

		case "INTEIRO":
		case "NUMERO":		// Apenas valores
			value=value.replace(/\D/g,"");                 //Remove tudo o que não é dígito
			value = (value * 1);
			return value;


		case "MONETARIO":
		case "MONEY":
			value=value.replace(/[^0-9.,-]/g,"");     //Remove tudo o que não é dígito ou virgula
			value=value.replace(/[.]/g,",");
			value=value.replace(/([,]..)(\d)/,"$1")       //Coloca um ponto entre o terceiro e o quarto dígitos
			return value;

		case "TELEFONE":
			value=value.replace(/\D/g,"");                 //Remove tudo o que não é dígito

			x=value.replace(/^(0800|0300)(\d{2})(\d{0,4})/,"$1 $2 $3");    // (55 41) 1234-5678. 12 dígitos.
			if (x != value) return x;

			x=value.replace(/^(0800|0300)(\d{0,2})/,"$1 $2");    // (55 41) 1234-5678. 12 dígitos.
			if (x != value) return x;

			x=value.replace(/^(08|03)0{0,3}/,"xyz");    // (55 41) 1234-5678. 12 dígitos.
			if (x == "xyz") return value;

			x=value.replace(/^(\d{2})(\d{2})(\d{4})(\d{4})/,"($1)($2) $3-$4");    // (55 41) 1234-5678. 12 dígitos.
			if (x != value) return x;

			x=value.replace(/^(\d{2})(\d{4})(\d)/,"($1) $2-$3");    // (41) 1234-5. Entre 7 dígitos e 10 dígitos.
			if (x != value) return x;

			x=value.replace(/^(\d{2})(\d{0,4})/,"($1) $2");    // (41) 1234. Menos que 6 dígitos.
			if (x != value) return x;

			x=value.replace(/^(\d{2})$/,"($1) ");    // (41). 2 dígitos.
			if (x != value) return x;

			return value;

		case "CPF":
			value=value.replace(/\D/g,"")                    //Remove tudo o que não é dígito
			value=value.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
			value=value.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)
			value=value.replace(/(\d{3})(\d{1,2})$/,"$1-$2") //Coloca um hífen entre o terceiro e o quarto dígitos
			return value;

		case "CEP":
            value=value.replace(/\D/g,"")                    //Remove tudo o que não é dígito
			value=value.replace(/^(\d{5})(\d)/,"$1-$2") //Esse é tão fácil que não merece explicações
			return  value
		case "CNPJ":
			value=value.replace(/\D/g,"")                           //Remove tudo o que não é dígito
			value=value.replace(/^(\d{2})(\d)/,"$1.$2")             //Coloca ponto entre o segundo e o terceiro dígitos
			value=value.replace(/^(\d{2,4})\.(\d{3})(\d)/,"$1.$2.$3") //Coloca ponto entre o quinto e o sexto dígitos
			value=value.replace(/\.(\d{3})(\d)/,".$1/$2")           //Coloca uma barra entre o oitavo e o nono dígitos
			value=value.replace(/(\d{4})(\d)/,"$1-$2")              //Coloca um hífen depois do bloco de quatro dígitos
			return  value
		case "SITE":
			//Esse sem comentarios para que você entenda sozinho ;-) perde cursor
			value=value.replace(/^http:\/\/?/,"")
			dominio=value
			caminho=""
			if(value.indexOf("/")>-1)
				dominio=value.split("/")[0]
				caminho=value.replace(/[^\/]*/,"")
			dominio=dominio.replace(/[^\w\.\+-:@]/g,"")
			caminho=caminho.replace(/[^\w\d\+-@:\?&=%\(\)\.]/g,"")
			caminho=caminho.replace(/([\?&])=/,"$1")
			if(caminho!="")dominio=dominio.replace(/\.+$/,"")
			value="http://"+dominio+caminho
			return value

		case "DATA":
			value=value.replace(/\D/g,"")                    	 			  //Remove tudo o que não é dígito
			value=value.replace(/^(\d{2})(\d)/,"$1/$2");					// Adiciona uma / entre o 2 e 3 digito
			value=value.replace(/^(.....)(.)/,"$1/$2");						// Adiciona uma / entre o 5 e 6 digito
			value=value.replace(/^([0][0]|[4-9]|[3][2-9])/, "");			// Substitui Dia se estiver errado
			value=value.replace(/^(...)([0][0]|[2-9]|[1][3-9])/, "$1");		// Sbustitui Mes se estiver errado
			return value

		case "DATAHORA":
			value=value.replace(/\D/g,"")                    	  			 //Remove tudo o que não é dígito
			value=value.replace(/^(\d{2})(\d)/,"$1/$2");					// Adiciona uma / entre o 2 e 3 digito
			value=value.replace(/^(.....)(.)/,"$1/$2");						// Adiciona uma / entre o 5 e 6 digito
			value=value.replace(/^(..........)(.)/,"$1 $2");				// Adiciona uma " " entre o 5 e 6 digito
			value=value.replace(/^(.............)(.)/,"$1:$2");
			value=value.replace(/^(................)(.)/,"$1:$2");
			value=value.replace(/^(...................)(.)/,"$1");
			value=value.replace(/^([0][0]|[4-9]|[3][2-9])/, "");			// Sbustitui Dia se estiver errado
			value=value.replace(/^(...)([0][0]|[2-9]|[1][3-9])/, "$1");		// Sbustitui Mes se estiver errado
			value=value.replace(/^(......)([0]|[3-9]|[1][0-8]|[2][1-9])/, "$1");		// Sbustitui Ano se estiver errado
			return value

		case "REAIS":
			value=value.replace(/[^0-9.,-]/g,"");     //Remove tudo o que não é dígito ou virgula
			value=value.replace(/[.]/g,",");
			return value;

		default:
			return value;
	}
}
// =============================================
// INTERFACE
// =============================================
function formInterfaceInt(form, field, fieldId, param, value){

        // ----------------------------------------------
        // Verificação
        // ----------------------------------------------
        if (!field)
            alert("field vazio");

        var functionName = "formInterface" + field;

        try {
            eval("var interfaceObj = new " + functionName + "();");
        } catch (exception) {
            var interfaceObj = new formInterfaceField();
        }

        interfaceObj.init(form, fieldId);

        functionName = "interfaceObj." + param + "(value);";

        eval(functionName);

}
function formInterfaceField(){

        // ----------------------------------------------
        // Contrutor
        // ----------------------------------------------

        this.field = null;
        this.div   = null;

        // ----------------------------------------------
        // INIT
        // ----------------------------------------------
        this.init = function(form, fieldId){

            this.field = $('#' + form + ' #form-field-' + fieldId + ' input');
            this.div = $('#' + form + ' #form-field-' + fieldId);

        }

        // ----------------------------------------------
        // Propriedades
        // ----------------------------------------------

        this.value = function(value){
            this.field.attr('value', value);
        }

        this.disable = function(){
            this.field.attr('disabled', 'disabled');
        }

        this.enable = function(){
            this.field.attr('disabled', '');
        }

        this.show = function(){
            this.div.show();
        }

        this.hide = function(){
            this.div.hide();
        }

        this.on = function(){
            this.field.attr('on', '1');
        }

        this.off = function(){
            this.field.attr('on', '0');
        }

        this.clear = function(){
            this.field.attr('value', '');
        }

        this.validate = function(){
            validateThisForm(this.field);
        }

        this.msg = function(value){
            msgBox = $('#' + this.field.attr('msgbox')).find("[dono=interface]");
            msgBox.each(function(){
                $(this).remove();
            });
            $('#' + this.field.attr('msgbox')).append('<div dono=\"interface\">' + value + '</p>');
        }

        this.appendMsg = function(value){
            $('#' + this.field.attr('msgbox')).append('<div dono=\"interface\">' + value + '</p>');
        }

        this.clearMsg = function(){
            msgBox = $('#' + this.field.attr('msgbox')).find("[dono=interface]");
            msgBox.each(function(){
                $(this).remove();
            });
        }

        this.focus = function(){
            this.field.focus();
        }


}

