var ua=navigator.userAgent.toLowerCase();
var IE=/msie/.test(ua);
var GK=/gecko/.test(ua);

function openEditTemplate(id_edition, id_tmp, id_departament) {
	var id_fk_template=document.forms[0].id_fk_template.value; 
	var _dir=( id_fk_template>0 ? '/marketing/issues/showEditTemplate?m=2&' : '/marketing/issues/showSelectTemplate?'); 
	abrirJanelaModal(_dir+'id='+document.forms[0].id_fk_template.value+'&id_edition='+id_edition+'&id_tmp='+id_tmp+'&id_departament='+id_departament, '620', '500','templates','yes');
}

function authorize(authorize, id) {
	if (authorize>0) {
		var id_email= parseInt(document.getElementById('rejectEmail').value)+0;
		id_email = id_email;
		if (id_email>0)
			document.location='?action=1&authorize='+authorize+'&id='+id+'&id_email='+id_email; 
		else {
			alert('Please select a rejection email');
			document.getElementById('rejectEmail').focus();
		}
	} else
		document.location='?action=1&authorize='+authorize+'&id='+id;
}


var grp;
var not_remove = new Array();
function markSelected(def_lang) {
	combo = document.getElementById('default_language');
	if (combo) {
		while (combo.options.length) combo.options[combo.options.length-1] = null;
		for (i=0; i<document.forms[0].elements.length; i++) {
			if (document.forms[0].elements[i].id=='check_langs' && document.forms[0].elements[i].checked==true) {
				val = document.forms[0].elements[i].value;
				val = document.forms[0].elements[i].value.split(';');
				if (def_lang==val[0]) sel = 1;
				else sel = 0;
				combo.options[combo.options.length] = new Option(val[1], val[0], sel);	
			}
		}
	}
}

function sendInboundMessage(msg) {
	if (document.forms[0].answer.value=='' || document.forms[0].answer.value.length==0) {
		if (confirm(msg)) document.forms[0].submit();
		else return false;
	} else document.forms[0].submit();
	return true;
}

function validMaxSelected(elementName, max, msg) {
	var count = 0;
	for (var i=0; i<document.forms[0].elements.length; i++) {
		if (document.forms[0].elements[i].name == elementName) {
			for(var j=0; j<document.forms[0].elements[i].options.length; j++) {
				if (document.forms[0].elements[i].options[j].selected) {
					count++;
					if (count>max) {
						alert(msg);
						return false;
					}
				}
			}
			return true;
		}
	}
	return true;
}

function getShortCutKeyPress(e, obj, id_hidden, enter) {
	if (window.navigator.appName == 'Microsoft Internet Explorer') e = window.event;
	if (obj.value.length > 0 && e.keyCode!=9) obj.value = '';
	if (e.keyCode == 13) obj.value = enter;
	if (e.keyCode) document.getElementById(id_hidden).value = e.keyCode;
 	obj.value = obj.value.toUpperCase();
}

function getShortCutKeyUp(e, obj, id_hidden, space) {
	if (window.navigator.appName == 'Microsoft Internet Explorer') e = window.event;
	if (e.keyCode) {
		if (e.keyCode == 32) obj.value = space;
		document.getElementById(id_hidden).value = e.keyCode;
		obj.value = obj.value.toUpperCase();
	} else obj.value = '';
}

function openDialogReport1() {
	if (document.forms[0].print.checked==true) document.forms[0].target='self';
	else document.forms[0].target='';
}

function openDialogReport2() {
	if (document.forms[0].print.checked==true && document.forms[0].download.checked==false) document.forms[0].target='self';
	else document.forms[0].target='';
}

function addRule(line){
	var qtd;
	qtd = document.forms[0].qtd_rule.value;
	field = "rule_"+qtd;
	document.forms[0].qtd_rule.value = parseInt(document.forms[0].qtd_rule.value) + 1;
	qtd = parseInt(qtd) + 1;
	next_field = "rule_"+qtd;
	if (line)
		document.getElementById(field).innerHTML += "<div id="+next_field+">"+document.getElementById('rule_g').innerHTML+"</div>";
	else
		document.getElementById(field).innerHTML += "<div id="+next_field+">"+document.getElementById('rule_0').innerHTML+"</div>";
}

function showSignature(tpl) {
	if (tpl == 0) {
		document.getElementById("signature").style.display='inline';
		//document.getElementById("answer").style.height='80%';
	} else {
		document.getElementById("signature").style.display='none';
		//document.getElementById("answer").style.height='100%';
	}

}

function Trim(str) {
	return str.replace(/^\s+|\s+$/g,"");
}

function showHideComboTpl(value) {
	if (value=='html') document.getElementById('combotpl').style.display='inline';
	else {
		document.getElementById('combotpl').style.display='none';
		document.forms[0].template.value='0';
		showSignature(0);
	}
}

//* Funções do knowledge usados no front-end do inbound  *//
function showQuestionsInb(id) {
	parent.frames.iquestions.location='/cc/knowledge/getQuestionsGridInb?know_category='+id;
}

