/* **************************************************************
*                         --XJS--	                            *
* Desenvolvedora: Rhianna Cantarelli							*
* Versão: 1.0													*
* Data: 17.10.2007												*
* Email: r.rhianna@yahoo.com.br									*
************************************************************** */


/* **************************************************************
	-- FUNÇÕES GET ELEMENTS

Métodos utilizados para encontrar Elementos em XHTML
************************************************************** */
// Retorna Elemento Pelo seu ID
function id(idName) { return document.getElementById(idName); }
// Retorna Array de Todos os Elementos Com Mesmo Nome de Tag
function tag(tagName) { return document.getElementsByTagName(tagName); }


/* **************************************************************
Retorna um Array com todos os elementos da classe determinada.
Usando um segundo argumento (sendo este o nome de uma tag), 
retornará todos os elementos daquela tag que utilizem a classe procurada
************************************************************** */
function getElementsByClassName(className) {
	var tArgs = arguments.length;
	var allElem;
	if (tArgs == 1)	{ allElem = tag("*"); }
	else { allElem = tag(arguments[1]); }

	var arrReturn = new Array(); var i;	var j;
	for (i=0,j=0; i<allElem.length; i++) {
		var c = " " + allElem[i].className + " "; if (c.indexOf(" " + className + " ") != -1) { arrReturn[j++] = allElem[i]; } 
	} 
	return arrReturn; 
}


/* **************************************************************
Retorna um Array com todos os elementos da tag determinada 
dentro da ID passada
************************************************************** */
function getTagsChildOfID(tagName, idName) {
	obj = id(idName);
	return obj.getElementsByTagName(tagName);
}


/* **************************************************************
Recebe o nome de uma tag e de uma classe que compreende estes elementos
Conforme o 'index' retornará:
length = Quantidade de coleções com a classe determinada;
isNam  = Retorna as tags do objeto da coleção de indice igual ao passado
************************************************************** */
function getTagsChildOfClass(tagName, className, index) {
	allClass = getElementsByClassName(className);
	var ret = '';
	if(index == 'length') { ret = allClass.length; }
	else { ret = allClass[index].getElementsByTagName(tagName); }
	return ret;
}












/* **************************************************************
	-- CONTROLE DE ATRIBUTOS DE OBJETOS

Dado ID, nome do Atributo e seu Novo Valor, Aplica-o no Objeto
************************************************************** */
function setAttributeToID(idName, attrib, value) {
	var exec = 'id("' + idName + '").style.' + attrib + '="' + value + '";';
	eval(exec);
}


/* **************************************************************
Dado TagName, nome do Atributo e seu Novo Valor, aplica-o em todas
as tags daquele tipo
************************************************************** */
function setAttributeToTags(tagName, attrib, value) {
	allTags = tag(tagName);
	var exec;
	for(i=0; i<allTags.length; i++) {
		exec = 'allTags[i].style.' + attrib + '="' + value + '";';
		eval(exec);
} }


/* **************************************************************
Dado Nome da Classe, do Atributo e seu Novo Valor, Aplica-o em todos
os Elementos que possuem aquela classe
************************************************************** */
function setAttributeToClass(className, attrib, value) {
	allClass = getElementsByClassName(className);
	var exec;
	for(i=0; i<allClass.length; i++) {
		exec = 'allClass[i].style.' + attrib + '="' + value + '";';
		eval(exec);
} }


/* **************************************************************
Dado array com Objetos, Nome do Atributo e seu Novo Valor, Aplica-o
em todos os objetos passados.
************************************************************** */
function setAttibuteToObjs(allObj, attrib, value) {
	var exec;
	for(i=0; i<allObj.length; i++) {
		exec = 'allObj[' + i + '].style.' + attrib + '=' + value + ';';
		eval(exec);
} }











