//-----------------------------------------------------------------------------------
//Este aplicativo é componente da suíte em asp Livesite.
//Todos os direitos reservados. É proibida a reprodução parcial ou total de qualquer
//parte deste aplicativo, bem como a sua utilização, sem prévia autorização.<br>
//Desenvolvido por Alex Albuquerque (email@alex.albuquerque.nom.br).
//Primeiro release em maio/2003.
//-----------------------------------------------------------------------------------

function textCounter(field, countfield, maxlimit) {
	if (field.value.length > maxlimit) // if too long...trim it!
	field.value = field.value.substring(0, maxlimit);
	// otherwise, update 'characters left' counter
	else 
	countfield.value = maxlimit - field.value.length;
}


/**********************************************************
 * Exibe a data atual em formato completo
 **********************************************************/
today = new Date()
day = today.getDate()
days = today.getDay()
month = today.getMonth()
year = today.getYear()

if (day < 10)
	day = "0" + day
if (year < 2000)
	year = "19" + year

function CriaArray (n){
	this.length = n }

	dayName = new CriaArray(7)
		dayName[0] = "Domingo"
		dayName[1] = "Segunda"
		dayName[2] = "Ter&ccedil;a"
		dayName[3] = "Quarta"
		dayName[4] = "Quinta"
		dayName[5] = "Sexta"
		dayName[6] = "S&aacute;bado"
	monthName = new CriaArray(12)
		monthName[0] = "Janeiro"
		monthName[1] = "Fevereiro"
		monthName[2] = "Mar&ccedil;o"
		monthName[3] = "Abril"
		monthName[4] = "Maio"
		monthName[5] = "Junho"
		monthName[6] = "Julho"
		monthName[7] = "Agosto"
		monthName[8] = "Setembro"
		monthName[9] = "Outubro"
		monthName[10] = "Novembro"
		monthName[11] = "Dezembro"

function js_fullDate(){
	if (year == '19100') year = '2000';
		document.write (dayName[days] + ", " + day + " de " + monthName[month] + " de " + year)
}

/**********************************************************
 * Efetua troca de caracteres dentro de uma expressão
 **********************************************************/
function replace(INNER_EXPRESSION,INNER_CARACTER,INNER_NEWCARACTER){
	var RegExp = eval('/\\' + INNER_CARACTER + '/g');
	return INNER_EXPRESSION.replace(RegExp,INNER_NEWCARACTER);
} 

//SoftLink dhtmlMenu
var st_path="";
var st_lib="includes/stm31.js";

/**********************************************************
REDIRECIONA COM BASE NA ESCOLHA EM COMBO BOX (direto)
 **********************************************************/
function jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

/**********************************************************
REDIRECIONA COM BASE NA ESCOLHA EM COMBO BOX (botão)
 **********************************************************/
function jumpMenuGo(objId,targ,restore){ //v9.0
  var selObj = null;  with (document) { 
  if (getElementById) selObj = getElementById(objId);
  if (selObj) eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0; }
}

/**********************************************************
PERMITE QUE O CLICK SOBRE O OBJETO CONDUZA AO LINK INDICADO
 **********************************************************/
function jumpToURL(IFRAME,INNER_URL,FRAME){
	if (IFRAME == "parent"){
	top.parent.window.document.location.href = ""+INNER_URL+""
	}
	else{
	window.document.location.href = ""+INNER_URL+""
	}
}

/**********************************************************
PERMITE QUE O CLICK SOBRE O OBJETO CONDUZA AO LINK INDICADO
 **********************************************************/
function jumpToFrame(INNER_URL,FRAME){
	parent.frames[FRAME].location = ""+INNER_URL+""
}

/**********************************************************
  	SELECIONA E COPIA O CONTEÚDO DE UM CAMPO TEXTO
 	 SOMENTE PARA IE (NETSCAPE APENAS SELECIONA)
 **********************************************************/
