/**
 * Internet Explorer 6.0, Mozilla 1.6 
 */


/**
 *    <<< Common >>>
 */

window.cjf = self;

cjf.SUPORTADO = document.getElementById?true:false;   
cjf.N4  = window.document.layers?true:false;
cjf.IE  = window.document.all   ?true:false;
cjf.IE4 = cjf.IE && navigator.appVersion.indexOf('MSIE 4')>0 ? true:false;
cjf.IE5 = cjf.IE && navigator.appVersion.indexOf('MSIE 5')>0 ? true:false;

cjf.anoBase = new Date().getFullYear(); //redefinido no index.jsp

cjf.ancestralOf = function(parentNode, node){
	while(node){
		if(node.parentNode==parentNode){
			return true;
		}
		node = node.parentNode;
	}
	return false;
}

cjf.findParentTag = function(node, tag){
	tag = tag.toUpperCase();
	var parentNode = node.parentNode;
	while(parentNode){
		if(parentNode.tagName.toUpperCase()==tag){
			return parentNode;
		}
		parentNode = parentNode.parentNode;
	}
	return null;
}

cjf.showBorders = function(window, size){
	size = !size?1:size;
	var doc_tables = window.document.getElementsByTagName("table");
	for (var i=0; i<doc_tables.length; i++){
	   	doc_tables[i].border = size;
	}
}

cjf.getEventTarget = function(window, event){
	return (event && event.relatedTarget) ?event.relatedTarget :window.event.toElement;
}

cjf.getDocument = function(source){
	return source.contentDocument?source.contentDocument:(source.document?source.document:source.ownerDocument);
}

cjf.getElement = function(source, id){
	return this.getDocument(source).getElementById(id);
}

cjf.getOffset = function(object, parent){
 	var offset = new Object();
	offset.left = object.offsetLeft;
	offset.top  = object.offsetTop;
	var objectParent = object.offsetParent
   	while (objectParent && objectParent != parent) {
		offset.left += objectParent.offsetLeft-objectParent.scrollLeft;
     	offset.top  += objectParent.offsetTop -objectParent.scrollTop;
     	objectParent = objectParent.offsetParent;
   	}
    return offset;
}

//cjf.getOffsetLeft = function(object, container){
//	var offsetLeft = object.offsetLeft;
//	while(object && object.offsetParent!=container){
//		object = object.offsetParent;
//		if(object && object.offsetLeft){
//			offsetLeft += object.offsetLeft;
//		}
//	}
//	return offsetLeft;
//}

//cjf.getOffsetTop = function(object, container){
//	var offsetTop = object.offsetTop;
//	while(object && object.offsetParent!=container){
//		object = object.offsetParent;
//		if(object && object.offsetTop){
//			offsetTop += object.offsetTop;
//		}
//	}
//	return offsetTop;
//}

cjf.setVisibility = function(object, bool){
	object.style.visibility=bool?'visible':'hidden';
}

cjf.isVisible = function(object){
	return object.style.visibility!='hidden';
}

cjf.setDisplay = function(object, bool){
	object.style.display=bool?'':'none';
}

cjf.isDisplay = function(object){
	return object.style.display!='none';
}

cjf.setOpacity = function(object, opacity){
	object.style.filter='alpha(opacity='+opacity+')';
}

cjf.setLocation = function(object, left, top){
    object.style.left = left;
   	object.style.top  = top;
}

cjf.setSize = function(object, width, height){
    object.style.width  = width;
    object.style.height = height;
}

cjf.trim = function(string){
	return string.replace(/^([ \n\r\t]+)/,'').replace(/([ \n\r\t]+)$/,'');
}

cjf.allTrim = function(string){
	return string.replace(/[ \n\r\t]/g,'');
}

cjf.getBounds = function(object, parent){ //corrigir com parent????this.getOffsetTop.. document.body.scrollLeft-2 document.body.scrollTop -2
	var bounds = new Object();
	bounds.left   = parseInt(object.offsetLeft  ); //corrigir com parent????
	bounds.top    = parseInt(object.offsetTop   );
	bounds.width  = parseInt(object.offsetWidth);
	bounds.height = parseInt(object.offsetHeight);
//	bounds.left   = parseInt(this.IE? object.style.pixelLeft : object.left  );
//	bounds.top    = parseInt(this.IE? object.style.pixelTop  : object.top   );
//	bounds.width  = parseInt(this.IE? object.clientWidth     : object.width );
//	bounds.height = parseInt(this.IE? object.clientHeight    : object.height);
	bounds.right  = bounds.left + bounds.width;
	bounds.bottom = bounds.top  + bounds.height;
	bounds.border = parseInt(object.style.borderWidth);
	return bounds;
}

cjf.moveElementTo = function(object, x, y){
	object.style.left = x;
	object.style.top  = y;
}
cjf.moveElementBy = function(object, dx, dy){
	var bounds = this.getBounds(object);
	this.moveElementTo(object, bounds.left+dx, bounds.top+dy); 
}

cjf.resizeElementTo = function(object, width, height){
	object.style.width   = width;
	object.style.height  = height;
} 
cjf.resizeElementBy = function(object, dWidth, dHeight){
	var bounds = this.getBounds(object);
	this.resizeElementTo(object, bounds.width+dWidth, bounds.height+dHeight);
}
 
cjf.getOuterHTML = function(node){
	if(typeof(node.outerHTML)!='undefined'){
		return node.outerHTML;
	}else{	// NS/Mozilla
		var str = "";
		switch (node.nodeType) {
			case 1: // ELEMENT_NODE
				str += "<" + node.nodeName;
				for (var i=0; i<node.attributes.length; i++) {
					if (node.attributes.item(i).nodeValue != null) {
						str += " "
						str += node.attributes.item(i).nodeName;
						str += "=\"";
						str += node.attributes.item(i).nodeValue;
						str += "\"";
					}
				}
				if (node.childNodes.length == 0 && leafElems[node.nodeName])
					str += ">";
				else {
					str += ">";
					str += this.getInnerHTML(node);
					str += "<" + node.nodeName + ">"
				}
				break;
				
			case 3:	//TEXT_NODE
				str += node.nodeValue;
				break;
			
			case 4: // CDATA_SECTION_NODE
				str += "<![CDATA[" + node.nodeValue + "]]>";
				break;
					
			case 5: // ENTITY_REFERENCE_NODE
				str += "&" + node.nodeName + ";"
				break;

			case 8: // COMMENT_NODE
				str += "<!--" + node.nodeValue + "-->"
				break;
		}
		return str;		
	}
}

cjf.getInnerHTML = function(node) {
	if(typeof(node.innerHTML)!='undefined'){
		return node.innerHTML;
	}else{	// NS/Mozilla
		var str = "";
		for (var i=0; i<node.childNodes.length; i++){
			str += this.getOuterHTML(node.childNodes.item(i));
		}
		return str;
	}
}

cjf.setInnerHTML = function(node, str){
	if(typeof(node.innerHTML)!='undefined'){
		node.innerHTML = str;
	}else{	// NS/Mozilla
		var r = node.ownerDocument.createRange(); 
		r.selectNodeContents(node);
		r.deleteContents();
		var df = r.createContextualFragment(str);
		node.appendChild(df);
	}
	return str;
}