/* **************************************************************
	-- FUNÇÕES VARIADAS

Identifica se há ou não o Player do Flash Instalado 
************************************************************** */
function isFlashPlayer() {
	var flashObj; 
	var ret;
	//fpversion = flashObj.GetVariable("$version");
	try { flashObj = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"); ret = true; }
	catch(err) { 
		ret = false;
		if (navigator.plugins != null && navigator.plugins.length > 0) { 
			//flashObj.description;
			flashObj = navigator.plugins["Shockwave Flash"]; ret = true; 
		} else { ret = false; }
	} 
	return ret; 
}


/* **************************************************************
Recebe o nome do arquivo .js que deve ser importado dinamicamente
************************************************************** */
function insertScript(srcScript) {
    var objScript = document.createElement('script');
    objScript.type='text/javascript';
    objScript.src = srcScript;
	document.body.appendChild(objScript);
}


/* **************************************************************
Retorna um numero aleatório entre o menor e o maior definidos
************************************************************** */
function nRandom(numMenor, numMaior){
    var numPossibilidades = numMaior - numMenor;
    num = Math.random() * numPossibilidades;
    num = Math.floor(num);
    return parseInt(numMenor) + num;
}


















/* **************************************************************
Retorna na Variavel 'xjsLastKeyDown' o KeyCode da ultima Tecla 
Pressionada, para haver precisão deve ser adicionado ao evento
document.onkeydown
************************************************************** */
function checkKeycode(e) {
	var keycode;
	if (window.event) { keycode = window.event.keyCode; }
	else if (e) { keycode = e.which; }
	return keycode;
}



/* **************************************************************
Identifica os Links que apontam para sites externos e aplica nos mesmos
a propriedade "target" para que abram em outra janela.
Para indicar que um link aponta para fora use "rel=ex" na tag "a"
************************************************************** */
function setTargetBlank() {
	if(document.getElementsByTagName) { var anchors = tag('a');
		for(var i=0; i<anchors.length; i++) { var anchor = anchors[i];
			if(anchor.getAttribute("href") && anchor.getAttribute('rel')==linkExterno) { anchor.target = '_blank'; }
} } }



/* **************************************************************
Realiza a troca de imagens com os sufixos determinados
************************************************************** */
function changeImg(obj) {
	var ie_var = "srcElement"; // Para Pegar Objeto no MSIE sem ter um parametro this
	if (obj[ie_var]) {	// Para MSIE
		getSRC = obj[ie_var]['src']; 
		if (getSRC.indexOf(sufixNoHover) != -1)	{ obj[ie_var]['src'] = getSRC.replace(sufixNoHover, sufixHover); }
		else if (getSRC.indexOf(sufixHover) != -1) { obj[ie_var]['src'] = getSRC.replace(sufixHover, sufixNoHover); }
	}
	else { // Para Outros Browsers
		getSRC = obj.src; 
		if (getSRC.indexOf(sufixNoHover) != -1)	{ obj.src = getSRC.replace(sufixNoHover, sufixHover); }
		else if (getSRC.indexOf(sufixHover) != -1) { obj.src = getSRC.replace(sufixHover, sufixNoHover); }
} }



/* **************************************************************
Identifica imagens que sejam cambeaveis a partir dos sufixos definidos
e aplica os eventos mouseover para efetuar a troca.
************************************************************** */
function setLinkHover() {
	getIMGs = tag('img');
	for(var i=0; i<getIMGs.length; i++)	{
		getSRC = getIMGs[i].src;
		if (getSRC.indexOf(sufixNoHover) != -1) {
			if (document.attachEvent) { // Adiciona Evento para MSIE
				getIMGs[i].attachEvent('onmouseover', changeImg);
				getIMGs[i].attachEvent('onmouseout', changeImg);
			}
			else { // Adiciona Evento para Outros Browsers
				getIMGs[i].setAttribute('onmouseover', 'changeImg(this)');
				getIMGs[i].setAttribute('onmouseout', 'changeImg(this)');
} } } }






/* **************************************************************
Adiciona um evento 'evType' aos objetos passados além de setar 
um atributo 'eventname' para estes mesmos objetos, de forma que no IE
seja mais facil encontrar o objeto que disparou tal evento.
************************************************************** */
function setEvent(obj, evType, evName){
	// Adiciona Evento para MSIE
	if (document.attachEvent) {	
		obj.attachEvent('on'+ evType, eval(evName)); 
		obj.eventname = evName;
	}
	else { nameEv = evName + '(this)'; obj.setAttribute('on'+ evType, nameEv); }
}



/* **************************************************************
Usado para IE
Retorna o objeto que disparou o evento em questão.
Rastreia a partir do Node que disparou o evento até encontrar
um node que contenha a propriedade 'eventname' igual ao nome
do evento que este chamou.
O rastreiamento é feito a partir do node mais interno para o mais
externo e o seu uso é feito da seguinte forma:

function yourFunction(obj) {
	if(document.attachEvent) { obj = getObjEvent(obj, 'openCloseMenu');	}
	do something...
}
************************************************************** */
function getObjEvent(obj, evName) {
	// Rastreia o Objeto que Disparou o Evento (IE)
	if (obj['srcElement']) { 
		isThis = false;
		count = 0;
		par = '';
		obj = window.event.srcElement;
		while(isThis != true)
		{
			par += ".parentNode";
			if(obj.eventname == undefined) { 
				nNivel = "window.event.srcElement" + par;
				obj = eval(nNivel);
			}
			else { if(obj.eventname == evName) { isThis = true; } }
			obj = eval(obj);
			count++;
			// Quebra Looping caso extenda-se demais
			if(count == 100) { isThis = true; }
		}
	}
	return obj;
}



/* **************************************************************
Executa ação de um botão aspNet ao pressionar enter no campo com
esta ação;
************************************************************** */
function executeOnEnter(idName){
    if(xjsLastKeyDown == 13) {
        buttonAction = id(idName).href;
        nameAction = buttonAction.replace("javascript:__doPostBack('", "");
        indexEnd = nameAction.indexOf("'");
        nameAction = nameAction.substring(0, indexEnd);
        
        // Realiza a Operação do Botão Simulado
        __doPostBack(nameAction,'');
    } 
}



/* **************************************************************
Deve ser utilizado como: 
	onfocus="setMonitoreEnter(false);" ou onblur="setMonitoreEnter(true);"
Nos campos onde permite-se que o botão enter seja usado para outro fim
que não seja o disparo de um comando de servidor.
************************************************************** */
function setMonitoreEnter(boolean) { MonitoreEnter = boolean; }




















/* **************************************************************
Usando 1 argumento (id) retorna o valor do campo.
Usando 2 argumentos (id) e (novoValor), atribui novo valor ao campo
************************************************************** */
function field(idName) {
	tArgs = arguments.length;
	if (tArgs == 1) { get = id(idName).value; return get; }
	else if (tArgs == 2) { id(idName).value = arguments[1]; }
}


/* **************************************************************
Verifica se o campo foi preenchido
erroTipo = 1;
************************************************************** */
function isEmpty(idName){ if (field(idName) == ""){ return 1; }	return 0; }


/* **************************************************************
Verifica se a String possui o numero exato de caracteres
erroTipo = 2;
************************************************************** */
function isFindNChar(string, num){ if (string.length != num){ return 2; } return 0; }



/* **************************************************************
Verifica se a String possui o numero minimo de caracteres
erroTipo = 2;
************************************************************** */
function isMiniNChar(string, num){ if (string.length < num){ return 2; } return 0; }



/* **************************************************************
Acessa o Select Indicado podendo verificar as propriedades escolhidas
O argumento toGet controla o funcionamento sendo:
'index'  : retorna o número do Option selecionado
'text' : retorna a string interna do Option
'value'  : retorna o valor da Opção
************************************************************** */
function selec(idName, toGet) {
	index = id(idName).selectedIndex;
	thisOption = getTagsChildOfID(toGet, idName)[index];

	if (toGet == 'index') { get = index; }
	else if (toGet == 'text') { get = thisOption.text; }
	else if (toGet == 'value') { get = id(idName).value; }
	return get;
}



/* **************************************************************
Verifica se alguma Opção de um Select foi selecionada
erroTipo = 3;
************************************************************** */
function isSelected(idName){ index = selec(idName, 'index'); if (index == 0){ return 3; } return 0; }



/* **************************************************************
Retorna um objeto Array com os indices dos inputs* de radio
que pertencem ao mesmo grupo(name).
* o indice é referente à coleção de todos os inputs
************************************************************** */
function radioButtons(nameRadio){
	allInputs = tag('input');
	var radio = new Array();
	var ind = 0;
	for (i=0; i<allInputs.length; i++) {
		if(allInputs[i].getAttribute('type') == 'radio' && allInputs[i].getAttribute('name') == nameRadio)
		{ radio[ind] = i; ind++; }
	}
	return radio;
}



/* **************************************************************
Verifica se algum RadioButtom da coleção está selecionado
************************************************************** */
function isRadioSelect(nameRadio){
	allInputs = tag('input');
	radioC = radioButtons(nameRadio);
	is = 0;
	for(i=0; i<radioC.length; i++){
		if (allInputs[radioC[i]].checked == true){ is = 1; }
	}
	if(is == 0){ return 3; }
	return 0;
}



/* **************************************************************
Seleciona radioButtom com determinado Valor ou desmarca todos
se valor for definido vazio
************************************************************** */
function radioSelect(nameRadio, value){
	allInputs = tag('input');
	radioC = radioButtons(nameRadio);
	for (i=0; i<radioC.length; i++){
		if(value == ''){ allInputs[radioC[i]].checked = false; }
		else if(allInputs[radioC[i]].getAttribute('value') == value){ allInputs[radioC[i]].checked = true; }
} }




/* **************************************************************
Permite Entrada Apenas de Números [deve ser adicionado no evento "onkeyup"]
************************************************************** */
function onlyNum(obj){
	val = obj.value;
	len = val.length;
	lastNum = val.substring(len-1, len);
	if (xjsLastKeyDown >= '48' && xjsLastKeyDown <= '57'){ return true; } // Numeros do Teclado
	else if (xjsLastKeyDown >= '96' && xjsLastKeyDown <= '105') { return true; } // Teclado Numérico
	else if (xjsLastKeyDown >= '37' && xjsLastKeyDown <= '40') { return true; }// Setas
	else if (xjsLastKeyDown == '46') { return true; } // Delete
	else if (xjsLastKeyDown == '35' || xjsLastKeyDown == '36') { return true; } // End e Home
	else if (xjsLastKeyDown == '18') { return true; } // Shift
	else if (xjsLastKeyDown == '8') { return true; } // BackSpace
	else { obj.value = val.substring(0, len-1); }
}





/* **************************************************************
Formata DATA Enquando a mesma é Digitada [deve ser adicionado no evento "onkeyup"]
Use em Conjunto com o "onlyNum()" e a propriedade maxlength="10"
************************************************************** */
function maskDATA(obj){
	data = obj.value;
	len = data.length;
	if(xjsLastKeyDown != '8'){
		if (len == 2){ data = data + dataSpace;	}
		else if (len == 5){ data = data + dataSpace; }
		obj.value = data;
	}
}



/* **************************************************************
Verifica data para o formato "dd/mm/aaaa"
---> isNaN(num) Verifica se é Numero
************************************************************** */
function isData(idName) {
	data = field(idName);

	if (isEmpty(idName) != 0) { return 1; }
	if (isFindNChar(data, 10) != 0) { return 2; }

	getDia = data.substring(0, 2);
	getMes = data.substring(3, 5);
	getAno = data.substring(6, 10);

	if (isNaN(getDia)) return 2;
	if (isNaN(getMes)) return 2;
	if (isNaN(getAno)) return 2;

	if (getMes < 1 || getMes > 12) return 2;

	// Seta dia máximo para cada mês
	if (getMes == 2 || getMes == 4 || getMes == 6 || getMes == 9 || getMes == 11) {
		if (getMes == 2) { // Identifica anos bissexto 
			sobra = 2080 - getAno;
			resto = sobra % 4;
			if (resto == 0) { maxDay = 29; }
			else { maxDay = 28; }
		}
		else {maxDay = 30;}
	}
	else {maxDay = 31;}

	if (getDia < 1 || getDia > maxDay) return 2;
    if (data.indexOf(dataSpace, 3) == -1 || data.indexOf(dataSpace, 5) == -1) return 2;

	return 0;
}





/* **************************************************************
Formata CPF [111.222.333-XX] durante sua digitação 
[deve ser adicionado no evento "onkeyup" no input]
Use em Conjunto com o "onlyNum()" e a propriedade maxlength="14"
************************************************************** */
function maskCPF(obj){
	cpf = obj.value;
	len = cpf.length;

	if(xjsLastKeyDown != '8'){
		if (len == 3){ cpf = cpf + '.';	}
		else if (len == 7){ cpf = cpf + '.'; }
		else if (len == 11){ cpf = cpf + '-'; }
		obj.value = cpf;
	}
}





/* **************************************************************
Valida o CPF
************************************************************** */
function isCPF(idName) {
	cpf = id(idName).value;

	if (isEmpty(idName) != 0) { return 1 };
	if (isFindNChar(cpf, 14) != 0) { return 2 };

	if (cpf.length == 14) {
		// Limpa pontos e Hifen
		n = cpf.substring(0, 3);
		n += cpf.substring(4, 7);
		n += cpf.substring(8, 11);
		n += cpf.substring(12, 14);
		cpf = n;
		// Verifica se só sobraram Numeros
		if (isNaN(cpf)) return 2;

		// Numeros Inválidos
		valid = false;
		for(i=0; i<10; i++){
			anter = cpf.charAt(i);
			atual = cpf.charAt(i+1);
			if (anter != atual) { valid = true; }
		}
		if (valid == false) { return 2; }

		var a = [];
		var b = new Number;
		var c = 11;

		for (i=0; i<11; i++){ a[i] = cpf.charAt(i); if (i < 9) { b += (a[i] * --c); } }
		if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
		b = 0;
		c = 11;

		for (y=0; y<10; y++) { b += (a[y] * c--); }
		if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }

		if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){ return 2; }

		return 0; 
	}
}