function changeFolderCategoryInb(value) {
	parent.frames.iquestions.location="/cc/knowledge/getQuestionsGridInb";
	document.location="/cc/knowledge/getCategoriesInb?id_folder="+value;
}

function insertAnswerInb(id) {
	top.frames[0].frames.hiddenFrame.location="/cc/inbound/insertKnowAnswer?id="+id;
}
//****//

//## CHAT ##
function openChat(msg) {
	if (document.forms[0].id_category.value=='-2') {
		alert(msg);
	} else {
		abrirJanelaModal('/cc/chat/open?id_group='+document.forms[0].id_group.value+'&id_category='+document.forms[0].id_category.value,'860','670','chat_attendance','no');
		window.close();
	}
}

function getSendMessage(event) {
	if (window.navigator.appName == 'Microsoft Internet Explorer') event = window.event;
	if (!event.shiftKey && !event.shiftLeft) 
		if (event.keyCode == 13) sendChatMessage();
}

function sendChatMessage() {
	document.forms[0].message.value = document.forms[0].writer.value;
	document.forms[0].writer.value = '';
	document.forms[0].submit();
}

function updateView(notReload) {
	parent.frames.iview.location.reload();
	parent.frames.iview.scrollTo(0,10000000);
}

function changeSession(id_transaction, indice) {
	unsetNewMessage(id_transaction);
	if (parent.frames.iwrite.document.forms[0].id_transaction.value != id_transaction) {
		parent.frames.hiddenFrame.location = '/cc/chat/users?id_transaction='+id_transaction;
		parent.frames.iview.location = 'http://chatv3.gtossulino.desenv.com/v3/view.php?id_transaction='+id_transaction;
		parent.frames.iwrite.document.forms[0].id_transaction.value=id_transaction;
	}
	for (j=0; j<document.getElementById("qtd_users").value; j++) {
		if (j != indice) document.getElementById("s_name["+j+"]").style.color='darkblue';
		else document.getElementById("s_name["+j+"]").style.color='red';
	}
	parent.frames.iwrite.document.forms[0].writer.focus();
}

function setNewMessage(id_transaction) {
	var nm_objeto = "new_message_"+id_transaction;
	parent.frames.iusers.document.getElementById(nm_objeto).style.display='inline';
}

function unsetNewMessage(id_transaction) {
	var nm_objeto = "new_message_"+id_transaction;
	parent.frames.iusers.document.getElementById(nm_objeto).style.display='none';
}

function endSession(id_transaction, id_client) {
	abrirJanelaModal('/cc/chat/endSession?id_transaction='+id_transaction+'&id_client='+id_client,'330','200','chat_end_session','no');
}
// ####
function openInbound(msg) {
	if (document.forms[0].id_category.value=='-2') {
		alert(msg);
	} else {
		abrirJanelaModal('/cc/inbound/open?id_group='+document.forms[0].id_group.value+'&id_category='+document.forms[0].id_category.value,'860','670','inbound_answer','no');
		window.close();
	}
}

function changeFolderCategory(value) {
	parent.frames.iquestions.location="/cc/knowledge/getQuestionsGrid";
	parent.frames.ianswer.location="/cc/knowledge/getAnswers";
	document.location="/cc/knowledge/getFolderTree?id_folder="+value;
}

function selectFile(document, hidden, id, file, getid) {
	hidden.value=id;
	if (getid==1)
		document.getElementById("div_file").innerHTML=file;
	else if (getid==2)
		opener.document.forms[0].submit();
	parent.close();
}

function showQuestions(id) {
	parent.frames.ianswer.location="/cc/knowledge/getAnswers";
	parent.frames.iquestions.location='/cc/knowledge/getQuestionsGrid?know_category='+id;
}

function showAnswer(id) {
	parent.frames.ianswer.location='/cc/knowledge/getAnswers?id='+id;
}

function replaceAnswer(id_file) {
	if (id_file) parent.opener.document.forms[0].answer_file.value=id_file;
	parent.opener.document.forms[0].answer.value=parent.frames.ianswer.document.forms[0].answer.value;
	parent.close();
}

function dumpProps(obj, parent) {
	for (var i in obj) {
		if (parent) { msg = parent + "." + i + "\n" + obj[i]; } else { var msg = i + "\n" + obj[i]; }
		
		if (!confirm(msg)) { return; }
		
		if (typeof obj[i] == "object") {
				if (parent) { dumpProps(obj[i], parent + "." + i); } else { dumpProps(obj[i], i); }
		}
	}
	return;
}

function sendToAnswer(id_file) {
	answerEditor = parent.opener.document.forms[0].answer;
	answerKnow = document.forms[0].answer;

	mimeType = parent.opener.document.forms[0].mime_type[0];

	//answerEditorWy = parent.opener.document.getElementById('wysiwygcc');
	//answerEditorWy.value = answerEditor.value + answerKnow.value;
	//answerEditor.value = answerEditor.value + answerKnow.value;

	answerEditor.value = answerKnow.value;
	
	parent.close();
	if (mimeType.checked) {
		parent.opener.showHideTextareaAnswer('html', 1);
	}
}