cjf.indexOfCombo = function (combo, value){
    for (var i = combo.length-1; i>=0; i--){
		if(combo[i] && combo[i]!=null && combo[i].value==value){
			return i;
		}
    }
    return -1;
}

cjf.importStyleSheets = function(source, target){
	if(target.document.styleSheets.length==0){
		alert('cjf.exportStyleSheets: tag "<style></style>" n?o definida!');
		return;
	}
	var styleTarget = target.document.styleSheets[0];
   	for(var i=0; i<source.document.styleSheets.length; i++){
   		var styleSource = source.document.styleSheets[i];
   		var rules = styleSource.rules?styleSource.rules:styleSource.cssRules;
		for(var j=0; j<rules.length; j++){
			var rule = rules[j];
			if(styleTarget.addRule) {	// IE
				styleTarget.addRule(rule.selectorText, rule.style.cssText ,styleTarget.rules.length);
			} else if(styleTarget.insertRule) {	// Mozilla/NS
				styleTarget.insertRule(rule.selectorText+'{'+rule.style.cssText+'}',styleTarget.cssRules.length);
			} 
		}
	}
}

cjf.selectAll = function(frame, fieldName, bool){
    var field = this.getField(frame, fieldName);
    this.fieldSelectAll(field, bool);
}

cjf.fieldSelectAll = function(field, bool){
    for (var i = field.options.length-1; i>=0; i--){
    	if(field.options[i]){
			field.options[i].selected = bool;
		}
    }
}

cjf.fieldCheckAll = function(field, bool){
	if(!field.length){
		field.checked = bool;	
		return;
	}
    for (var i = field.length-1; i>=0; i--){
		field[i].checked = bool;
    }
}

cjf.setDisabled = function(form, bool){
	var elements = form.elements;
	for(var i=0; i<elements.length; i++){
		var field = elements[i];
		if(field.name && field.name.indexOf('$')==-1){
			field.disabled = bool;
		}
	}
}

//cjf.getTeclaCodigo = function(frame, event){
//	return (event && event.which)?event.which:frame.event.keyCode;
//}

cjf.focusSafe = function(field){
	try{
		field.focus();
	}catch(e){
	}
}

cjf.canHaveFocus = function(field){
	return !field.disabled && !field.readOnly && field.style && field.style.display!='none' && 
			field.style.visibility!='hidden' && field.type && field.type.toLowerCase()!='hidden';
}

cjf.firstFocus = function(frame){
	if(!frame.cjfFirstFocusSetted){
		var elements = this.getForm(frame).elements;
		for(var j=0; j<elements.length; j++){
			var field = elements[j];
			if(this.canHaveFocus(field)){ //primeiro campo recebe o foco
				this.focusSafe(field);
				return;
			}
		}
	}
} 

cjf.nextFocus = function(fieldCurrentFocus){
	var found = false;
	var elements = fieldCurrentFocus.form.elements;
	for(var j=0; j<elements.length; j++){
		var field = elements[j];
		if(field && found && this.canHaveFocus(field)){
			this.focusSafe(field);
			break;
		}
		if(field==fieldCurrentFocus){
			found = true;
		}
	}	
}

cjf.getChecked = function(checkboxes){
	for(var i=0; i<checkboxes.length; i++){
		if(checkboxes[i].checked){
			return checkboxes[i]
		}
	}
	return null;
}

cjf.getCheckedValue = function(checkboxes){
	var checkbox = this.getChecked(checkboxes);
	return checkbox!=null?checkbox.value:null;
}

cjf.getSelected = function(comboBox){
	return comboBox.selecteIndex!=-1?comboBox.options[comboBox.selectedIndex]:null;
}

cjf.getSelectedValue = function(comboBox){
	var option = this.getSelected(comboBox);
	return option!=null?option.value:null;
}

cjf.stringToFloat = function(str){
	return str?parseFloat(this.trim(str).replace(/\./g,'').replace(/,/, '.')):0.00;
}

cjf.floatToString = function(flt){
	if(!flt || (flt>-0.00001 && flt<0.00001)){
		flt = 0.00;
	}
	var string = (flt+'').replace(/\./g,',');
	var index;
	if((index=string.indexOf(','))==-1){
		string+=',00'
	}else if(string.length==index+2){
		string+='0';
	}else if(string.length>index+3){
		string = string.substring(0, index+3);
	}
	var max = (string.length-3)/3; //separadores de milhar
	for(var i=0; i<max; i++){
		string = string.replace(/(\d)(\d\d\d[\.\,])/g, '$1.$2')
	}
	return string;
}

/**
 *    <<< Cookies >>>
 */
cjf.cookieExpiresDays = 730; // <-02 anos
cjf.cookieExpiresTime = new Date(new Date().getTime() + (cjf.cookieExpiresDays * 24 * 60 * 60 * 1000));

cjf.cookieGet = function(name) {
	var arg = name + "=";
	var alen = arg.length;
	var clen = this.document.cookie.length;
	var i = 0;
	while (i < clen) {
		var j = i + alen;
		if (this.document.cookie.substring(i, j) == arg)
			return this.cookieGetVal(j);
		i = this.document.cookie.indexOf(" ", i) + 1;
		if (i == 0)
			break;
	}
	return null;
}
cjf.cookieSet = function(name, value) {
	var argv = this.cookieSet.arguments;
	var argc = this.cookieSet.arguments.length;
	var expires = (argc > 2) ? argv[2] : this.cookieExpiresTime;
	var path = (argc > 3) ? argv[3] : null;
	var domain = (argc > 4) ? argv[4] : null;
	var secure = (argc > 5) ? argv[5] : false;
	this.document.cookie =
		name
			+ "="
			+ escape(value)
			+ ((expires == null) ? "" : ("; expires=" + expires.toGMTString()))
			+ ((path == null) ? "" : ("; path=" + path))
			+ ((domain == null) ? "" : ("; domain=" + domain))
			+ ((secure == true) ? "; secure" : "");
}
cjf.cookieDelete = function(name) {
	var exp = new Date();
	exp.setTime(exp.getTime() - 1);
	var cval = this.cookieGet(name);
	this.document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}
cjf.cookieGetVal = function(offset) {
	var endstr = this.document.cookie.indexOf(";", offset);
	if (endstr == -1)
		endstr = this.document.cookie.length;
	return unescape(this.document.cookie.substring(offset, endstr));
}

/**
 *    <<< Menu >>>
 */

cjf.menuHandler = function(imgId, event){
	var img = this.getElement(this, imgId);
	var table = this.getElement(this, img.id.substr(0, img.id.length-'_img'.length));
	if(img.src.indexOf('plus')!=-1){
		img.src = img.src.replace(/plus/i, 'minus');
		table.style.display = '';
	}else{
		img.src = img.src.replace(/minus/i, 'plus');
		table.style.display = 'none';
	}
}