/* **************************************************************
Formata CNPJ [11.222.333/0001-XX] durante sua digitação 
[deve ser adicionado no evento "onkeyup" no input]
Use em Conjunto com o "onlyNum()" e a propriedade maxlength="18"
************************************************************** */
function maskCNPJ(obj){
	cnpj = obj.value;
	len = cnpj.length;

	if(xjsLastKeyDown != '8'){
		if (len == 2){ cnpj = cnpj + '.'; }
		else if (len == 6){ cnpj = cnpj + '.'; }
		else if (len == 10){ cnpj = cnpj + '/'; }
		else if (len == 15){ cnpj = cnpj + '-'; }
		obj.value = cnpj;
	}
}





/* **************************************************************
Valida o CNPJ
************************************************************** */
function isCNPJ(idName) {
	cnpj = id(idName).value;

	if (isEmpty(idName) != 0) { return 1 };
	if (isFindNChar(cnpj, 18) != 0) { return 2 };


	// Limpa pontos barra e Hifen
	n = cnpj.substring(0, 2);
	n += cnpj.substring(3, 6);
	n += cnpj.substring(7, 10);
	n += cnpj.substring(11, 15);
	n += cnpj.substring(16, 18);
	cnpj = n;
	// Verifica se só sobraram Numeros
	if (isNaN(cnpj)) return 2;

	var a = [];
	var b = new Number;
	var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
	for (i=0; i<12; i++){ a[i] = cnpj.charAt(i); b += a[i] * c[i+1]; }
	if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }

	b = 0;
	for (y=0; y<13; y++) { b += (a[y] * c[y]); }
	if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }

	if ((cnpj.charAt(12) != a[12]) || (cnpj.charAt(13) != a[13])){ return 2; }

	
	return 0;
}