function autoCopy(theField) {
	var tempval=eval("document."+theField)
	tempval.focus()
	tempval.select()
	therange=tempval.createTextRange()
	therange.execCommand("Copy")
	alert("As informações foram copiadas para a memória e você pode colá-las onde desejar.");
	}

function colorPicked(INNER_FORM,INNER_FIELD,INNER_ELEMENT){
	if (INNER_ELEMENT=="pSTRCONF_NAME_COLOR"){
		pSTRCONF_NAME_COLOR.bgColor = document[INNER_FORM][INNER_FIELD].value;
	}
	if (INNER_ELEMENT=="pSTRCONF_COLOR"){
		pSTRCONF_COLOR.bgColor = document[INNER_FORM][INNER_FIELD].value;
	}
	if (INNER_ELEMENT=="pCONTENT_TITLE_COLOR"){
		pCONTENT_TITLE_COLOR.bgColor = document[INNER_FORM][INNER_FIELD].value;
	}
}

function color_onKeypress(){ 
	var string="abcdefghijklmnopqrstuvxwyzABCDEFGHIJKLMNOPQRSTUVXWYZ1234567890#";
	if (string.indexOf(unescape('%' + window.event.keyCode.toString(16))) != -1) 
		window.event.returnValue = true;
	else
		window.event.returnValue = false;
}

function openWindow(theURL, winName, w, h, conditions){
/***********************************************************************
 * Abre qualquer janela pop-up centralizada na tela e coloca o foco nela
 **********************************************************************/
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	features = 'height='+h+',width='+w+',top='+wint+',left='+winl+','+conditions+''
	winName = window.open(theURL, winName, features)
		if (parseInt(navigator.appVersion) >= 4){
			winName.window.focus();
		}
}
/**********************************************************
 * Impede a entrada de caracteres não especificados
 **********************************************************/
function txtDate_onKeypress(){ 
	var string="1234567890/";
	if (string.indexOf(unescape('%' + window.event.keyCode.toString(16))) != -1) 
		window.event.returnValue = true;
	else
		window.event.returnValue = false;
}

/**********************************************************
 * Ajusta a data para o formato dd/mm/aaaa automaticamente
 **********************************************************/
function adjustDate_onKeyPress(input){
	if ((event.keyCode<48)||(event.keyCode>57)){
		event.returnValue = false;
		}
    else {
//    	if((input.value.length==3)||(input.value.length==7))
    	if((input.value.length==2)||(input.value.length==5))
//			input.value=input.value + "." ;
			input.value=input.value + "/" ;
//		else {
//    		if(input.value.length==11)
//				input.value=input.value + "-" ;
//		}
	}
}

function txtHour_onKeypress(){ 
/**********************************************************
 * Impede a entrada de caracteres não especificados
 **********************************************************/
	var string="1234567890:";
	if (string.indexOf(unescape('%' + window.event.keyCode.toString(16))) != -1) 
		window.event.returnValue = true;
	else
		window.event.returnValue = false;
}

function txtCEP_onKeypress(){ 
/**********************************************************
 * Impede a entrada de caracteres não especificados
 **********************************************************/
	var string="1234567890-";
	if (string.indexOf(unescape('%' + window.event.keyCode.toString(16))) != -1) 
		window.event.returnValue = true;
	else
		window.event.returnValue = false;
}

/**********************************************************
 * Ajusta o CEP para o formato 00000-000 automaticamente
 **********************************************************/
function adjustCEP_onKeyPress(input){
	if ((event.keyCode<48)||(event.keyCode>57)){
		event.returnValue = false;
		}
    else {
//    	if((input.value.length==3)||(input.value.length==7))
    	if((input.value.length==5))
//			input.value=input.value + "." ;
			input.value=input.value + "-" ;
//		else {
//    		if(input.value.length==11)
//				input.value=input.value + "-" ;
//		}
	}
}