cjf.menuSelectLink = function(page){
	if(cjf.lastMenuLink){
		cjf.lastMenuLink.style.backgroundColor = '#e6e6e6';
		cjf.lastMenuLink = null;
	}
	var link = this.menuFindLink(page);
	if(link){
		link.style.backgroundColor = 'LightSteelBlue';
		cjf.lastMenuLink = link;
		cjf.menuExpande(link);
	}
}

cjf.menuFindLink = function(page){
	if(cjf.document.getElementsByTagName){
		var tagsA = cjf.document.getElementsByTagName("a");
		for (var i=0; i<tagsA.length; i++){
			var strClick = tagsA[i].onclick;
			if(strClick && strClick.toString().indexOf(page)!=-1){
   				return tagsA[i];
   			}
		}
	}
	return null;
}

cjf.menuExpande = function(link){
	var node = link;
	var scroll = false
	while(node){
		if(node.style && node.style.display=='none'){
			node.style.display='inline';
			scroll = true;
		}
		node = node.parentNode;
	}
	if(scroll && link.scrollIntoView){
		var tr = cjf.findParentTag(link, 'tr');
		if(tr){
			tr.scrollIntoView(false);
		}
	}
}

/**
 *    <<< Janelas >>>
 */

cjf.showFramePrincipal = function(page){

	cjf.menuSelectLink(page);

	var iframe = this.getElement(this, 'cjfConteudoPrincipal');
	//if(page.indexOf('CJF_OPERACAO')==-1){
	//	var index = page.indexOf('?');
	//	page += (index==-1?'?':'&')+'CJF_OPERACAO=CJF_OPERACAO_PESQUISAR'
	//}
	iframe.src=page;
	this.showAguarde(this);
	var frame = this.frames['cjfConteudoPrincipal'];
    this.hideMessage(frame, true);
}

cjf.showTitle = function(title){
	var text  = this.getElement(this, 'cjfTituloTexto');
	text.innerText=title;
	this.setVisibleTitle(true);
}

cjf.setVisibleTitle = function(bool){
	var title = this.getElement(this, 'cjfTitulo');
	this.setVisibility(title, bool);
}

cjf.showButtons = function(cancelar, confirmar, excluir, editar, adicionar){
	var btnCancelar = this.getElement(this, 'cjfBotaoCancelar');
	this.setDisplay(btnCancelar, cancelar);

	var btnConfirmar = this.getElement(this, 'cjfBotaoConfirmar');
	this.setDisplay(btnConfirmar, confirmar);

	var btnExcluir = this.getElement(this, 'cjfBotaoExcluir');
	this.setDisplay(btnExcluir, excluir);

	var btnEditar = this.getElement(this, 'cjfBotaoEditar');
	this.setDisplay(btnEditar, editar);

	var btnAdicionar = this.getElement(this, 'cjfBotaoAdicionar');
	this.setDisplay(btnAdicionar, adicionar);

	this.setVisibleButtons(true);
}

cjf.setVisibleButtons = function(bool){
	var botoes  = this.getElement(this, 'cjfBotoes');
	this.setVisibility(botoes, bool);
}

cjf.setVisibleButtons = function(bool){
	var botoes  = this.getElement(this, 'cjfBotoes');
	this.setVisibility(botoes, bool);
}

cjf.setMessageButton = function(frame, btnName, message){
  	frame.cjfMessage = message;
   	frame.cjfSetOnclick = function(btnName){
   		var btn = cjf.getElement(this, btnName)
   		btn.botaoConfirmarClick = btn.onclick;
   		btn.cjfMessage = this.cjfMessage;
   		btn.onclick = function(){
   			if(cjf.showConfirm(this.cjfMessage)){
   				this.botaoConfirmarClick();
   			}
   		};
   	}
   	frame.setTimeout("self.cjfSetOnclick('"+btnName+"')", 500);
}

cjf.getForm = function(frame){
	var form = frame.document.forms['CJF_FORM'];
	if(!form){
		this.alert('form "CJF_FORM" n?o achado!');
	}
	return form;
}
cjf.getFormPrincipal = function(){
	var frame = this.frames['cjfConteudoPrincipal'];
	return this.getForm(frame);
}
cjf.getField = function(frame, fieldName){
	var form = this.getForm(frame);
	var field = eval('form.elements["'+fieldName+'"]');
	if(!field){
		alert('Campo "'+fieldName+'" n?o encontrado!');
	}
	return field;
} 

cjf.submitForm = function(frame, parameter, page, textoOperacao){
	var form = this.getForm(frame);
	if(parameter.indexOf('CJF_FINALIZACAO')==0){
		form.CJF_FINALIZACAO.value = parameter;
	}else{
		form.CJF_OPERACAO.value = parameter;
	}
	var id = !form.id.value?-1:form.id.value
	if((id==0 || id==-1)  
		&& (parameter.indexOf('CJF_OPERACAO_EXCLUIR')==0 || 
		    parameter.indexOf('CJF_OPERACAO_EDITAR' )==0 || 
		    parameter.indexOf('CJF_OPERACAO_ABRIR'  )==0)  ){
		this.showMessage(this.getI18NMessage('selecioneUmItem')+'!', frame, null);
		return;
	}
	if(parameter.indexOf('CJF_OPERACAO_ABRIR')==0){
		page = page+id;
		alert(page);
		this.showFramePrincipal(page);
		return;
	}
	if(parameter.indexOf('CJF_FINALIZACAO_CANCELAR')==0 || 
	   parameter.indexOf('CJF_OPERACAO_ADICIONAR')==0 || id==0 || 
	   (this.validateForm(frame, form) && !this.subCadastrosHasOpeneds(frame)) ){
		if(parameter.indexOf('CJF_FINALIZACAO_CONFIRMAR')==0){
			this.frameSelectAll(frame); //combos multiple
		}
		if(form.onsubmit && !form.onsubmit()){
			return;
		}
		if(parameter.indexOf('CJF_OPERACAO_ADICIONAR')==0){
			this.limparPesquisa(frame);
		}
		if(parameter.indexOf('CJF_OPERACAO_EXCLUIR')==-1 ||  this.showConfirm(this.getI18NMessage('desejaRealmente')+' '+this.getI18NMessage(textoOperacao)+' '+this.getI18NMessage('esteItem')+'?')){
			if(form.action!='imprimirRelatorio.do'){
				this.showAguarde(frame.parent);
			}
			if(parameter.indexOf('CJF_OPERACAO_EXCLUIR')==-1){
				cjf.setDisabled(form, false);
			}
			form.submit();
			this.hideMessage(frame, true);
		}
	}
}

cjf.formLoad = function(frame, exception, message, expressaoValidacao, timeout){
   	this.showException(exception, frame, timeout);
   	this.showMessage(message, frame, null, timeout);
   	frame.expressaoValidacao = expressaoValidacao;
   	this.hideAguarde(frame);
   	this.firstFocus(frame);
   	try{
   		this.ajudaEditavelCarregar(frame); //@FIXME
   	}catch(e){
   	}
   	cjf.ajusteMozilla(frame);
}