/* **************************************************************
Verifica se o mail é válido
************************************************************** */
function isEmail(idName){
	if (isEmpty(idName) != 0) { return 1 };

	mail = field(idName);
	
	indexArroba = 0;
	indexPonto = 0;

	// Encontra a Extenção do nome do Usuário
	for (i=0; i<mail.length; i++){ if (mail.charAt(i) == '@') { indexArroba = i; break; } }

	// Encontra a Extenção do nome do Dominio
	for (i=indexArroba; i<mail.length; i++){ if (mail.charAt(i) == '.') { indexPonto = i; break; } }

	if (indexPonto == 0 || indexArroba <= 1) return 2;
	if (indexPonto == (indexArroba + 1)) return 2;
	if ((indexPonto + 1) == mail.length) return 2;
	return 0;
}





/* **************************************************************
Verifica se a String é um link http correto
Parametro Minimo é: http://dominio.com
************************************************************** */
function isLink(idName){
    if (isEmpty(idName) != 0) { return 1 };
    
    link = field(idName);
    
    invalidChar = "\"'!@#$%&*:;{}[]<>";
    
    // Verifica Tamanho Minimo de um Link
    if(link.length < 14) { return 2; }
    
    // Verifica Prefixo http
    if(link.indexOf('http://') == -1) { return 2; }
    else
    {
        // Procura pelos Caracteres Inválidos
        for(i=7; i<link.length; i++) {
            for(ii=0; ii<invalidChar.length; ii++) {
                if(link.charAt(i) == invalidChar.charAt(ii)) { return 2; }
        } }
        
        // O Setimo caracter não pode ser ponto nem virgula
        if(link.charAt(7) == '.' || link.charAt(7) == ',') { return 2; }
        // O ultimo caracter não pode ser ponto nem virgula
        if(link.charAt(link.length-1) == '.' || link.charAt(link.length-1) == ',') { return 2; }
        // No minimo 1 Ponto deve ser Encontrado
        if(link.indexOf('.') == -1) { return 2; }
    }
    return 0;
}





/* **************************************************************
Faz o preenchimento de um input type="text" com o conteúdo de um 
input type="file"
************************************************************** */
function setFileWText(obj, targ) { id(targ).value = obj.value;	}





/* **************************************************************
Faz Controle de uma Determinada Mensagem no Input, limpando o mesmo
quando recebe Foco e Voltando à mensagem em caso de perder foco
com o valor vazio.
Deve ser adicionado no evento onfocus e on blur
************************************************************** */
function setValue(obj, val) {
	atualVal = obj.value;
	if(atualVal == val) { obj.value = ''; }
	else if(atualVal == '') { obj.value = val; }
}






/* **************************************************************
Variaveis que indicam os valores comuns a todos os Objetos de
validação objFormValidation(). Estes valores podem ser alterados
posteriormente usando os métodos internos do objeto.
************************************************************** */
var DefaultOutputError = 'alert'; // html ou alert
var DefaultDivOutputError = 'xjsOutput'; // ID da Div de Saida das Mensagens
var DefaultFieldString = '*?*'; // String que será trocada nas mensagens pelo nome do campo
var dataSpace = '.'; // Completa a Mascada de data identificando o seu separador



/* **************************************************************
Valores default das mensagens de alerta
Internamente os valores referentes aos tipos de erros são:
1 - Campo vazio
2 - Valor Invalido
3 - Não selecionado
************************************************************** */
var DefaultTitleAlert = 'Foram encontrados os seguintes erros:';
var DefaultEmptyInput = 'O Campo *?* deve ser preenchido.';
var DefaultWrongValue = 'O Campo *?* está incorreto.';
var DefaultNotSelected = 'Escolha uma das Opções do campo *?*.';