/**********************************************************
 * Formatação automática de valores em moeda
 * milSep = Separador dos inteiros, pode ser . ou ,
 * decSep = Separador dos centavos, pode ser . ou ,
 **********************************************************/
function formatCurrency(fld, milSep, decSep, e) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;
	
	if (whichCode == 13) return true;  // Tecla Enter
		key = String.fromCharCode(whichCode);  // Captura o valor da tecla pressionada
			if (strCheck.indexOf(key) == -1) return false;  // Tecla inválida
			len = fld.value.length;
			for(i = 0; i < len; i++)
				if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
					aux = '';
					for(; i < len; i++)
				if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
					aux += key;
					len = aux.length;
		if (len == 0) fld.value = '';
		if (len == 1) fld.value = '0'+ decSep + '0' + aux;
		if (len == 2) fld.value = '0'+ decSep + aux;
		if (len > 2) {
		aux2 = '';
			for (j = 0, i = len - 3; i >= 0; i--) {
			if (j == 3) {
				aux2 += milSep;
				j = 0;
			}
		aux2 += aux.charAt(i);
		j++;
		}
	
	fld.value = '';
	len2 = aux2.length;
		for (i = len2 - 1; i >= 0; i--)
		fld.value += aux2.charAt(i);
		fld.value += decSep + aux.substr(len - 2, len);
	}
	return false;
}

function Date_Change(sNewValue,sForm,sField){
/**********************************************************
 * Insere no formulário a escolha da data feita no pop-up
 **********************************************************/
	document[sForm][sField].value = sNewValue;
}

function openCalendar(sDate,sCallback,sCallbackForm,sCallbackField,nTop,nLeft){
/**********************************************************
 * Processa a solicitação da abertura do calendário pop-up
 **********************************************************/
	var oWindow;
	oWindow = window.open("../_Includes/popupcalendar.asp?date=" + sDate + "&callback=" + sCallback + "" + "&callbackform=" + sCallbackForm + "" + "&callbackfield=" + sCallbackField + "","calendar","top=" + nTop + ",left=" + nLeft + ",height=132,width=145,status=no,resizable=no,toolbar=no,menubar=no,scrollbars=no,location=no");
	oWindow.focus();
	return true;
}

function getTimeNow(INNER_FORM, INNER_FIELD){
/**********************************************************
 * Insere a hora atual HH:MM no campo de qualquer formulário
 **********************************************************/
	today = new Date();
	hoursNow = today.getHours()
	if (hoursNow < 10){
		hoursNow = "0" + hoursNow
	}
	minutesNow = today.getMinutes();
	if (minutesNow < 10){
		minutesNow = "0" + minutesNow
	}
	document[INNER_FORM][INNER_FIELD].value = hoursNow + ":" + minutesNow;
	return true;
}

function toggleWindow(sWindow)
{
	//when = newDate();
	//when.setDay(when.getDay()+1);
	//when = when.toGMTString();
	if (document.all) {
		if (document.all(sWindow).style.display == 'none') {
			document.all(sWindow).style.display = 'block';
			sWin = sWindow + "_option";
			document.images(sWin).src = '<%=gsSiteRoot%>../images/x.gif';
			document.images(sWin).alt = '<%=dictLanguage("Collapse_This_Window")%>';
			document.cookie = sWindow + "=TRUE";
		}
		else {
			document.all(sWindow).style.display = 'none';
			sWin = sWindow + "_option";
			document.images(sWin).src = '<%=gsSiteRoot%>../images/maximize.gif';
			document.images(sWin).alt = '<%=dictLanguage("Open_This_Window")%>';
			document.cookie = sWindow + "=FALSE";					
		}
	}
	else if (document.getElementById) {
		if (document.getElementById(sWindow).style.display == 'none') {
			document.getElementById(sWindow).style.display = 'block';
			document.getElementById(sWindow).style.visibility = 'visible';
			sWin = sWindow + "_option";
			document.images[sWin].src = '<%=gsSiteRoot%>../images/x.gif';
			document.images[sWin].alt = '<%=dictLanguage("Collapse_This_Window")%>';
			document.cookie = sWindow + "=TRUE";
		}
		else {
			document.getElementById(sWindow).style.display = 'none';
			document.getElementById(sWindow).style.visibility = 'hidden';
			sWin = sWindow + "_option";
			document.images[sWin].src = '<%=gsSiteRoot%>../images/maximize.gif';
			document.images[sWin].alt = '<%=dictLanguage("Open_This_Window")%>';
			document.cookie = sWindow + "=FALSE";					
		}	
	}
}