cjf.frameSelectAll = function(frame){
	if(frame.cjfSelectAll){
		for(var i=0; i<frame.cjfSelectAll.length; i++){
			this.selectAll(frame, frame.cjfSelectAll[i], true);
		}
	}
}

cjf.frameAddSelectAll = function(frame, fieldName){
	if(!frame.cjfSelectAll){
		frame.cjfSelectAll = [];
	}
	frame.cjfSelectAll[frame.cjfSelectAll.length] = fieldName;
}

cjf.limparPesquisa = function(frame){
	var elements = this.getForm(frame).elements;
	for(var i=0; i<elements.length; i++){
		var field = elements[i];
		if(field && typeof(field)=='object' && (field.type || field.length)){
			var type = (field.length && !field.options?field[0]:field).type.toLowerCase();
			if(this.canHaveFocus(field.length && !field.options?field[0]:field)){
				if(type=='checkbox' || type=='radio'){
					this.fieldCheckAll(field, false);
				}else if(field.options){
					field.selectedIndex = -1;
					this.fieldSelectAll(field, false);
				}else {
					field.value = '';
				}
			}else if(type=='hidden'){
				var display = cjf.getElement(frame, 'cjfPopupDisplay_'+field.name);
				if(display){
					field.value = '';
					display.innerHTML = this.getI18NMessage('pesquisar')+'...';
				}
			}
		}
	}
}

cjf.logoff = function(noAsk){
	if(noAsk || confirm(this.getI18NMessage('desejaRealmenteSairDoSistema')+'?')){
		this.location = 'index.jsp?logoff=true';
	}
}

cjf.sessaoExpirada = function(frame){
	frame.alert(this.getI18NMessage('sessaoExpirada')+'!');
	if(frame.parent && frame.parent.cjfPopup){
		frame.parent.close();
	}
    this.logoff(true);
}

cjf.showAguarde = function(frame){
	var conteudoPrincipal = this.getElement(frame, 'cjfConteudoPrincipal');
	var aguarde = this.getElement(frame, 'cjfAguarde');

    var offset = this.getOffset(conteudoPrincipal, frame);
    this.setLocation(aguarde, offset.left, offset.top);
	this.setSize(aguarde, conteudoPrincipal.offsetWidth, conteudoPrincipal.offsetHeight);
	
	this.setVisibility(aguarde, true);
}

cjf.hideAguarde = function(frame){
	var aguarde = this.getElement(frame.parent, 'cjfAguarde');
	if(aguarde){
		this.setVisibility(aguarde, false);
	}
}

cjf.rowSelect = function(tr, id){
	var childNodes = tr.parentNode.childNodes;
	var form = this.getFormPrincipal();
	var selectedRow=null;
	if(form.id.value!=''){
		selectedRow=this.getElement(tr.parentNode,'tr'+form.id.value);
	}
	if(selectedRow!=null){
		selectedRow.bgColor='#e6e6e6';
	}
	tr.bgColor='LightSteelBlue';
	form.id.value=id;
}

cjf.showException = function(exception, frame, timeout){
	if(exception && exception!='null'){
		this.showMessage(exception, frame, null, timeout);
	}
}

cjf.showMessage = function(mensagem, frame, focusField, timeout){
	if(mensagem && mensagem!='null'){
		var parent = frame?frame.parent:this;
		var frame = parent.frames['cjfMensagem'];
		frame.calendarField = null;
		var table = this.getElement(frame, 'cjfTableMensagem');
		this.setDisplay(table, true);
		table = this.getElement(frame, 'cjfTableCalendario');
		this.setDisplay(table, false);
		var display = this.getElement(frame, 'cjfDisplayMensagem');
		display.innerHTML = mensagem; //+'<br><br> //TODO melhorar esta mensagem!';
		var iframe = this.getElement(parent, 'cjfMensagem');
		this.resizeElementTo(iframe, '460', '180');
		this.moveElementTo(iframe, '28%', '18%');
		this.setVisibility(iframe, true);
		if(focusField){
			iframe.focusField = focusField;
		}
		if(timeout){
			frame.setTimeout("cjf.hideMessage(self);", timeout);
		}
	}
}

cjf.showCalendar = function(img, frame, fieldName){
	var field = this.getField(frame, fieldName);
	if(field.disabled || field.readOnly){
		return;
	}
	var parent = frame?frame.parent:this;
	var frameMensagem = parent.frames['cjfMensagem'];
	this.calendarSetYearDisabled(frameMensagem, true);
    this.calendarSetYear(this.anoBase); //volta ao ano base
	var table = this.getElement(frameMensagem, 'cjfTableMensagem');
	this.setDisplay(table, false);
	table = this.getElement(frameMensagem, 'cjfTableCalendario');
	this.setDisplay(table, true);
	var iframeMensagem = this.getElement(parent, 'cjfMensagem');
	iframeMensagem.focusField = null;
	this.resizeElementTo(iframeMensagem, '250', '202');
	var offset = this.getOffset(img, frame.document.body);
	iframeMensagem.style.left = offset.left;
	iframeMensagem.style.top  = offset.top;
	if(frame.parent && frame.parent.cjfPopup){
		iframeMensagem.style.left = offset.left;
		iframeMensagem.style.top  = offset.top;
	}else{
		var iframeConteudoPrincipal = this.getElement(this, 'cjfConteudoPrincipal');
		var offsetPrincipal = this.getOffset(iframeConteudoPrincipal, this);
		iframeMensagem.style.left = offset.left + offsetPrincipal.left;
		iframeMensagem.style.top  = offset.top  + offsetPrincipal.top;
	}
	this.calendarRoll(frameMensagem, field);
	this.setVisibility(iframeMensagem, true);
}

cjf.hideMessage = function(frame, noFocus){
	var iframe = this.getElement(frame.parent, 'cjfMensagem');
	this.setVisibility(iframe, false);
	if(iframe.focusField){
		if(!noFocus && this.canHaveFocus(iframe.focusField)){
			this.focusSafe(iframe.focusField);
		}
		iframe.focusField = null;
	}
	if(frame.calendarField){
		if(!noFocus && this.canHaveFocus(frame.calendarField)){
			this.focusSafe(frame.calendarField);
		}
		frame.calendarField = null;	
	}
}

cjf.showConfirm = function(mensagem){
	if(mensagem && mensagem!='null'){
		return confirm(mensagem); //+'\n\n //TODO melhorar esta mensagem!');
	}
}

cjf.showPopUp = function(opener, source, page, fieldName, callback, width, height){
	if (!source.isDisabled)
	{ 
		width  = (width ?width :'640');
		height = (height?height:'480');
		var url = 'popup.do?CJF_POPUP_PAGE='+escape(page)+'&CJF_POPUP_FIELD='+escape(fieldName)+(callback?'&CJF_POPUP_CALLBACK='+escape(callback):'');
		if(opener.showModalDialog){
			//sunken raised
			var params =
		      "dialogWidth:"+width+"px; dialogHeight:"+height+"px; "+ 
			  "edge:raised; center:Yes; help:No; "+
		      "resizable:Yes; status:No;";
			opener.showModalDialog(url, opener, params);
			//opener.showModelessDialog(page, opener, params);
		}else{
			opener.open(url, '_blank',
	                         'scrollbars=No,menubar=0,location=0,'+
	                         'resizable=Yes,toolbar=0,status=0,'+
	                         'width='+width+',height='+height+','+
	                         'top='+((screen.height-height)/2)+','+
	                         'left='+((screen.width-width)/2));
		}
	}
}