/* **************************************************************
Cria Objeto que contem dados acerca dos campos que devem ser validados
assim como informações sobre o retorno da mensagem de erro.
************************************************************** */
function objFormValidation() {
	this.output = DefaultOutputError;
	this.idoutput = DefaultDivOutputError;
	this.fieldstring = DefaultFieldString;


	this.fields = new Array();
	this.method = new Array();
	this.labels = new Array();

	this.titlealert = DefaultTitleAlert;
	this.emptyinput = DefaultEmptyInput;
	this.wrongvalue = DefaultWrongValue;
	this.notselected = DefaultNotSelected;


	// Métodos Set
	this.setOutPut = function(out, id) { 
	    this.output = out; 
	    this.idoutput = id; 
	};
	this.setFieldString = function(value) { this.fieldstring = value; };

	this.setTitleAlert = function(value) { this.titlealert = value; };
	this.setEmptyInput = function(value) { this.emptyinput = value; };
	this.setWrongValue = function(value) { this.wrongvalue = value; };
	this.setNotSelected = function(value) { this.notselected = value; };

	// Adiciona Campo à Validação
	this.addField = function(idf, met, lab){
		nAtual = this.fields.length;
		this.fields[nAtual] = idf;
		this.method[nAtual] = met;
		this.labels[nAtual] = lab;
	};


	// Faz Testes nos Campos
	this.checkForm = function() {
		var len = this.fields.length;
		var errorArray = new Array();
		var errorN = 0;

		for(cont=0; cont<len; cont++)
		{
			if(this.method[cont] == 'isEmpty') { ret = isEmpty(this.fields[cont]);	}
			else if(this.method[cont] == 'isData') { ret = isData(this.fields[cont]); }
			else if(this.method[cont] == 'isEmail')	{ ret = isEmail(this.fields[cont]); }
			else if(this.method[cont] == 'isLink')	{ ret = isLink(this.fields[cont]); }
			else if(this.method[cont] == 'isSelected')	{ ret = isSelected(this.fields[cont]); }
			else if(this.method[cont] == 'isRadioSelect')	{ ret = isRadioSelect(this.fields[cont]); }
		
			else if(this.method[cont] == 'isCPF')	{ ret = isCPF(this.fields[cont]); }
			else if(this.method[cont] == 'isCNPJ')	{ ret = isCNPJ(this.fields[cont]); }
			if (ret != 0) { errorArray[errorN] = this.addError(this.labels[cont], ret); errorN++; }
		}
		
		if(errorN != 0){ this.strErrorMessage(errorArray); return false; }
		else { return true; }
	};
	

	this.addError = function(label, n) {
		if(n == 1) { return this.emptyinput.replace(this.fieldstring, label); }
		else if(n == 2) { return this.wrongvalue.replace(this.fieldstring, label); }
		else if(n == 3) { return this.notselected.replace(this.fieldstring, label); }
	};
	
	
	this.strErrorMessage = function(err){
		var finalMessage = '';

		if(this.output == 'alert')
		{
			finalMessage = this.titlealert + '\n';
			for(i=0; i<err.length; i++)	{ finalMessage += err[i] + '\n'; }
			alert(finalMessage);
		}
		else if(this.output == 'html')
		{
			finalMessage = '<div class="xjsOutput">';
			finalMessage += '<h3>' + this.titlealert + '</h3>';
			finalMessage += '<ul>';
			for(i=0; i<err.length; i++)	{ finalMessage += '<li>' + err[i] + '</li>'; }
			finalMessage += '</ul></div>';
			thisTag = id(this.idoutput);
			thisTag.innerHTML = finalMessage;
			thisTag.style.display = 'block';
		}
	};
}



















/* **************************************************************
setDisplay : Controla Especificamente Propriedade Display do ID
setVisibility : Controla Especificamente Propriedade Visivility do ID
showHideElement : Só efetua mudança de Display se Objeto Existir
************************************************************** */
function setDisplay(idName, value){	id(idName).style.display = value; }
function setVisibility(idName, value){	id(idName).style.visibility = value; }
function showHideElement(idName, value) { if(id(idName)) { setDisplay(idName, value); } }



/* **************************************************************
Abre/Fecha Sombra - Usada para Modal
************************************************************** */
function showHideShadow(toDo) {
	if(toDo == 'show') {
		setDisplay('divShadow', 'block');
		extendToNode('divShadow', 'Screen', 'yes', 'yes');
	}
	else if(toDo == 'hide') { setDisplay('divShadow', 'none'); }

	if(toDo == 'show' && browser.type == 'IE' && browser.version == '6') { 
		searchAndInsertIframe('div', 'iFrame'); 
		searchAndInsertIframe('div', 'iFrameModal');
	}
}




/* **************************************************************
Abre/Fecha Modal + Sombra
************************************************************** */
function showHideModal(toDo, URLimg, legenda) {
	if(toDo == 'show') {
		ModalIsOpen = true;
		showHideShadow(toDo);

	    setDisplay('divContainModal', 'block');
	    resetModal();

		nIMG = new Image();
		nIMG.src = URLimg;
		nIMG.alt = legenda;
		nIMG.id = ModalImgID;
		
		pLeg = document.createElement('p');
		pLeg.id = ModalPID;
		pLeg.innerHTML = legenda;
		
		if(nIMG.complete == true) { showModalImage(); }
		nIMG.onload = function() { 
		    setTimeout('showModalImage()', 300);
	    };
	}
	else if(toDo == 'hide') {
		ModalIsOpen = false;
		showHideShadow(toDo);
		resetModal();
		setDisplay('divContainModal', 'none');
	}
}


function showModalImage()
{
    if(nIMG.complete == true){
        id('divModalL').innerHTML = '<div id="divIMGModal"></div><div id="divLegModal"></div>';
        id('divLegModal').appendChild(pLeg);
        id('divIMGModal').appendChild(nIMG);
        setModalDim();
        setModalCoords();
    }
}



/* **************************************************************
Reseta Posição, Elementos e Dimensoes do Modal
************************************************************** */
function resetModal()
{
    if(id(ModalPID)) { id('divLegModal').innerHTML = ''; }
	if(id(ModalImgID)) { id('divIMGModal').innerHTML = ''; }
	id('divModalL').innerHTML = '<div id="divIMGModal"></div><img src="../../img/loader_big.gif" class="imgLoadModal" alt="" /><div id="divLegModal"></div>';
	
	id('divModal').style.height = ModalOnLoadH + 'px';
	id('divModal').style.width = ModalOnLoadW + 'px';
	setModalCoords();
}





/* **************************************************************
Reseta Posição, Elementos e Dimensoes do Modal
************************************************************** */
function setModalCoords()
{
    coordY = 0;
    coordX = 0;
    dimenW = 0;
    dimenH = 0;

    atualY = getPageYScroll();
    atualX = getPageXScroll();
    
    atualW = id('divModal').clientWidth;
    atualH = id('divModal').clientHeight;

    // Posiciona eixo Vertical
    if(ModalY == 'middle') {
        bodyY = thisPage.windowH/2;
        modalY = atualH/2;
        coordY = atualY + (bodyY - modalY);
    }
    else { coordY = atualY + ModalY; }

    // Posiciona eixo Horizontal    
    if(ModalX == 'middle') {
        bodyX = thisPage.windowW/2;
        modalX = atualW/2;
        coordX = atualX + (bodyX - modalX);
    }
    else { coordX = atualX + ModalX; }
    
    id('divModal').style.top = coordY + 'px';
    id('divModal').style.left = coordX + 'px';
}