function popup(url) {
	newWindow = window.open(url,'daughter','menubar=yes,toolbar=no,location=no,scrollbars=yes,resizable=no,width=433,height=500,screenX=100,screenY=100,top=100,left=100');
	if (newWindow.opener == null) newWindow.opener = self;
	newWindow.focus();
}

function popupwide(url) {
	newWindow = window.open(url,'daughter','menubar=yes,toolbar=no,location=no,scrollbars=yes,resizable=no,width=600,height=500,screenX=100,screenY=100,top=100,left=100');
	if (newWindow.opener == null) newWindow.opener = self;
	newWindow.focus();
}

function popup2(url) {
	newWindow = window.open(url,'daughter2','menubar=yes,toolbar=no,location=no,scrollbars=yes,resizable=no,width=433,height=500,screenX=200,screenY=200,top=200,left=200');
	if (newWindow.opener == null) newWindow.opener = self;
	newWindow.focus();
}

/**********************************************************
 * Exibe a resolução de vídeo, quantidade de cores
 * e o browser em uso.
 **********************************************************/
    var num_colors
	if (screen.colorDepth == 4){
	num_colors = "16 cores";
	}
     
	else if (screen.colorDepth== 8){
	num_colors = "256 cores";
	}
	
	else if (screen.colorDepth  == 16){
	num_colors= "65.536 cores (HighColor)";
	}

	else if (screen.colorDepth  == 24){
	num_colors= "16.777.216 cores (TrueColor)";
	}

	else if (screen.colorDepth  == 32){
	num_colors= "32 milhões de cores (TrueColor)";
	}

function showConfiguration(){
    var configuration = 'Resolução de Vídeo: ' + screen.width + ' x ' + screen.height + '\n' + 'Total de Cores: ' + num_colors + '\n' + 'Browser: ' + navigator.appName + '\n' + 'Versão: ' + navigator.appVersion
	window.alert(configuration)
}

/************************************************************
 * Seleciona automaticamente todas as checkbox dos formulários
 ************************************************************/
function checkAll(INNER_FORM, INNER_FIELD, INNER_FIELD_LEN) {
	with(document[INNER_FORM]) {
		for(i=0;i<elements.length;i++) {
			thiselm = elements[i];
			if(thiselm.name.substring(0,INNER_FIELD_LEN) == '' + INNER_FIELD + '')
				thiselm.checked = !thiselm.checked
		}
	}
}

/************************************************************
 * Concede o foco no campo do form especificado
 ************************************************************/
function getFocus(INNER_FORM, INNER_FIELD){
	window.document[INNER_FORM][INNER_FIELD].focus()
}

/************************************************************
 * Função indexadora para exbir o help de contexto
 ************************************************************/
function help(topic){
	openWindow('../_help/mmHelp.asp?topic=' + topic + '','Helper','550','450','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes')
}

/************************************************************
 * Função para carregar o valor de uma dropdown list em
 um iFrame. Ao selecionar uma opção na lista, o valor é passado
 para a URL dentro do iFrame. Pode ser uma URL  simples
 ou executar um select em banco de dados. Pode ser usado para
 carregar somente texto ou até mesmo listas de opções baseadas
 na escolha no formulário principal.
  
 iFRAMENAME = Nome do IFrame no HTML
 iFRAMEFORM = Formulário onde está a dropdown list
 iFRAMEOBJECT = Nome do objeto no HTML, no caso a dropdown list
 DISPLAY MODE = Modo de exibição do conteúdo
 				displaymode = 0 'Abre em um iFrame especificado
				displaymode = 1 'Abre em uma nova janela
 iFRAMEURL = 	URL a ser carregada no iFrame.
 ************************************************************/