cjf.showDefaultModeless = function(opener, page, width, height, scrolling){
	width  = (width ?width :'640');
	height = (height?height:'480');
	scrolling = (scrolling?scrolling:'yes');
	var url = 'popup.do?CJF_POPUP_PAGE='+escape(page)+'&scrolling='+scrolling;
	if(opener.showModalDialog){
		//sunken raised
		var params =
	      "dialogWidth:"+width+"px; dialogHeight:"+height+"px; "+ 
		  "edge:raised; center:Yes; help:No; "+
	      "resizable:Yes; status:No;";
		opener.showModelessDialog(url, opener, params);
	}else{
		opener.open(url, '_blank',
                         'scrollbars=No,menubar=0,location=0,'+
                         'resizable=Yes,toolbar=0,status=0,'+
                         'width='+width+',height='+height+','+
                         'top='+((screen.height-height)/2)+','+
                         'left='+((screen.width-width)/2));
	}
}

cjf.callbackPopUp = function(frame, fieldName, id, display, callback, extrainfo){
	var field = this.getField(frame, fieldName);	
	if(field.type.toLowerCase()=='hidden' || field.type.toLowerCase()=='text'){
		this.callbackPopUpHidden(frame, field, id, display, callback, extrainfo);
	}else{
		this.callbackPopUpCombo(frame, field, id, display, callback, extrainfo);
	}
}
cjf.callbackPopUpHidden = function(frame, field, id, display, callback, extrainfo){	
   	var span  = this.getElement(frame, 'cjfPopupDisplay_'+field.name);
   	
	field.value = id;
	span.innerHTML = display;
	
	if (field.onchange != undefined)
	  field.onchange(); 
	
	if(callback){
		if(callback == 'trocaCidadeNovo') {	
			field.value = display;
			span.innerHTML = display;
		} else {
			frame.eval(callback)(field, id, display, extrainfo);
		}
	}
}
cjf.callbackPopUpCombo = function(frame, combo, id, display, callback, extrainfo){
	var index;
	if((index=this.indexOfCombo(combo, id))!=-1){
		combo.selectedIndex = index;
	}else{
		display = display.replace(/<b>|<\/b>|<i>|<\/i>/gi,'');
		var option = frame.document.createElement('option');
		option.value = id;
		option.text = display;
		combo.options[combo.options.length]=option;
		combo.selectedIndex = combo.options.length-1;
		if(callback){
			frame.eval(callback)(combo, id, display, 'adicionar', option, extrainfo);
		}
	}
}
cjf.removeComboItems = function(frame, comboName, callback){
	var combo = this.getField(frame, comboName);
	if(combo.selectedIndex==-1){
		this.showMessage(this.getI18NMessage('selecioneUmItem'), null, combo);
		return;	
	}
	if(this.showConfirm(this.getI18NMessage('removerItemsSelecionados')+'?')){
		for(var i=combo.options.length-1; i>=0; i--){
			var option = combo.options[i];
			if(option && option!=null && option.selected){
				combo.options[i]=null;
				if(callback){
					frame.eval(callback)(combo, option.value, option.text, 'remover', option);
				}
			}
		}
	}
}

cjf.ajustarTabela = function(frame, idTabela){
	var header = this.getElement(frame, idTabela+'_header');
	var detail = this.getElement(frame, idTabela+'_detail');
	var somatorio = this.getElement(frame, idTabela+'_somatorio');
	if(header && detail && detail.rows.length!=0) {
		var cells = detail.rows[0].cells;
		for (var j=0; j < cells.length; j++) {
			var width = cells[j].offsetWidth-3;
			if(width>0 && j<header.rows[0].cells.length){
				header.rows[0].cells[j].width = cells[j].offsetWidth-3;
			}
   		}
	}
	if(somatorio && detail && detail.rows.length!=0) {
		var cells = detail.rows[0].cells;
		for (var j=0; j < cells.length; j++) {
			var width = cells[j].offsetWidth-3;
			if(width>0 && j<somatorio.rows[0].cells.length){
				somatorio.rows[0].cells[j].width = cells[j].offsetWidth-3;
			}
   		}
	}
}


/**
 *    <<< Valida??o >>>
 */

cjf.validateForm = function(frame, form){
	return this.validateExpressao(frame, form, form, frame.expressaoValidacao);
}

cjf.validateExpressao = function(frameContext, form, subForm, expressao){
	if(expressao){
		var cjf = this;
		var vazio = this.isBlank; //alias para funcoes
		var dataValida = this.isValideDate;
		var zero = this.isZero;
		var selecionado = this.isSelected;
		var checked = this.isChecked;
		var comparaDatas = this.comparaDatas;
		var verificaIntervaloNumero = this.verificaIntervaloNumero;
		var verificaSubTotais = this.verificaSubTotais;
		var horaValida = this.isValidHour;
		with(frameContext){
			with(cjf){
				with(form){ //avaliado no contexto do form
					with(subForm){
						try{
							return eval(expressao);
						}catch(e){
							alert(e.message);
							return false;
						}
					}
				}
			}
		}
	}
	return true;
}

cjf.isBlank = function(field, silent, rotulo){
	var empty;
	if(field.options){
		empty = field.options.length==0;
	}else{
		var value = field.value;
		if(!value){
			value = field.fileName;
		}
		empty = !value || this.allTrim(value)=='';
	}
	if(empty && !silent){
		rotulo = rotulo?rotulo:this.findRotulo(field);
		
		this.showMessage(this.getI18NMessage('campo')+' "'+(rotulo?rotulo:field.name)+'" '+this.getI18NMessage('naoPodeSerVazio')+'!', null, field);
		if(this.canHaveFocus(field)){
			this.focusSafe(field);
		}
	}
	return empty;
} 

cjf.isValideDate = function(field, silent, rotulo){
	if(this.isBlank(field, silent)){
		return false;
	}
	var value = this.allTrim(field.value);
	if(value && value.length==10){
		var day = value.substr(0,2);
		var month = value.substr(3,2)-1;
		var year = value.substr(6);
		var date = new Date(year,month,day);
		if(date.getDate()==day && date.getMonth()==month && date.getFullYear()==year){
			return true;
		}
	}
	if(!silent){
		rotulo = rotulo?rotulo:this.findRotulo(field);
		this.showMessage(this.getI18NMessage('aDataNoCampo')+' "'+(rotulo?rotulo:field.name)+'" '+this.getI18NMessage('naoEValida')+'!', null, field);
		if(this.canHaveFocus(field)){
			this.focusSafe(field);
		}

	}
	return false;
} 