/* **************************************************************
Posiciona Modal Conforme Variaveis de Configuração
************************************************************** */
function setModalDim()
{
    // Resgata Tamanho Atual
    imgH = id(ModalImgID).clientHeight;
    imgW = id(ModalImgID).clientWidth;
    
    // Ajusta Largura do <P>
    if(id(ModalPID).innerHTML != ''){
        id(ModalPID).style.width = imgW + 'px';
    }
    else { id(ModalPID).style.display = 'none'; }
    
    pH = id(ModalPID).clientHeight;
    pW = id(ModalPID).clientWidth;
    
    // Ajusta Dimensão do divModal
    id('divModal').style.height = (imgH + pH) + 'px';
    id('divModal').style.width = imgW + 'px';
}





/* **************************************************************
Extende uma Div por Toda a Area de Determinado Node
parentID - 'Screen' : usa toda a area visivel como referencia
setW e setH: seta quais propriedades devem ser alteradas
	'yes' ou 'no'
outros parametros devem ser ID de elementos a serem diminuidos
************************************************************** */
function extendToNode(thisID, parentID, setW, setH) {
	var totalW;
	var totalH;
	if(parentID == 'Screen'){
		totalW = document.documentElement.clientWidth;
		totalH = thisPage.bodyH;
	}
	else {
		totalW = id(parentID).clientWidth;
		totalH = id(parentID).clientHeight;
	}

	var tArgs = arguments.length;
	var decW = 0;
	var decH = 0;
	if (tArgs > 4) {
		for(i=4; i<tArgs; i++) {
			if(id(arguments[i])) {
				getW = id(arguments[i]).clientWidth;
				getH = id(arguments[i]).clientHeight;
				decW += getW; 
				decH += getH;
			}
			else if(arguments[i].indexOf('_W') != -1 || arguments[i].indexOf('_H') != -1) {
				if(arguments[i].indexOf('_W') != -1) { decW += parseInt(arguments[i].replace('_W', '')); }
				if(arguments[i].indexOf('_H') != -1) { decH += parseInt(arguments[i].replace('_H', '')); }
	} } }
	
	var finalW = totalW - decW;
	var finalH = totalH - decH;
	if(browser.type == 'IE' && browser.version == '6'){
		if(setW == 'yes'){ id(thisID).style.width = finalW + 'px'; }
		if(setH == 'yes'){ id(thisID).style.height = finalH + 'px'; }
	}
	else {
		if(setW == 'yes'){ id(thisID).style.minWidth = finalW + 'px'; }
		if(setH == 'yes'){ id(thisID).style.minHeight = finalH + 'px'; }
	}
}



/* **************************************************************
Posiciona um elemento na tela com 'position:absolute' em determinadas
coordenadas passadas
setPosition = 'Center' : Centraliza Horizontal e Verticalmente
setPosition = 'CenterV': Centraliza Verticalmente
setPosition = 'CenterH': Centraliza Horizontalmente
************************************************************** */
function positionNodeTo(thisID, setPosition, setT, setL) {
	tW = document.documentElement.clientWidth;
	tH = document.documentElement.clientHeight;
	width = id(thisID).clientWidth;
	height = id(thisID).clientHeight;
	setLeft = setL;
	setTop = setT;


	if(setL == '') { 
		setLeft = (tW - width) / 2; 
		if((tW - width) % 2 != 0) { setLeft = setLeft-0.5; }
	}
	if(setT == '') { 
		setTop = (tH - height) / 2; 
		if((tH - height) % 2 != 0) { setTop = setTop-0.5; }
	}

	
	if(setPosition == 'Center') { 
		id(thisID).style.left = setLeft + 'px'; 
		id(thisID).style.top = setTop + 'px';
	}
	if(setPosition == 'CenterH') { id(thisID).style.left = setLeft + 'px'; }
	if(setPosition == 'CenterV') { id(thisID).style.top = setTop + 'px'; }
}



/* **************************************************************
Retorna a posição Y em que se encontra o topo da area visivel da
tela na janela do navegador
************************************************************** */
function getPageYScroll() {
    var yScroll;
    if (self.pageYOffset) { yScroll = self.pageYOffset; } 
	else if (document.documentElement && document.documentElement.scrollTop) { yScroll = document.documentElement.scrollTop; } 
	else if (document.body) { yScroll = document.body.scrollTop; }
    return yScroll;
}



/* **************************************************************
Retorna a posição X em que se encontra a Margem esquerda da area 
visivel da tela na janela do navegador
************************************************************** */
function getPageXScroll() {
    var xScroll;
    if (self.pageXOffset) { xScroll = self.pageXOffset; } 
	else if (document.documentElement && document.documentElement.scrollLeft) { xScroll = document.documentElement.scrollLeft; } 
	else if (document.body) { xScroll = document.body.scrollLeft; }
    return xScroll;
}







/* **************************************************************
SELECT DHTML
************************************************************** */
var ignoreClick = false;
var openDHTMLSelect = null;

function initiDHTMLSelects(className) {
	var getAllSelectsDHTML = getElementsByClassName(className);
	
	for(i=0; i<getAllSelectsDHTML.length; i++) {
		// Resgata ID do Select Atual
		idObject = getAllSelectsDHTML[i].id;
		objSelect = id(idObject);
		objSelect.style.zIndex = '1';
		
		objSelectBorder = getTagsChildOfID('div', idObject);
		objSelectBorder = objSelectBorder[0];

		// Adiciona Evento Para Abrir e Fechar Select
		if (document.attachEvent) { objSelectBorder.attachEvent('onclick', openCloseDHTMLSelect); }
		else { objSelectBorder.setAttribute('onclick', 'openCloseDHTMLSelect(this)'); 
		}
	}
}


function closeDHTMLSelect() {
	if(ignoreClick == false) {
		if(openDHTMLSelect != null) { openDHTMLSelect.className = 'selectDHTML'; downZIndex(openDHTMLSelect); openDHTMLSelect = null; }
	}
	else { ignoreClick = false; }
}