function insertAnswerAtCursor(id_file) {
	myDocument = parent.opener.document;
	myField = myDocument.forms[0].answer;
	if (id_file) myDocument.forms[0].answer_file.value=id_file;
	myValue = parent.frames.ianswer.document.forms[0].answer.value;
	if (myDocument.selection) { //IE support
		myField.focus();
		sel = myDocument.selection.createRange();
		sel.text = myValue;
	} else if (myField.selectionStart || myField.selectionStart == '0') { //MOZILLA/NETSCAPE support
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		myField.value = myField.value.substring(0, startPos)
		+ myValue
		+ myField.value.substring(endPos, myField.value.length);
	} else {
		myField.value += myValue;
	}
	parent.close();
}


function insertSalut(salut, nome) {
	if (salut.length>0) {
		document.forms[0].salut_name.value=salut+" ";
		if (nome) document.forms[0].salut_name.value+=nome+", ";
		else document.forms[0].salut_name.value+=", ";
	} else
		if (nome) document.forms[0].salut_name.value=nome+", ";
		else document.forms[0].salut_name.value="";
}

//disabilita ou habilita um form através de um checkbox
function disableForm(check) {
	if (check.checked) value = true;
	else value = false;
	for (i=0; i<document.forms[0].elements.length; i++)
		if (document.forms[0].elements[i] != check && document.forms[0].elements[i].type != 'hidden')  document.forms[0].elements[i].disabled = value;
	
}

//Insere em um elemento do form aonde estiver o cursor do mouse.
function insertAtCursor(myField, myValue, myDocument) {
	if (myDocument.selection) { //IE support
		myField.focus();
		sel = myDocument.selection.createRange();
		sel.text = myValue;
	} else if (myField.selectionStart || myField.selectionStart == '0') { //MOZILLA/NETSCAPE support
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		myField.value = myField.value.substring(0, startPos)
		+ myValue
		+ myField.value.substring(endPos, myField.value.length);
	} else {
		myField.value += myValue;
	}
}

//Oculta/exibe um elemento HTML
function showHideElement(id,img){
	var element = document.getElementById(id);
	element.src='/arquivos/skin2/geral/'+img;
}

//** FUNCOES DO RELOGIO DO SISTEMA
function MakeArrayday(size) {
	this.length = size;
	for(var i = 1; i <= size; i++) this[i] = "";
	return this;
}

function MakeArraymonth(size) {
	this.length = size;
	for(var i = 1; i <= size; i++) this[i] = "";
	return this;
}

function funClock() {
	var runTime = new Date();
	var hours = runTime.getHours();
	var minutes = runTime.getMinutes();
	var seconds = runTime.getSeconds();
	var clock;
	var movingtime;
	if (minutes <= 9) minutes = "0" + minutes;
	if (seconds <= 9) seconds = "0" + seconds;
	movingtime = hours + ":" + minutes + ":" + seconds;
	clock = document.getElementById('clock');
	clock.innerHTML = movingtime;
	setTimeout("funClock()", 1000);
}
//**


// Funcao usada no listbox RECORRENCIA na caixa de dialogo INSERIR COMPROMISSO do modulo OFFICE/AGENDA 
function validarRecorrencia( form ){
	var listbox = form.repeticao;
	alert( form[0].type);
	switch( listbox.value ){
		case '0':
		case '2':{y = form.length;} break;
		case '1':{alert(1);}break;
		case '3':{alert(3);}break;
	}
}

function remover_dashboard_avisos(){redirect('/office/dashboard/showAvisos?id='+getDados('grid'));}
function fecharBusca(id) {document.forms[0].elements.id.value=getDados('grid');}

//Abri uma caixa de dialogo de algum item do sistema
function abrirDialogItem(modulo,funcionalidade,largura,altura,id){
	url ='/'+modulo+'/'+funcionalidade+'/showDialog?id='+id+'&altura='+altura+'&largura='+largura;
	abrirJanelaModal(url, largura,altura,'item','yes');
}

function pontorecado(id) {
	url = '/office/ponto/showCorrecao?id='+id+'&rec='+getDados('grid');
	abrirJanelaModal(url, 530, 350);
}

// Prepara para inserir item nos favoritos
function confirmarFavorito( modulo,funcionalidade,largura,altura,id ){
	var favorito = prompt(JS_ADD_FAVORITES, "");
	if( favorito ) document.location='/office/favoritos/inserirFavorito?modulo='+modulo+'&funcionalidade='+funcionalidade+'&largura='+largura+'&altura='+altura+'&id='+id+'&favorito='+favorito;
}

// Abre prompt para usuario digitar o nome de uma nova categoria
function inserirCategoriaFavorito(id){
	var favorito = prompt(JS_ADD_CAT_FAVORITES, "");
	if( favorito ) document.location='/office/favoritos/showSetupCategorias?frame=1&id='+id+'&action=1&categoria='+favorito;
}