function dropDown_to_IFrame(iFRAMENAME,iFRAMEFORM,iFRAMEOBJECT,DISPLAYMODE,iFRAMEURL){
	var selectedurl=document[iFRAMEFORM][iFRAMEOBJECT].options[document[iFRAMEFORM][iFRAMEOBJECT].selectedIndex].value
		if (document.getElementById&&DISPLAYMODE==0)
		document.getElementById(""+iFRAMENAME+"").src=iFRAMEURL+selectedurl
		else if (document.all&&DISPLAYMODE==0)
		document.all[iFRAMENAME].src=iFRAMEURL+selectedurl
		else{
			if (!window.win2||win2.closed)
			win2=window.open(iFRAMEURL+selectedurl)
			//Se a janela já existir, recarrega nela mesma
			else{
				win2.location=selectedurl
				win2.focus()
				}
		}
	}

/************************************************************
 * Função para carregar o valor de uma input text em
 um iFrame. Ao modificar o valor da input text, este é passado
 para a URL dentro do iFrame. Pode ser uma URL simples
 ou executar um select em banco de dados. Pode ser usado para
 carregar somente texto ou até mesmo listas de opções baseadas
 na escolha no formulário principal.
  
 iFRAMENAME = Nome do IFrame no HTML
 iFRAMEFORM = Formulário onde está a input text
 iFRAMEOBJECT = Nome do objeto no HTML, no caso a input text
 DISPLAY MODE = Modo de exibição do conteúdo
 				displaymode = 0 'Abre em um iFrame especificado
				displaymode = 1 'Abre em uma nova janela
 iFRAMEURL = 	URL a ser carregada no iFrame.
 ************************************************************/
function inputText_to_IFrame(iFRAMENAME,iFRAMEFORM,iFRAMEOBJECT,DISPLAYMODE,iFRAMEURL){
	var selectedurl=document[iFRAMEFORM][iFRAMEOBJECT].value
		if (document.getElementById&&DISPLAYMODE==0)
		document.getElementById(""+iFRAMENAME+"").src=iFRAMEURL+selectedurl
		else if (document.all&&DISPLAYMODE==0)
		document.all[iFRAMENAME].src=iFRAMEURL+selectedurl
		else{
			if (!window.win2||win2.closed)
			win2=window.open(iFRAMEURL+selectedurl)
			//Se a janela já existir, recarrega nela mesma
			else{
				win2.location=selectedurl
				win2.focus()
				}
		}
	}
/************************************************************
 * Função para dar um refresh em um iframe, passando a ele
 valores para serem atualizados.
 
 iFRAMENAME = Nome do IFrame no HTML
 iFRAMEURL = URL a ser carregada no iFrame.
 ************************************************************/
function Refresh_IFrame(iFRAMENAME,iFRAMEURL){
		document.getElementById(""+iFRAMENAME+"").src=iFRAMEURL
	}