function openCloseDHTMLSelect(obj) {
	var atualClass;
	var isOpen;

	// Seleciona Objeto ID Pai do Select e sua Classe Atual
	if(document.attachEvent) {
		var obj = (obj.srcElement)?obj.srcElement : obj.target;
		isThis = false;
		force = 'obj';

		while(isThis != true) {
			force += '.parentNode';
			obj = eval(force);

			if(obj.className.indexOf('selectBorder') != -1) { 
				isThis = true;
				atualClass = obj.parentNode.className;
				obj = obj.parentNode;
	} } }
	else { 
		atualClass = obj.parentNode.className; 
		obj = obj.parentNode;
	}

	// Verifica se Está Aberto
	if(atualClass.indexOf('selectDHTML_open') != -1) { isOpen = true; }
	else { isOpen = false; }

	// Verifica se Há Outro Select Aberto, Havendo, Fecha-o
	if(isOpen == false && openDHTMLSelect != null && openDHTMLSelect != obj) { 
		openDHTMLSelect.className = 'selectDHTML'; downZIndex(openDHTMLSelect); openDHTMLSelect = null;
	}

	// Abre ou Fecha Select Atual
	if(isOpen == true) { obj.className = 'selectDHTML'; openDHTMLSelect = null; downZIndex(obj); }
	else if (isOpen == false) { obj.className += ' selectDHTML_open'; openDHTMLSelect = obj; ignoreClick = true; upZIndex(obj); }
}


function upZIndex(obj) { obj.style.zIndex = '2'; }
function downZIndex(obj) { obj.style.zIndex = '1'; }
function selectedDHTMLValueSet(option, value) {
	idObject = option.parentNode.parentNode.parentNode.id;
	inputs = getTagsChildOfID('input', idObject);
	inputs[0].value = option.innerHTML;
	inputs[1].value = value;
}



















/* **************************************************************
Retorna um objeto "browser" com a propriedade "type" para determinar 
o browser que o usuario utiliza.
Retorna também uma propriedade "version"
************************************************************** */
function objBrowser() {
	strTipo = '';
	strVersao = '';

	// Detecta se é IE
	if(document.all) { 
		strTipo = 'IE'; 
		if(window.XMLHttpRequest) { strVersao = '7'; }
		else if(document.compatMode) { strVersao = '6'; }
	}
	// Detecta de é Opera
	if(window.opera) { strTipo = 'Opera'; }
	// Detecta Gecko
	if(document.getBoxObjectFor != null) { strTipo = 'Gecko'; }
	// Detecta Safari
	if((document.childNodes) && (!document.all) && (!navigator.taintEnabled) && (!navigator.accentColorName)) { 
		strTipo = 'Safari'; 
	}

	this.type = strTipo;
	if (strTipo == 'IE') { this.version = strVersao; }
	else { this.version = ''; }
}



/* **************************************************************
Retorna Objeto com propriedades sobre a pagina atual tais como:
nome da pagina
nome da Sessão
altura e largura total do monitor do usuario
altura e largura total da janela do browser
altura e largura total do documento
************************************************************** */
function objPageInfo(atualURL) {
	// Resgata Nome da Pagina e Sessão Atual
	splita = atualURL.split("/");
    intLast = splita.length - 1;
    this.pageName = splita[intLast];
    this.session = splita[intLast - 1];
	
	// Resgata Dimensoes do Monitor
	this.screenW = screen.width; 
	this.screenH = screen.height;
	
	// Resgata Dimensoes do Browser
	this.windowW = document.documentElement.clientWidth;
	this.windowH = document.documentElement.clientHeight;

	// Total do Body
	if(id(xjsIDContainer)){
	    this.bodyW = id(xjsIDContainer).clientWidth;
	    this.bodyH = id(xjsIDContainer).clientHeight;
	}
	else {
	    this.bodyW = this.windowW;
	    this.bodyH = this.windowH;
	}
}





/* **************************************************************
Cria um Objeto que Carrega os Valores das propriedades do Popup
	url -> url da pagina a ser aberta
	popName -> nome de controle do popup
	isScroll -> 'yes' ou 'no'
	isResize -> 'yes' ou 'no'

Valores padrões:
	isMaxArea -> false : Para Ocupar toda a tela
	width e height -> respectiva largura e altura
	isToCenter -> true : Indica que deve ser aberto ao centro da tela
	top e left -> coordenadas de abertura do popup na tela

************************************************************** */
function objPopUp(url, popName, isScroll, isResize) {
	this.url = url;
	this.popName = popName;
	this.isMaxArea = false;
	this.width = '';
	this.height = '';
	this.isToCenter = true;
	this.top = '';
	this.left = '';
	this.isScrollBars = isScroll;
	this.isResizable = isResize;
	strPopUp = '';

	this.setDimencion = function(isMax, w, h) {
		this.isMaxArea = isMax;
		this.width = w;
		this.height = h;
	};
	
	this.setPosition = function (isCenter, t, l) {
		this.isToCenter = isCenter;
		this.top = t;
		this.left = l;
	};
	
	this.createString = function () {
		tW = screen.width;
		tH = screen.height;

		if (this.isMaxArea == true) { W = tW; H = tH; }
		else { W = this.width; H = this.height; }
		popArea = 'Width='+ W + ', Height='+ H +', ';
		
		if (this.isToCenter == true) { L = (tW - this.width) / 2; T = (tH - this.height) / 2; }
		else { L = this.left; T = this.top; }
		popPosition = 'top='+ T +', left='+ L +', ';
		
		popCaracteres = 'scrollbars='+ this.isScrollBars +', resizable='+ this.isResizable;
		strPopUp = popArea + popPosition + popCaracteres;
	};
	
	this.openThis = function () {
		this.createString();
		window.open(this.url, this.popName, strPopUp);
	};
}