function abrirJanelaModal(url,largura,altura,nome,rolagem) 
{
	var esquerda = (screen.width - largura) / 2;
	var cima = (screen.height - altura) / 2 -50;
	window.open(url,nome,'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=' + rolagem + ',resizable=yes,copyhistory=no,top=' + cima + ',left=' + esquerda + ',width=' + largura + ',height=' + altura);
}


function abrirJanela(url, largura, altura){window.open(url,'','width='+largura+',height='+altura+',toolbar=yes,resizable=1,location=0,status=yes,menubar=yes,scrollbars=yes');}
function abrirJanelaModalex(url, largura, altura, obj){abrirJanelaModal(url+'?id='+obj.id, largura, altura)}
function abrirJanelaModalReload(url, largura, altura){
	abrirJanelaModal(url, largura, altura);
	document.location=document.location;
}

function marcarComoLido(msg,url,id){
	url =url+'?id='+id+'&lido=1';
	if( confirm( msg ) ) document.location=url
}

function adicionarContatos(msg,url,id,param){
	url =url+'?id='+id+param;
	if( confirm( msg ) ) abrirJanelaModal(url, 350, 210);
}

function remove(url) { if( confirm(JS_REMOVER_CHILD) ) document.location=url }
function removefull(url) { if( confirm(JS_REMOVER_PERMANENTE) ) document.location=url }
function lixeira(url) { if( confirm(JS_REMOVER) ) document.location=url }

//** METODOS PARA A LIXEIRA **//
//Envia um item para a lixeira indenpente do modulo
function enviarLixeira(modulo,funcionalidade,id,adicional){
	url='/'+modulo+'/enviarLixeira?modulo='+modulo+'&funcionalidade='+funcionalidade+'&id='+id;
	if(adicional) url = url + '&' + adicional;
	if( confirm(JS_REMOVER) ) document.location=url
}

//Envia um item para a lixeira independente do modulo executando um metodo
function enviarLixeiraParam(modulo,funcionalidade,id,param){
	url ='/'+modulo+'/'+funcionalidade+'/index?id='+id+'&param='+param;
	if( confirm(JS_REMOVER) ) document.location=url
}
//Restaura item da lixeira
function restaurar_da_lixeira(filtro,idtab,tname){ redirect('/lixeira/index?exec=1&frame=1&filtro='+filtro+'&idtab='+idtab+'&tname='+tname+'&id='+getDados('grid'));}
//Limpa toda a lixeira
function limpar_da_lixeira(filtro,idtab,tname){ redirect('/lixeira/index?exec=2&frame=1&filtro='+filtro+'&idtab='+idtab+'&tname='+tname+'&id='+getDados('grid')); }
//Envia um item para a lixeira indenpente do modulo
function enviarContaParaLixeira(modulo,funcionalidade,id,adicional){
	url='/setup/sinbound/enviarParaLixeira?modulo='+modulo+'&funcionalidade='+funcionalidade+'&id='+id;
	if(adicional) url = url + '&redir=' + adicional;
	if( confirm(JS_REMOVER) ) document.location=url;
}
//Envia um item do perfil para a lixeira
function enviarPerfilParaLixeira(modulo,funcionalidade,id,adicional){
	url='/setup/smodulos/scc/sinbound/enviarPerfilParaLixeira?modulo='+modulo+'&funcionalidade='+funcionalidade+'&id='+id;
	if(adicional) url = url + '&redir=' + adicional;
	if( confirm(JS_REMOVER) ) document.location=url;
}
//Envia um item para a lixeira indenpente do modulo
function enviarParaLixeira(modulo,funcionalidade,id,adicional){
	if (not_remove && not_remove[id]) {
		alert(JS_ERRO_REMOVER);
		return;
	}
 	loc = new String(document.location);
  	loc = loc.replace(/&/g,"*amp*");
	url='/lixeira/enviarParaLixeira?modulo='+modulo+'&funcionalidade='+funcionalidade+'&id='+id+'&loc='+loc;
	if(adicional) url = url + '&redir=' + adicional;
	if( confirm(JS_REMOVER) ) document.location=url;
}
//Envia um item para a lixeira indenpente do modulo
function removerDaSessao(id,url){
	url = url +'&id='+id;
	if( confirm(JS_REMOVER) ) document.location=url
}
//***

//Metodo usado para executar comandos no XTree
function executeXTree( id, caption, pai ){
	id_departamento  = id;
	id_pai = pai;
	departamento = caption;
}

//Metodo que redireciona navegador para excluir departamento
function remover_departamento(id){redirect('/setup/showDepartamentos?action=1&id='+id);}
//Metodo que redireciona navegador para excluir um grupo
function remover_grupo(id){	redirect('/setup/showClientes?action=1&id='+id);}
//Metodo que redireciona navegador para remover usuario
function remover_usuario(id){redirect('/setup/showUsuarios?action=1&id='+getDados('grid'));}