cjf.isValidHour = function(field, silent, rotulo){
	if(this.isBlank(field, silent)){
		return false;
	}
	var value = this.allTrim(field.value);
	if(value && value.length==5)
	{
		var horas = parseInt(value.substr(0,2));
		var minutos = parseInt(value.substr(3,2));
		if( (horas>=0) && (horas<=23) && (minutos>=0) && (minutos<=59) ){
			return true;
		}
	}
	if(!silent){
		rotulo = rotulo?rotulo:this.findRotulo(field);
		this.showMessage(this.getI18NMessage('aHoraNoCampo')+' "'+(rotulo?rotulo:field.name)+'" '+this.getI18NMessage('naoEValida')+'!', null, field);
		if(this.canHaveFocus(field)){
			this.focusSafe(field);
		}
	}
	return false;
} 


cjf.isZero = function(field, silent, rotulo){
	var value = field.value.replace(/,/,'.');
	var number = parseFloat(value);	
	var zero = isNaN(number) || number==0;
	if(zero && !silent){
		rotulo = rotulo?rotulo:this.findRotulo(field);
		this.showMessage(this.getI18NMessage('campo')+' "'+(rotulo?rotulo:field.name)+'" '+this.getI18NMessage('naoPodeSerZero')+'!', null, field); 
		if(this.canHaveFocus(field)){
			this.focusSafe(field);
		}
		return true;
	}
	return zero;
} 

cjf.isSelected = function(field, silent, rotulo){
	var selected = field.selectedIndex!=-1 && field.options[field.selectedIndex].value;
	if(!selected && !silent){
		rotulo = rotulo?rotulo:this.findRotulo(field);
		this.showMessage(this.getI18NMessage('campo')+' "'+(rotulo?rotulo:field.name)+'" '+this.getI18NMessage('deveSerSelecionado')+'!', null, field); 
		if(this.canHaveFocus(field)){
			this.focusSafe(field);
		}
		return false;
	}
	return selected;
} 

cjf.isChecked = function(field, silent, rotulo){
	if(field.length){
		for(var i=0; i<field.length; i++){
			if(field[i].checked){
				field = field[i];
				break;
			}
		}
	}
	if(!field.checked && !silent){
		rotulo = rotulo?rotulo:this.findRotulo(field);
		this.showMessage(this.getI18NMessage('campo')+' "'+(rotulo?rotulo:field.name)+'" '+this.getI18NMessage('deveSerSelecionado')+'!', null, field); 
		if(this.canHaveFocus(field)){
			this.focusSafe(field);
		}
	}
	return field.checked;
} 

cjf.verificaIntervaloNumero = function(field, interval1, interval2 , silent, rotulo){
	var value = parseFloat(field.value.replace(/\,/g,'.'));
	var x1 = parseFloat(interval1);
	var x2 = parseFloat(interval2);
	if(value<x1 || value>x2){
		if(!silent){
			rotulo = rotulo?rotulo:this.findRotulo(field);
			this.showMessage(this.getI18NMessage('valor')+' "'+(rotulo?rotulo:field.name)+'" '+this.getI18NMessage('deveSer')+' '+this.getI18NMessage(value<x1?'maior':'menor')+ ' '+this.getI18NMessage('que')+' "'+(value<x1?interval1:interval2)+ '"!', null, field);
			if(this.canHaveFocus(field)){
				this.focusSafe(field);
			}
		}
		return false;
	}
	return true;
}

cjf.verificaSubTotais = function(field){
	var valueTotal = parseFloat(field.value.replace(/\./g,'').replace(/,/, '.'));
	var sum = 0; var i=1;
   	for(; i<arguments.length; i++){
   		if(!arguments[i].type){
   			break;
   		}
   		var value = arguments[i].value;
   		if(value){
	      	sum += parseFloat(value.replace(/\./g,'').replace(/,/, '.'))*10000;
	    }
    }
    sum/=10000;
	if(sum!=valueTotal){
		var silent = i<arguments.length?arguments[i++]:null;
		if(!silent){
			var rotulo = i<arguments.length?arguments[i++]:null;
			rotulo = rotulo?rotulo:this.findRotulo(field);
			this.showMessage(this.getI18NMessage('campo')+' "'+(rotulo?rotulo:field.name)+'" '+this.getI18NMessage('comErroTotalizacao')+'!', null, field); 
			if(this.canHaveFocus(field)){
				this.focusSafe(field);
			}
		}
		return false;
	}
	return true;
}

cjf.comparaDatas = function(field1, field2, operator, silent){
	if(this.isValideDate(field1, silent) && this.isValideDate(field2, silent)){
		var date1 = new Date(field1.value.substr(6),field1.value.substr(3,2)-1,field1.value.substr(0,2));
		var date2 = new Date(field2.value.substr(6),field2.value.substr(3,2)-1,field2.value.substr(0,2));
		operator = this.fixOperator(operator);
		if(!eval('date1.getTime()'+operator+'date2.getTime()')){
			if(!silent){
				//var rotulo1 = this.findRotulo(field1);
				//var rotulo2 = this.findRotulo(field2);
				var rotulo1 = field1.id;
				var rotulo2 = field2.id;				
				var comparacao = this.getComparacao(operator); 
				this.showMessage(this.getI18NMessage('data')+' "'+(rotulo1?rotulo1:field1.name)+'" '+this.getI18NMessage('deveSer')+' '+comparacao+ ' '+this.getI18NMessage('aData')+' "'+(rotulo2?rotulo2:field2.name)+ '"!', null, field1);
				if(this.canHaveFocus(field1)){
					this.focusSafe(field1);
				}
			}
			return false;
		}
		return true;
	}
	return false;
}

cjf.fixOperator = function(operator){
	if(!operator){
		return '>';
	}
	operator = this.allTrim(operator.toLowerCase());
	switch (operator){ 
	   case '='  : 
	   case 'igual'  : 
	      return '=='; 
	   case '<>' : 
	   case 'diferente' : 
	      return '!='; 
	   case 'maior' : 
	   case 'maiorque' : 
	      return '>'; 
	   case 'maiorouigual' : 
	   case 'maiorouigualque' : 
	   case 'maiorigual' : 
	      return '>='; 
	   case 'menor' : 
	   case 'menorque' : 
	      return '<'; 
	   case 'menorouigual' : 
	   case 'menorouigualque' : 
	   case 'menorigual' : 
	      return '<='; 
	   default : 
	      return operator;  
	} 
}

cjf.getComparacao = function(operator){
	switch (operator){ 
	   case '='  : 
	   case '==' : 
	      return this.getI18NMessage('igual'); 
	   case '!=' : 
	   case '<>' : 
	      return this.getI18NMessage('diferente'); 
	   case '>' : 
	      return this.getI18NMessage('maiorQue'); 
	   case '>=' : 
	      return this.getI18NMessage('maiorIgualQue'); 
	   case '<' : 
	      return this.getI18NMessage('menorQue'); 
	   case '<=' : 
	      return this.getI18NMessage('menorIgualQue'); 
	   default : 
	      return '\"ERRO NO USO DA FUN??O\"'; 
	} 
}