/* **************************************************************
Cria um objeto responsavel por armazenar as propriedades de um 
filme flash para posterior amostra
************************************************************** */
function objFlash(srcSWF){
	this.scr = srcSWF;
	this.id = '';
	this.classe = '';
	this.title = '';
	this.width = '';
	this.height = '';
	this.quality = '<param name="quality" value="high" />';
	this.transparency = '';
	this.param = '<param name="allowScriptAccess" value="sameDomain" />';
	this.alternate = '<div class="xjsAltFlash">' + xjsAltFlash + '</div>';
	this.flashvars = '';
	strSwf = '';


	this.setObject = function(thisID, thisClass, thisTitle, w, h) {
		this.id = thisID;
		this.classe = thisClass;
		this.title = thisTitle;
		this.width = w;
		this.height = h;
	};
	this.setQuality = function(q) { this.quality = '<param name="quality" value="'+ q +'" />'; };
	this.setTransparency = function() { this.transparency += '<param name="wmode" value="transparent">'; };


	this.addFlashVars = function(name, value) { 
		// Verifica se já há alguma variavel setada e adiciona o '&' para a próxima
		if(this.flashvars != '' && this.flashvars.indexOf('=') != -1) { this.flashvars += '&'; }
		this.flashvars += name +'='+ value;
	};
	this.addParam = function(name, value) { this.param += '<param name="' + name + '" value="' + value + '" />'; };


	this.clearFlashVars = function() { this.flashvars = ''; };
	this.clearParam = function() { this.param = '<param name="allowScriptAccess" value="sameDomain" />'; };
	this.clearTransparency = function() { this.transparency = ''; };


	this.createString = function () {
		// Inicia Tag Object
		strSwf = '<object ';
		
		if(browser.type == 'IE') {
			strSwf += 'classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ';
			strSwf += 'codebase="http://www.adobe.com/br/shockwave/download/alternates/" ';
			this.addParam('movie', this.scr);
		}
		else {
			strSwf += 'type="application/x-shockwave-flash" ';
			strSwf += 'data="'+ this.scr +'" ';
		}

		// Adiciona Propriedades Básicas
		if (this.id != '') { strSwf += 'id="' + this.id + '" '; }
		if (this.classe != '') { strSwf += 'class="' + this.classe + '" '; }
		if (this.title != '') { strSwf += 'title="' + this.title + '" '; }

		strSwf += 'width="' + this.width + '" ';
		strSwf += 'height="' + this.height + '" ';
		strSwf += '>';

		if(this.flashvars != '') { this.addParam('flashvars', this.flashvars); }
		strParam = this.quality + this.transparency + this.param;
		
		strSwf += strParam + this.alternate + '</object>';
	};

	
	this.showFlash = function(where) {
		this.createString();
		
		if(where == 'here') { document.write(strSwf); }
		else if(where == 'alert') {alert(strSwf); }
		else { id(where).innerHTML = strSwf; }
	};
	
	
	this.fontReplace = function(getTagByClass, searchTag) {
		getTag = new Array;	
		getTag = getElementsByClassName(getTagByClass, searchTag);

		for (f=0; f<getTag.length; f++)
		{
			if (xjsSuportFlash == true) {
				content = getTag[f].innerHTML; 
				this.title = content;
				
				this.clearFlashVars();
				this.clearParam();
				
				this.addFlashVars('tagInside', content);

				this.createString();
				getTag[f].innerHTML = strSwf;
			}
			// Para não 'piscar' defina que a classe para troca tem visibility=hidden
			getTag[f].style.visibility = 'visible';
        } 
    };
}




/* **************************************************************
Cria um objeto thumbnail
************************************************************** */
function objThumbNail(idImg, idLabel, strMessage) {
	this.img = idImg;
	this.label = idLabel;
	this.message = strMessage;
	this.nAtual = 0;


	this.thumbImg = new Array();
	this.thumbImgLabel = new Array();
	
	this.addImage = function(src, label) {
		indexAtual = this.thumbImg.length;
		this.thumbImg[indexAtual] = src;
		this.thumbImgLabel[indexAtual] = label;
	};
	
	this.setImg = function() { 
		id(this.img).src = this.thumbImg[this.nAtual]; 
		this.setMessage();
	};
	
	this.nextImg = function() {
		last = this.thumbImg.length - 1;
		if(this.nAtual < last){ this.nAtual++; this.setImg(); } 
	};

	this.prevImg = function() {
		if(this.nAtual > 0){ this.nAtual--; this.setImg(); } 
	};


	this.setMessage = function() {
		if(this.message != '') {
			finalMessage = '';
			if(this.message.indexOf('*atual*') != -1) { 
				nAtual = this.nAtual + 1;
				finalMessage = this.message.replace('*atual*', nAtual);
			}
			if(this.message.indexOf('*total*') != -1) { 
				nTotal = this.thumbImg.length;
				if(finalMessage != ''){ finalMessage = finalMessage.replace('*total*', nTotal); }
				else { finalMessage = this.message.replace('*total*', nTotal); }
			}
			id(this.label).innerHTML = finalMessage; 
        }
    };
}










/* **************************************************************
Declaração e/ou Adição de Dados das Variáveis Básicas 
************************************************************** */
// Basic
var xjsLocation = location + ''; // url atual


// Behavior
var xjsLastKeyDown;
var linkExterno = 'ex'; // Valor de um atributo 'rel' de uma tag 'a' que indica que a mesma é aberta em link Externo
var sufixHover = '_hover';
var sufixNoHover = '_nhover';
var MonitoreEnter = true; // Quando Monitorado, o Enter Dispara uma Ação 'activeOnEnter()'


// Objects
var browser = new objBrowser();
var thisPage;
var xjsIDContainer = 'divPrincipal'; // ID do container principal da Tela
var xjsSuportFlash = isFlashPlayer();
var xjsAltFlash = '<a href="http://www.adobe.com/go/getflash/" rel="'+ linkExterno +'">Get Adobe Flash Player</a>';

// Layout
var ModalImgID = "imgModal";
var ModalPID = "pModalTexto";
var ModalIsOpen = false;
var ModalY = 'middle'; // Distancia Vertical da Margem superior; middle ou valor em PX
var ModalX = 'middle' // Posicionamento Horizontal da Margem esquerda; middle ou valor em PX
var ModalDimY = 'var'; // Altura minima do Modal; var = variavel
var ModalDimX = 'var'; // Largura minima do Modal; var = variavel
var ModalOnLoadW = 370; // Largura do Modal enquanto Carrega
var ModalOnLoadH = 200; // Altura do Modal enquanto Carrega

// CSS Para Safari
if(browser.type == 'Safari') { 
    document.write('<style type="text/css">@import "../../css/styles-safari.css";</style>');
}