//Metodo que ativa/desativa filtro de usuario relacionados somente ao grupo raiz
function filtrar_usuarios( check,id ){
	if( check.checked ) redirect('/setup/usuarios/showUsuarios?id_departamento='+id+'&filtro=1');
	else redirect('/setup/usuarios/showUsuarios?id_departamento='+id+'&filtro=0');
}

// Metodo usado para executar comando ao dar duplo-clique sobre elemento Xtree
var OnDBLClick = '';
function XTreeOnDBLClick(  ){ if( OnDBLClick ) eval( OnDBLClick ); }

/*
Metodo usado para apresentar uma caixa de confirmacao para o usuario e
dependendo de sua escolha, realizar uma das operacoes passadas como parametro
*/
function confirmaOpcao(mensagem, opt_ok, opt_nok){if( confirm( mensagem ) ){ eval( opt_ok )}else{ eval( opt_nok ) }}
function confirmredirect(mensagem, url){if( confirm( mensagem ) ){document.location = url;}}
// Metodo usado para redirecionar o navegador cliente pra outro site
function redirect(url){ document.location = url; }

// Metodo usado para alterar a cor de uma linha de uma tabela no clique
var objLinha = null;
function salvarCelula( _objLinha ){
	if( objLinha!= null ) objLinha.className=objLinha.oldClass;
	objLinha = _objLinha;
	objLinha.oldClass=objLinha.className;
	objLinha.className='selected'
}

// Metodo usado para alterar a cor de uma linha de uma tabela no clique

var objLinhaTop = null;
function salvarCelulaTop( _objLinha ){
	if( objLinhaTop!= null ) objLinhaTop.style.backgroundColor='#2e86d0'
	objLinhaTop = _objLinha;
	objLinhaTop.style.backgroundColor='#AAAAAA'
}

// Metodo usado para alterar a cor de uma linha de tabela ao passar o mouse
function setarCor( obj_linha, cor){ objLinha.style.backgroundColor=cor; }

// Metodo utilizado para armazenar e recuperar dados de uma pagina em um array
var dados = new Array();
function getDados( index ){ return dados[index]; }
function setDados( index, valor ){ dados[index] = valor;}

//Funcao que recebe como parametro um form e marca ou desmarcar todos os checks
var checado = true;
function selecionarChecks( form ){
	count = form.length;
	for(i=1; i<count; i++)
		if( form.elements[i].type == 'checkbox') form.elements[i].checked=checado
	checado = ! checado;
}



// Funcoes para abrir layer
var vis=0;
function MM_findObj(n, d) { //v4.01
	var p,i,x;  if(!d) d=document;
	if((p=n.indexOf("?"))>0&&parent.frames.length) {
		d=parent.frames[n.substring(p+1)].document;
		n=n.substring(0,p);
	}
	if(!(x=d[n])&&d.all) x=d.all[n];
	for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
	if(!x && d.getElementById) x=d.getElementById(n);
	return x;
}

function MM_showHideLayers() { 
	var i,p,obj,args=MM_showHideLayers.arguments;
	if (vis==1) {
		vis=0;
		v='hide';
	} else {
		vis=1;
		v='show';
	}
	if ((obj=MM_findObj(args[0]))!=null) {
		if (obj.style) {
			obj=obj.style;
			v=(v=='show')?'visible':(v=='hide')?'hidden':v;
		}
		obj.visibility=v;
	}
}

function Selecao(layer,dest,tlink,turl,ttext,ttarget) {
	var doc=document.formulario;
	if (ttarget.value!='') targ=' target="'+ttarget.value+'" ';
	else targ='';
	if (turl.value!='http://' && turl.value!='') dest.value=dest.value+'<a href="'+turl.value+'"'+targ+'>'+ttext.value+'</a>';
	else dest.value=dest.value+'<a href="'+tlink.value+'"'+targ+'>'+ttext.value+'</a>';
	MM_showHideLayers(layer);

}

function selSiteRet() {
	//alert('chegou');
}

function selSite(u) {
	a = u.split('&');
	var d;
	for(var i=0; i<a.length; i++) if (a[i].substr(0,2)=='d=') { d=a[i].substr(2,100); break; }
	if (d) {
		d = d.split(';');
		sendRequest('/mcms/content/getSites?s=' + d[1], 'cmblang', 'selSiteRet', '');
	}
}

function selMiningFolder(u) {
	a = u.split('&');
	var d;
	for(var i=0; i<a.length; i++)
		if (a[i].substr(0,7)=='folder=') { d=a[i].substr(7,100); break; }

	if (d) {
		d = d.split(';');
		sendRequest('/mining/mining/?folder=' + d, 'cmblang', 'selSiteRet', '');
	}
}

// oculta as os campos de qtd no fidelity (asia)
function hideTextAmount(obj) {
	var objs = document.getElementsByTagName('INPUT');
	for (i=0; i<objs.length; i++)
		if (objs[i].id && objs[i].id.substr(0,4)=='qtd_') {
			var aux = objs[i].id;
			if (aux != 'qtd_' + obj.value)
 				document.getElementById(objs[i].id).disabled=true;
 			else
				document.getElementById(objs[i].id).disabled=false;
		}
}