function pickFile(INNER_FORM, INNER_FIELD, INNER_VALUE, INNER_FIELD2, INNER_VALUE2, INNER_FOCUS, INNER_CLOSEFRAMES){
/************************************************************
 * Função para carregar o valor de uma seleção em lista, por imagem
 ou texto, em um formulário. o script permite a inserção de até
 dois valores, geralmente o ID e o NOME da seleção. Para utilizar
 apenas um objeto, deixe em branco a configuração referente ao
 segundo objeto.
  
 INNER_FORM = Formulário onde está o objeto
 INNER_FIELD = Nome do objeto no HTML
 INNER_VALUE = Valor a ser passado ao objeto
 INNER_FIELD2 = Nome do segundo objeto no HTML
 INNER_VALUE2 = Valor a ser passado ao segundo objeto
 INNER_FOCUS = Concede o foco ao primeiro objeto
 	* para foco, utilize 'yes' no script
	* sem foco, deixe vazio no script
 INNER_CLOSEFRAMES = Informa se a janela a ser fechada é um frameset
  	* para frameset, utilize 'yes' no script
	* sem normal, deixe vazio no script
 ************************************************************/	
	top.window.opener.document[INNER_FORM][INNER_FIELD].value = INNER_VALUE;
	if (INNER_FOCUS == "yes")
		top.window.opener.document[INNER_FORM][INNER_FIELD].focus();
			if (INNER_FIELD2 != "" || INNER_VALUE2 != "")
				top.window.opener.document[INNER_FORM][INNER_FIELD2].value = INNER_VALUE2;
	if (INNER_CLOSEFRAMES == "yes")
		parent.self.close();
	else{
		self.close();
	}
}

/**********************************************************
 * Insera a soma de até 3 campos em um campo total
 **********************************************************/
function getTotalNow(INNER_FORM,INNER_FIELD1,INNER_FIELD2,INNER_FIELD3,INNER_TOTALFIELD){

	VAL1 = document[INNER_FORM][INNER_FIELD1].value
	VAL1 = replace(VAL1,'.','')
	VAL1 = replace(VAL1,',','.')

	VAL2 = document[INNER_FORM][INNER_FIELD2].value
	VAL2 = replace(VAL2,'.','')
	VAL2 = replace(VAL2,',','.')

	VAL3 = document[INNER_FORM][INNER_FIELD3].value
	VAL3 = replace(VAL3,'.','')
	VAL3 = replace(VAL3,',','.')

	TOTAL_VALUE = eval(VAL1)+eval(VAL2)+eval(VAL3);
	document[INNER_FORM][INNER_TOTALFIELD].value = CommaFormatted(CurrencyFormatted(TOTAL_VALUE));
	return true;
}

/**********************************************************
 * Copia o valor de um campo para outro automaticamente
 **********************************************************/
function copyField(INNER_FORM,INNER_INITIALFIELD,INNER_FINALFIELD){
	document[INNER_FORM][INNER_FINALFIELD].value = document[INNER_FORM][INNER_INITIALFIELD].value;
	return true;
}

/**********************************************************
 * Formata números para moeda com 3 casas e decimals
 **********************************************************/
function CurrencyFormatted(amount){
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}
/**********************************************************
 * Formata números para moeda com 3 casas e decimals
 **********************************************************/
function CommaFormatted(amount){
	var delimiter = "."; // replace comma if desired
	var a = amount.split('.',2)
	var d = a[1];
	var i = parseInt(a[0]);
	if(isNaN(i)) { return ''; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3)
	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);
	if(d.length < 1) { amount = n; }
	else { amount = n + ',' + d; }
	amount = minus + amount;
	return amount;
}

//-----------------------------------------------------------------------------------
// showLayer()
// ATIVA E DESATIVA A EXIBIÇÃO DE LAYERS
// Todo layer será exibido pela ação de um clique em algum objeto. Esse objeto será
// chamado de button no script e será determinado pela variável innerBtn
//-----------------------------------------------------------------------------------
function showLayer(iFrameId,image){
//	var innerObj = getInnerObj(iFrameId);
//	var innerBtn = document.getElementById(buttonId)
//	innerObj.focus();
//	document.getElementById(layerId).style.left = getOffsetLeft(innerBtn) + "px";
//	document.getElementById(layerId).style.top = (getOffsetTop(innerBtn) + innerBtn.offsetHeight) + "px";

	if (document.getElementById(iFrameId).style.visibility=="visible"){
		document.getElementById(iFrameId).style.visibility="hidden";
		document.getElementById("previewImage").src="" +image+ "";
	}
	else {
		document.getElementById(iFrameId).style.visibility="visible";
	}
}