cjf.findRotulo = function(field){
	if(typeof(field.rotulo)!='undefined'){
		return field.rotulo;
	}
	var parentNode = field.parentNode;
	while(parentNode.tagName.toUpperCase()!='TD'){
		parentNode = parentNode.parentNode;
	}
	var previousSibling = parentNode.previousSibling;
	if(!previousSibling.innerHTML){
		previousSibling = previousSibling.previousSibling;
	}
	if(previousSibling){
		var rotulo = this.getInnerHTML(previousSibling).replace(/[\:\*]/g,'');
		var lower = rotulo.toLowerCase();
	 	if(lower.indexOf('<input')==-1 && lower.indexOf('<textarea')==-1 && lower.indexOf('<select')==-1){
	 		return rotulo;
	 	}
	}
	return '';
}

cjf.validoCNPJ = function(field, silent, rotulo) {
	var cnpj = field.value;
	var valido = cnpj && (cnpj = cnpj.replace(/[^0-9]/g,'')).length == 14;
	if(valido){
		valido = false;
		var soma = 0;
    	for (var i = 0, j = 5; i < 12; i++) {
        	soma += j-- * (cnpj.charAt(i) - '0');
	        if (j < 2) {
    	        j = 9;
        	}
	    }
    	soma = 11 - (soma % 11);
	    if (soma > 9) {
    	   	soma = 0;
	    }
    	if (soma == (cnpj.charAt(12) - '0')) {
       		soma = 0;
	       	for (var i = 0, j = 6; i < 13; i++) {
    	   	    soma += j-- * (cnpj.charAt(i) - '0');
       		    if (j < 2) {
       	    	    j = 9;
	            }
    	    }
        	soma = 11 - (soma % 11);
	        if (soma > 9) {
    	        soma = 0;
        	}
	        if (soma == (cnpj.charAt(13) - '0')) {
    	        valido = true; //CNPJ V?lido
        	}
    	}
    }
	if(!valido && !silent){
		rotulo = rotulo?rotulo:this.findRotulo(field);
		this.showMessage(this.getI18NMessage('campo')+' "'+(rotulo?rotulo:field.name)+'" '+this.getI18NMessage('invalido')+'!', null, field); 
		if(this.canHaveFocus(field)){
			this.focusSafe(field);
		}
	}
	return valido;
}

cjf.validoCPF = function(field, silent, rotulo) {
	var cpf = field.value;
	
	var valido = cpf && (cpf = cpf.replace(/[^0-9]/g,'')).length == 11
	if(valido){
		valido = false;
		var soma = 0;
	    for (var i = 0; i < 9; i++) {
			soma += (10 - i) * (cpf.charAt(i) - '0');
	    }
		soma = 11 - (soma % 11);
	    if (soma > 9) {
			soma = 0;
	    }
	    if (soma == (cpf.charAt(9) - '0')) {
			soma = 0;
			for (var i = 0; i < 10; i++) {
			    soma += (11 - i) * (cpf.charAt(i) - '0');
			}
			soma = 11 - (soma % 11);
			if (soma > 9) {
			    soma = 0;
			}
			if (soma == (cpf.charAt(10) - '0')) {
		    	valido = true; //CPF V?lido
		    	//field.value = cpf; 
			}
	    }  
	}
	if(!valido && !silent){
		rotulo = rotulo?rotulo:this.findRotulo(field);
		this.showMessage(this.getI18NMessage('campo')+' "'+(rotulo?rotulo:field.name)+'" '+this.getI18NMessage('invalido')+'!', null, field); 
		if(this.canHaveFocus(field)){
			this.focusSafe(field);
		}
	}
	return valido;
}

cjf.validoRG = function(fieldRG, fieldPais, silent, rotulo) {
	var valido = true;
	for (i = 0; i < fieldRG.value.length; i++){
		var ch = fieldRG.value.substr(i,i+1);
		ch = ch.charCodeAt(0);
		if (!((ch >= 48 && ch <= 57) || (ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122))) {
			valido = false;
			break;
		}
	}
	
	if(!valido && !silent){
		rotulo = rotulo?rotulo:this.findRotulo(fieldRG);
		this.showMessage(this.getI18NMessage('campo')+' "'+(rotulo?rotulo:fieldRG.name)+'" '+this.getI18NMessage('invalido')+'!', null, fieldRG); 
		if(this.canHaveFocus(fieldRG)){
			this.focusSafe(fieldRG);
		}
	}
	return valido;
}

/**
 *    <<< Mascara >>>
 *      onkeydown e onkeyup
 */

//Onkeydown - não tolera caracteres não números (exceto rg) e limita tamanho do campo
cjf.somentenumeros = function(field, mascara ,event){
	var lower = mascara.toLowerCase();
	var tecla = event.keyCode?event.keyCode:event.which;

	//define tamanho do campo
	if(lower=='cnpj'){
		  if(field.maxLength!=18){
			  field.maxLength=18;
		  }
  	}else if(lower=='cpf'){
		  if(field.maxLength!=14){
			  field.maxLength=14;
		  }
	}else if(lower=='cep'){
		  if(field.maxLength!=10){
			  field.maxLength=10;
		  }
	}else if(lower=='ncm'){
		  if(field.maxLength!=10){
			  field.maxLength=10;
		  }
	}else if(lower=='data' || lower=='dataanolivre'){
		  if(field.maxLength!=10){
			  field.maxLength=10;
		  }
	}else if(lower=='horario'){
		  if(field.maxLength!=5){
			  field.maxLength=5;
		  }	  
	}else if (lower=='rg'){
  	  if(!field.maxLength!=15){
			field.maxLength=15;
	  }
	} 
	
    //Caso já tenha chegado ao limite, sair
    if (field.value.length >= field.maxLength){ 	    
      if(tecla==8 ||tecla==46 || tecla==35 || tecla==36 || tecla==37 || tecla==39 ){
		  return true;
	  }  else {
	      return false;
	  }    
    }	


	//Como rg não tem formatação específica, apenas limita seu tamanho
	// alem disso, tem o cpf para estrangeiros
	if( ( ( lower!='rg')&&(lower!='cpf') )|| 
	    ( (lower == 'cpf')&&(this.getFormPrincipal().estrangeiro['0'].checked) )
	  ){
	 
	  //Este if bloqueia caracteres não numéricos,
	  // exceto backspace(8), end(35), home(36), left(37), right(39), delete(46)
	  if ( tecla < 48 || (tecla > 57 && tecla < 96) || tecla > 105 ){
	    if(tecla==8 ||tecla==46 || tecla==35 || tecla==36 || tecla==37 || tecla==39 ){
			return true;
		}
		return false;
	  } 
	}
	
    return field.value;
}