// calcula os pontos * qtd no fidelity (asia)
function calcPointsExchange(obj,points) {
	var id = obj.id.substr(4,obj.id.length);
	if (obj.value == '') var val = 0;
	else var val = obj.value * points;
	document.getElementById('amount_' + id).innerHTML=val;
}

// le somente numeros  Uso: onKeyPress='return getNumbers(event);'
function getNumbers(e) {
	var whichCode = (window.Event) ? e.which : e.keyCode;
	if (whichCode == 8 || whichCode == 13 || whichCode == 0 ) return true;
	key = String.fromCharCode(whichCode);  // Get key value from key code
	var strCheck = "0123456789";
	if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
	return true;
}

function countChars(obj, e, max) {
	if (max != 0) {
		var e = e ? e : window.event;
		var target = e.target ? e.target : e.srcElement;
		var evt = e ? e : window.event;
		var key = String.fromCharCode(evt.charCode).toLowerCase();

		len = target.value.length;
		if ( len <= max && (!e.keyCode || e.keyCode == 13) ) len++;
		if ( e.keyCode == 8 ) len--;
		
		document.getElementById('chars_' + obj.id).innerHTML = len;
		if (!IE && e.keyCode) return true;
		if (len>max) { return false;}
		else { return true; }
	}
	document.getElementById('chars_' + obj.id).innerHTML = obj.value.length;
	return true;
}

function storeCaret2(e) {
alert(e);
}

function storeCaret (textEl) {
	if (textEl.createTextRange)
	textEl.caretPos = document.selection.createRange().duplicate();
}

function insertAtCaret (textEl, text) {
	if (textEl.createTextRange && textEl.caretPos) {
		var caretPos = textEl.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text;
	} else
		textEl.value = text;
}

function insertField(field, area) {
	if (!field) return;
	var textarea = document.getElementById(area);
	var open = "%" + field + "%";
	if(!textarea.setSelectionRange)  {
		var selected = document.selection.createRange().text;
		if(selected.length <= 0) insertAtCaret(textarea, open);
		else document.selection.createRange().text = open;
	}  else  {
		var pretext = textarea.value.substring(0, textarea.selectionStart);
		var codetext = open + textarea.value.substring(textarea.selectionStart, textarea.selectionEnd);
		var posttext = textarea.value.substring(textarea.selectionEnd, textarea.value.length);
		if(codetext == open) codetext = open;
		textarea.value = pretext + codetext + posttext;
	}
}

function insertFieldSurvey(field, area) {
	if (!field) return;
	var textarea = document.getElementById(area);
	var open = "%%" + field + "%%";
	if(!textarea.setSelectionRange)  {
		var selected = document.selection.createRange().text;
		if(selected.length <= 0) insertAtCaret(textarea, open);
		else document.selection.createRange().text = open;
	}  else  {
		var pretext = textarea.value.substring(0, textarea.selectionStart);
		var codetext = open + textarea.value.substring(textarea.selectionStart, textarea.selectionEnd);
		var posttext = textarea.value.substring(textarea.selectionEnd, textarea.value.length);
		if(codetext == open) codetext = open;
		textarea.value = pretext + codetext + posttext;
	}
}


function summer_mudaWD() {
	document.getElementById("scount").disabled=false;
	document.getElementById("sweekday").disabled=false;
	document.getElementById("smonthday").disabled=true;
	document.getElementById("smonth").disabled=false;

	document.getElementById("ecount").disabled=false;
	document.getElementById("eweekday").disabled=false;
	document.getElementById("emonthday").disabled=true;
	document.getElementById("emonth").disabled=false;

	document.getElementById("scount").style.backgroundColor='#ffffff';
	document.getElementById("sweekday").style.backgroundColor='#ffffff';
	document.getElementById("smonthday").style.backgroundColor='#f1f1f1';
	document.getElementById("smonth").style.backgroundColor='#ffffff';

	document.getElementById("ecount").style.backgroundColor='#ffffff';
	document.getElementById("eweekday").style.backgroundColor='#ffffff';
	document.getElementById("emonthday").style.backgroundColor='#f1f1f1';
	document.getElementById("emonth").style.backgroundColor='#ffffff';

	document.getElementById("scount").style.color='#000000';
	document.getElementById("sweekday").style.color='#000000';
	document.getElementById("smonthday").style.color='#f1f1f1';
	document.getElementById("smonth").style.color='#000000';

	document.getElementById("ecount").style.color='#000000';
	document.getElementById("eweekday").style.color='#000000';
	document.getElementById("emonthday").style.color='#f1f1f1';
	document.getElementById("emonth").style.color='#000000';

}

function summer_mudaMD() {
	document.getElementById("scount").disabled=true;
	document.getElementById("sweekday").disabled=true;
	document.getElementById("smonthday").disabled=false;
	document.getElementById("smonth").disabled=false;

	document.getElementById("ecount").disabled=true;
	document.getElementById("eweekday").disabled=true;
	document.getElementById("emonthday").disabled=false;
	document.getElementById("emonth").disabled=false;

	document.getElementById("scount").style.backgroundColor='#f1f1f1';
	document.getElementById("sweekday").style.backgroundColor='#f1f1f1';
	document.getElementById("smonthday").style.backgroundColor='#ffffff';
	document.getElementById("smonth").style.backgroundColor='#ffffff';

	document.getElementById("ecount").style.backgroundColor='#f1f1f1';
	document.getElementById("eweekday").style.backgroundColor='#f1f1f1';
	document.getElementById("emonthday").style.backgroundColor='#ffffff';
	document.getElementById("emonth").style.backgroundColor='#ffffff';

	document.getElementById("scount").style.color='#f1f1f1';
	document.getElementById("sweekday").style.color='#f1f1f1';
	document.getElementById("smonthday").style.color='#000000';
	document.getElementById("smonth").style.color='#000000';

	document.getElementById("ecount").style.color='#f1f1f1';
	document.getElementById("eweekday").style.color='#f1f1f1';
	document.getElementById("emonthday").style.color='#000000';
	document.getElementById("emonth").style.color='#000000';

}

function summer_mudaTS() {
	summer_mudaMD();
}

function summer_load() {
	document.getElementById("scount").disabled=true;
	document.getElementById("sweekday").disabled=true;
	document.getElementById("smonthday").disabled=true;
	document.getElementById("smonth").disabled=true;

	document.getElementById("ecount").disabled=true;
	document.getElementById("eweekday").disabled=true;
	document.getElementById("emonthday").disabled=true;
	document.getElementById("emonth").disabled=true;

	document.getElementById("scount").style.backgroundColor='#f1f1f1';
	document.getElementById("sweekday").style.backgroundColor='#f1f1f1';
	document.getElementById("smonthday").style.backgroundColor='#f1f1f1';
	document.getElementById("smonth").style.backgroundColor='#f1f1f1';

	document.getElementById("ecount").style.backgroundColor='#f1f1f1';
	document.getElementById("eweekday").style.backgroundColor='#f1f1f1';
	document.getElementById("emonthday").style.backgroundColor='#f1f1f1';
	document.getElementById("emonth").style.backgroundColor='#f1f1f1';

	document.getElementById("scount").style.color='#f1f1f1';
	document.getElementById("sweekday").style.color='#f1f1f1';
	document.getElementById("smonthday").style.color='#f1f1f1';
	document.getElementById("smonth").style.color='#f1f1f1';

	document.getElementById("ecount").style.color='#f1f1f1';
	document.getElementById("eweekday").style.color='#f1f1f1';
	document.getElementById("emonthday").style.color='#f1f1f1';
	document.getElementById("emonth").style.color='#f1f1f1';

}


var idiv=0;
function insertNew() {
	odiv=idiv;
	idiv++;
	
	acct = document.getElementById('accounts').options;
	grps = document.getElementById('groups').options;
	fltr = document.getElementById('filters').options;
	
	tbb = document.getElementById('main');
	row = document.createElement("tr");
	tbod='';
	
	// Procura se tem TBODY na tabela.
	for(var i=0; i<tbb.childNodes.length; i++) {
		oo = tbb.childNodes[i];
		if (oo.nodeName=='TBODY') tbod = oo;
	}
	
	// Adiciona celula do nome
	cell = document.createElement("td");
	xtext = document.createTextNode('Nome:');
	cell.appendChild(xtext);
	row.appendChild(cell);
	cell = document.createElement("td");
	aTextBox=document.createElement('input');
	aTextBox.type = 'text';
	aTextBox.value = document.getElementById('edition_name').value;
	aTextBox.size = '25';
	aTextBox.name = 'edition[' + idiv + ']'
	cell.appendChild(aTextBox);
	row.appendChild(cell);

	// Adicioona celula da conta
	cell = document.createElement("td");
	xtext = document.createTextNode('Conta:');
	cell.appendChild(xtext);
	row.appendChild(cell);
	cell = document.createElement("td");
	sel2=document.createElement('select');
	sel2.name='account[' + idiv + ']';
// 	sel2.style.width='130px';

	for(i=0; i<acct.length; i++) {
		opt = document.createElement('OPTION');
		opt.value = acct[i].value;
		opt.text = acct[i].text;
		if (acct[i].selected) opt.selected = true;
		sel2.options.add(opt);
	}

	cell.appendChild(sel2);
	row.appendChild(cell);

	// Adicioona celula da Grupos
	cell = document.createElement("td");
	xtext = document.createTextNode('Grupo:');
	cell.appendChild(xtext);
	row.appendChild(cell);
	cell = document.createElement("td");
	sel2=document.createElement('select');
	sel2.name='group[' + idiv + ']';
// 	sel2.style.width='130px';
	
	for(i=0; i<grps.length; i++) {
		opt = document.createElement('OPTION');
		opt.value = grps[i].value;
		opt.text = grps[i].text;
		if (grps[i].selected) opt.selected = true;
		sel2.options.add(opt);
	}
	cell.appendChild(sel2);
	row.appendChild(cell);

	// Adicioona celula de filtros
	cell = document.createElement("td");
	xtext = document.createTextNode('Filtro:');
	cell.appendChild(xtext);
	row.appendChild(cell);
	cell = document.createElement("td");
	sel2=document.createElement('select');
	sel2.name='filter[' + idiv + ']';
// 	sel2.style.width='130px';
	
	for(i=0; i<fltr.length; i++) {
		opt = document.createElement('OPTION');
		opt.value = fltr[i].value;
		opt.text = fltr[i].text;
		if (fltr[i].selected) opt.selected = true;
		sel2.options.add(opt);
	}
	cell.appendChild(sel2);
	row.appendChild(cell);
	
	// Adiciona linha na tabela
	if (tbod) {
		tbod.appendChild(row);
		tbb.appendChild(tbod);
	} else
		tbb.appendChild(row);

}