//Onkeyup - reformata a string formada
cjf.mascara = function(field, mascara ,event){
  var lower = mascara.toLowerCase();
  var tecla = event.keyCode?event.keyCode:event.which;

  	
  //Este if bloqueia caracteres não numéricos,
  // exceto backspace(8), end(35), home(36), left(37), right(39), delete(46)
  if ( tecla < 48 || (tecla > 57 && tecla < 96) || tecla > 105 ){
	if(tecla==8 ||tecla==46 || tecla==35 || tecla==36 || tecla==37 || tecla==39 ){
	    return true;
	}
	return false;
  }

  //Não usa função txtBoxFormat
  if ( ( lower=='data') || (lower.indexOf('dinheiro')==0) || (lower=='numero')  || ( lower=='rg') )  {
	if(lower=='data' && field.value.length>4 && field.value.length<10){
		  field.value+=this.anoBase;
	}
	if ( lower=='dinheiro' ) {
	    
	    if(field.value){
	       var tmp = field.value;
	       var virgula = tmp.indexOf(',');
	       if ( virgula != tmp.length - 3 ){
	         if (virgula != -1){
	           //tira a virgula
	            tmp = tmp.toString().replace( ",", "" );
	         }
	         //coloca a virgula
	         var valor = tmp.substring(0, tmp.length-2)+','+tmp.substring(tmp.length-2, tmp.length);
	         
	         field.value = valor; 
	       }
	    }
	}
    if (lower=='numero'){
      var tmp = field.value;
      if ( (tmp.indexOf('0') == 0) && (tmp.length > 1) )
        tmp = tmp.substring(1, tmp.length);
        
      field.value = tmp;
    	    	
	}
	/*if (lower=='rg'){
	  
	}*/
	

  }else { //usa a função txtBoxFormat
	  if(lower=='cnpj'){
		  mascara = '99.999.999/9999-99';
  	  }else if(lower=='cpf'){
		  mascara = '999.999.999-99';
	  }else if(lower=='cep'){
		  mascara = '99999-999';
	  }else if(lower=='ncm'){
		  mascara = '9999.99.99';
	  }else if(lower=='data' || lower=='dataanolivre'){
		  mascara = '99/99/9999';
	  }else if(lower=='horario'){
		  mascara = '99:99';
	  }else if(lower=='fone'){
		  mascara = '999-9999';
	  }else if(lower=='celular'){
		  mascara = '9999-9999';
	  }
	  txtBoxFormat(field, mascara ,event); // definido no arquivo "formata.js"
  }
  

		
  if(field.value.length==field.maxLength){
 	  this.nextFocusField = field;
	  this.setTimeout("cjf.nextFocus(cjf.nextFocusField)",60);
  }
  
  return field.value;
}

/*cjf.formataRG = function(field, event){
	var tecla = event.keyCode?event.keyCode:event.which;
	tecla = tecla>=97 && tecla<=122?tecla-(97-65):tecla;
	if (tecla < 48 || (tecla > 57 && tecla<65) || tecla>90 || field.value.length >= field.maxLength){
		return false;
	}
	var value = field.value.replace(/\W/g,'');
	value += String.fromCharCode(tecla);
	if(value.length>=1){
		value=value.substr(0,1)+'.'+value.substr(1);
	}
	if(value.length>=5){
		value=value.substr(0,5)+'.'+value.substr(5);
	}
	if(value.length>=9){
		value=value.substr(0,9)+'-'+value.substr(9);
	}
	field.value = value;
	return false;
}

cjf.duasCasasDecimais = function(value){
	var value = value?value:this.value.replace(/\D/g,'');
	if(value.length==1){
		value = '0,0'+value;
	}else if(value.length==2){
		value = '0,'+value;
	}else{
		value = value.substring(0, value.length-2)+','+value.substring(value.length-2);
	}
	return this.value?this.value=value:value;
}

cjf.tresCasasDecimais = function(value){
	var value = value?value:this.value.replace(/\D/g,'');
	if(value.length==1){
		value = '0,00'+value;
	}else if(value.length==2){
		value = '0,0'+value;
	}else if(value.length==3){
		value = '0,'+value;		
	}else{
		value = value.substring(0, value.length-3)+','+value.substring(value.length-3);
	}
	return this.value?this.value=value:value;
}

cjf.quatroCasasDecimais = function(value){
	var value = value?value:this.value.replace(/\D/g,'');
	if(value.length==1){
		value = '0,000'+value;
	}else if(value.length==2){
		value = '0,00'+value;
	}else if(value.length==3){
		value = '0,0'+value;
	}else if(value.length==4){
		value = '0,'+value;		
	}else{
		value = value.substring(0, value.length-4)+','+value.substring(value.length-4);
	}
	return this.value?this.value=value:value;
}*/


/**
 *    <<< TextArea >>>
 */
 
cjf.ajustaTextArea = function(textArea, maxLength, maxHeight){
    if(maxLength!=-1 && textArea.value.length>maxLength){
		textArea.value =  textArea.value.substring(0, maxLength);

		//this.showMessage(this.getI18NMessage('campo')+' "'+field.name+'" '+this.getI18NMessage('invalido')+'!', null, field); 

		alert(this.getI18NMessage('excedido')+' '+maxLength+' '+this.getI18NMessage('caracteres')+'!');
    	return false;
    }
	if(!textArea.cjfTextAreaMinHeight){
		textArea.cjfTextAreaMinHeight = textArea.offsetHeight;
	}
	var minHeight = textArea.cjfTextAreaMinHeight;
	if(textArea.scrollHeight <= textArea.clientHeight && textArea.clientHeight > minHeight){
		textArea.style.height = minHeight;
	}
	if(textArea.scrollHeight > textArea.clientHeight && textArea.scrollHeight < maxHeight){
		textArea.style.height = textArea.offsetHeight + textArea.scrollHeight - textArea.clientHeight;
	}
	return true;
}  

cjf.flipTextArea = function(textArea, maxHeight){
	if(!textArea.cjfTextAreaMinHeight){
		textArea.cjfTextAreaMinHeight = textArea.offsetHeight;
	}
	this.ajustaTextArea(textArea, -1, !textArea.cjfFlip?maxHeight:textArea.cjfTextAreaMinHeight);
	textArea.cjfFlip=!textArea.cjfFlip?true:false
}  

cjf.getI18NMessage = function(key){
	var i18nMsg;
	if(!(i18nMsg=this.i18nMessages[key])){
		alert('I18N: Message for key "'+key+'" not found!');
	}
	return i18nMsg;
}

cjf.i18nMessages = []; //preenchido por I18N.getJsArray(..) no index.jsp e popup.jsp

cjf.ajusteMozilla = function(frame){ //chamado por cjf.formLoad(..)
	if(!this.IE){
		var divs = frame.document.getElementsByTagName('DIV');
		for(var i=0; i<divs.length; i++){
			var div = divs[i];
			if(div.className=='cssTabelaScroll'){
				div.style.height = frame.document.body.clientHeight*0.50;
			}else if(div.className=='cssDivTabelaScroll'){
				div.style.height = frame.document.body.clientHeight*0.75;
			}
		}
		var tds = frame.document.getElementsByTagName('TD');
		for(var i=0; i<tds.length; i++){
			var td = tds[i];
			if(td.id && td.id.indexOf('cjfSubCadastroBotaoAdicionar')==0){
				td.onclick();
				this.getElement(frame,'cjfSubCadastroBotaoCancelar_'+td.id.substring(td.id.indexOf('_')+1) ).onclick();
			}
		}		
	}
	//this.showBorders(frame, 1);
}