// Funcao para o UCID da LH
function GetValue( cpo, id, rt, mtd, fld, sz, e ) {
	if (!e) e = window.event;
	if (e.keyCode==8 || e.keyCode==13 || (e.keyCode>36 && e.keyCode<47)) 
		if (sz && id.length<sz) {
			document.forms[0].elements['id_fk_clientes_pj'].value=0;
			document.getElementById(fld).innerHTML='<span style="color:red">!! Invalid !!</span>';
			return;
		}
	if (sz && id.length<sz) {
			document.forms[0].elements['id_fk_clientes_pj'].value=0;
			document.getElementById(fld).innerHTML='<span style="color:red">!! Invalid !!</span>';
		return;
	}

	Vhtml.xopen( '/default/getAjData?tb=pj&cp=' + cpo + '&id=' + id + '&rt=' + rt , fld, '', '', false, 'setClientPJ');
}


// Funcao de retorno para o UCID da LH (da funcao acima)
function setClientPJ(str, obj) {
	str = str.split('||');
	if (str[0]) {
		aux = str[0].split('=');
		if (aux[0] != 'nome') {
			aux[1]='<span style="color:red">' + aux[0] + '</span>';
			document.forms[0].elements['id_fk_clientes_pj'].value=0;
		} else {
			for(i=0; i<str.length; i++) {
				auxx = str[i].split('=');
				switch (auxx[0]) {
					case 'id_cliente':			document.forms[0].elements['id_fk_clientes_pj'].value=auxx[1]; break;
					case 'iata_number':			document.forms[0].elements['iata_number'].value=auxx[1]; break;
					case 'agent_location_code':	document.forms[0].elements['alias_number'].value=auxx[1]; break;
					case 'nome':				document.getElementById(obj).innerHTML=auxx[1]; break;
					case 'iata_flag':			document.forms[0].elements['iata_flag'].value=auxx[1]; break;
					case 'ch1':					document.forms[0].elements['ch1'].value=auxx[1]; break;
					case 'ch2':					document.forms[0].elements['ch2'].value=auxx[1]; break;
					case 'ch3':					document.forms[0].elements['ch3'].value=auxx[1]; break;
					case 'ch4':					document.forms[0].elements['ch4'].value=auxx[1]; break;
					case 'active':				document.forms[0].elements['active'].value=auxx[1]; break;
					case 'sph1_city':			document.forms[0].elements['sph_1_area'].value=auxx[1]; break;
					case 'sph2_coordiator':		document.forms[0].elements['sph_2_country'].value=auxx[1]; break;
					case 'sph3_region':			document.forms[0].elements['sph_3_region'].value=auxx[1]; break;
					case 'sph4_territory':		document.forms[0].elements['sph_4_territory'].value=auxx[1]; break;
					case 'sph5_district':		document.forms[0].elements['sph_5_district'].value=auxx[1]; break;
				}
			}
		}
	}
}

function LimitThis( obj_element, int_length ) {
	if ( obj_element.value.length == int_length ) return false;
}

function CountThis( obj_element, int_length, str_viewner ) {
	if ( obj_element.value.length > int_length )
		obj_element.value = obj_element.value.substring( 0, int_length );

	if ( document.getElementById( str_viewner ) )
		document.getElementById( str_viewner ).innerHTML = ( int_length - obj_element.value.length );
}

var hint_status=false;
function showHint(name, value, obj, e) {
	if (hint_status || !value) return;
	if (!e) var e = window.event;
	var x = e.clientX + document.body.scrollLeft;
	var y = e.clientY + document.body.scrollTop;
	
	document.getElementById(name).innerHTML = value;
	document.getElementById(name).style.top = y+1;
	document.getElementById(name).style.left = x- parseInt(document.getElementById(name).style.width)-20;
	document.getElementById(name).style.display='';
	
	hint_status=true;

}

function hideHint(name) {
	document.getElementById(name).style.display='none';
	hint_status=false;
}

/**
 * Janela Clone
 */
function clone(url) { if( confirm(JS_CLONE) ) document.location=url }
