﻿// Funcao que permite a navegacao para a pagina de dados de uma entidade
function ConsultarEntidade(urlBase, numeroCliente)
{
	if(frmPost.fNumeroClientePost == null)
	{
		inputHidden = CreateInput('fNumeroClientePost', 'fNumeroClientePost', 'Hidden', numeroCliente);
		frmPost.appendChild(inputHidden);
	}
	else
	{
		 document.frmPost.fNumeroClientePost.value = numeroCliente;
	}
	document.frmPost.action = urlBase + "Site/Cogen41/Clientes/DadosCliente.aspx";
	document.frmPost.submit();
}

// Funcao que permite a navegacao para a pagina de dados de uma apolice
function ConsultarApoliceSemSistemaOrigem(urlBase, numeroApolice)
{
	if(frmPost.fNumeroApolicePost == null)
	{
		inputHidden = CreateInput('fNumeroApolicePost', 'fNumeroApolicePost', 'Hidden', numeroApolice);
		frmPost.appendChild(inputHidden);
	}
	else
	{
		document.frmPost.fNumeroApolicePost.value = numeroApolice;
	}
	
	document.frmPost.action = urlBase + "Site/Comum/Apolices/ObterSistemaOrigemApolice.aspx";
	document.frmPost.submit();
}

// Preenche a combo fornecida com os codigos indicados
function PreencherComboCodigos(comboID, selectedItemValue, arrayCodigos, includeBlankOption)
{
	var combo;
 
	if (arrayCodigos == null)
	{
		alert("O array de codigos encontra-se mal parametrizado. Combo:" + comboID);
		return;
	}
	
	// Obter e Limpar a combo box
	combo = document.getElementById(comboID);
	if (combo == null)
		return;
		
	combo.length = 0;
	
	var idxCombo = 0;
	if (includeBlankOption)
	{
		combo.options[0] = new Option("-- Seleccionar --", "");
		idxCombo++;
	}

	// Carregar a combo box com os valores e seleccionar o indicado
	// A descricao encontra-se sempre uma posicao depois do codigo
	for (var i = 0; i < arrayCodigos.length; i += 2, idxCombo++)
	{
		combo.options[idxCombo] = new Option(arrayCodigos[i + 1], arrayCodigos[i]);
		
		if (arrayCodigos[i] == selectedItemValue)
		{
			combo.options[idxCombo].selected = true;
		}
	}
	
}

function GetFirstElementCode(inputCode)
{
	var actualCode;
	
	inputCode = "" + inputCode;
	if (inputCode.indexOf(":") != -1)
		actualCode = inputCode.substring(0, inputCode.indexOf(":"));
	else
		actualCode = inputCode.substring(0, inputCode.length);

	return actualCode;
}

function GetPreviousElementsCodes(inputCode)
{
	var previousCodes;
	
	inputCode = "" + inputCode;
	previousCodes = inputCode.substring(inputCode.indexOf(":") + 1, inputCode.length);
	
	return previousCodes;
}

function checkIntegerNumber(objectValue, errorMsg) {
	var erro = "";
	if (isNaN(objectValue)) // nao eh numero
		erro =  errorMsg
	else { 
		var num = new Number(objectValue)
		if (num%1 != 0)  // nao eh inteiro
			erro = errorMsg;
	}
	return erro;
}

function checkData(dia, mes, ano, errorMsg) {
	var erro = "";
	if (dia != "" && mes != "" && ano != "") {
		if (checkIntegerNumber(dia, errorMsg) != "")
			erro = errorMsg;
		else if (checkIntegerNumber(mes, errorMsg) != "")
			erro = errorMsg;
		else if (checkIntegerNumber(ano, errorMsg) != "")
			erro = errorMsg;
		else if (mes == 1 || mes == 3 || mes == 5 || mes == 7 || mes == 8 || mes == 10 || mes == 12) {
				if (dia < 1 || dia > 31)
					erro = errorMsg;}
		else if (mes == 4 || mes == 6 || mes == 9 || mes == 11){
			if (dia < 1 || dia > 30)
				erro = errorMsg;}
		else {
			limite = ((ano % 400 == 0) || ((ano % 4 == 0) && (ano % 100 !=0))) ? 29 : 28;
			if (dia < 1 || dia > limite)
				erro = errorMsg;}
		if ( mes < 1 || mes > 12){
				erro = errorMsg;}
	}
	else if(dia == "" && mes == "" && ano == "") {}
	else
		erro = errorMsg;
	return erro;
}

// Comparar duas datas.
// Retorna 1, 2 ou 0 conforme a data 1 seja maior, menor ou igual a data 2
function compareDate(sDate1, sDate2) {
	var year1, year2, month1, month2, day1, day2, n1, n2;
	
	year1 = parseInt(sDate1.substr(0, 4), 10);
	year2 = parseInt(sDate2.substr(0, 4), 10);

	n1 = sDate1.indexOf('-');
	n2 = sDate1.substr(n1+1).indexOf('-');
	month1 = parseInt(sDate1.substr(n1+1, n2), 10);
	day1 = parseInt(sDate1.substr(n1+1+n2+1), 10);

	n1 = sDate2.indexOf('-');
	n2 = sDate2.substr(n1+1).indexOf('-');
	month2 = parseInt(sDate2.substr(n1+1, n2), 10);
	day2 = parseInt(sDate2.substr(n1+1+n2+1), 10);

	// Verificar os anos
	if (year1 > year2)
		return 1;
	else if (year1 < year2)
		return 2;
	
	// Anos iguais, verificar os meses
	if (month1 > month2)
		return 1;
	else if (month1 < month2)
		return 2;

	// Anos e meses iguais, verificar os dias
	if (day1 > day2)
		return 1;
	else if (day1 < day2)
		return 2;
		
	// Tudo igual, retornar 0
	return 0;
}


// Comparar duas datas.
// Retorna 1, 2 ou 0 conforme a data 1 seja maior, menor ou igual a data 2
function RetornaAnoEntreDatas(sDate1, sDate2) {
	var year1, year2, numYear, month1, month2, day1, day2, n1, n2;
	
	year1 = parseInt(sDate1.substr(0, 4), 10);
	year2 = parseInt(sDate2.substr(0, 4), 10);

	n1 = sDate1.indexOf('-');
	n2 = sDate1.substr(n1+1).indexOf('-');
	month1 = parseInt(sDate1.substr(n1+1, n2), 10);
	day1 = parseInt(sDate1.substr(n1+1+n2+1), 10);

	n1 = sDate2.indexOf('-');
	n2 = sDate2.substr(n1+1).indexOf('-');
	month2 = parseInt(sDate2.substr(n1+1, n2), 10);
	day2 = parseInt(sDate2.substr(n1+1+n2+1), 10);

	// Verificar os anos
	numYear = year1 - year2;
			
	// Tudo igual, retornar 0
	return numYear;
}

function NewWindow(mypage, myname,w, h, scroll, posX, posY)
{
	var win = null;
	LeftPosition = posX;
	TopPosition = posY;
	settings =
	'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll
	win = window.open(mypage,myname,settings)
	
	return win;
}

//funcoes para os cookies
function fixDate(date) {
	var base = new Date(0)
	var skew = base.getTime()
	if (skew > 0)
	date.setTime(date.getTime() - skew)}
	
function setCookie(name, value, expires, path, domain, secure) {
	var curCookie = name + "=" + escape(value) +
	((expires) ? "; expires=" + expires.toGMTString() : "") +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "")
	document.cookie = curCookie}
	
function Nvl(x, defaultValue) { 
	if ( !defaultValue ) defaultValue = '';	
	return ( ( IsEmpty(x) ) ? defaultValue: x );
}

function getCookie(name) {
	var prefix = name + "="
	var cookieStartIndex = document.cookie.indexOf(prefix)
	if (cookieStartIndex == -1)
		return null
	var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length)
	if (cookieEndIndex == -1)
		cookieEndIndex = document.cookie.length;
	return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex))
}

// Funcao para inicializar 1 cookie - Validade em segundos
function InicializaCookie(nome, valor, validade)
{
	var now = new Date();
	fixDate(now);
	now.setTime(now.getTime() + validade * 1000);
	setCookie(nome, valor, now);
}

var subMenu;
function off(){
	var i, comboElements;
	subMenu.style.visibility="hidden";
	subMenu=null;
	
	if (navigator.appName == "Microsoft Internet Explorer") {
		comboElements = document.all.tags("SELECT");
		for (i = 0; i < comboElements.length; i++) {
			//comboElements[i].style.visibility = "visible";
			comboElements[i].style.display = "";
		}
	}
}

function on(menuname){
	var topSubMenu, leftSubMenu;
	var topCombo, leftCombo;
	var i, comboElements;
	var auxElement, newElement;
 
	newElement = document.getElementById(menuname);

	if ((subMenu != null) && (newElement != subMenu))
		subMenu.style.visibility="hidden";

	subMenu = newElement;
	subMenu.style.visibility="visible";

	if (navigator.appName == "Microsoft Internet Explorer") {
		topSubMenu = subMenu.offsetTop;
		leftSubMenu = subMenu.offsetLeft;
		for (auxElement = subMenu.offsetParent; (auxElement != null) && (auxElement.tagName != "BODY"); auxElement = auxElement.offsetParent) {
			topSubMenu = topSubMenu + auxElement.offsetHeight;
			leftSubMenu = leftSubMenu + auxElement.offsetWidth;
		}

		comboElements = document.all.tags("SELECT");

		for (i=0; i < comboElements.length; i++) {
			topCombo = comboElements[i].offsetTop;
			leftCombo = comboElements[i].offsetLeft;
			for (auxElement = comboElements[i].offsetParent; auxElement.tagName != "BODY"; auxElement = auxElement.offsetParent) {
				topCombo = topCombo + auxElement.offsetTop;
				leftCombo = leftCombo + auxElement.offsetLeft;
			}
			if (!(((topCombo >= topSubMenu + subMenu.offsetHeight) || 
				(topCombo + comboElements[i].offsetHeight <= topSubMenu)) || 
				((leftCombo >= leftSubMenu + subMenu.offsetWidth) || 
				(leftCombo + comboElements[i].offsetWidth <= leftSubMenu)))) {
					comboElements[i].style.display = "none";
					//comboElements[i].style.visibility = "hidden";
			}
		}
	}
}

// Criar uma TD
function CreateTD(tdId, tdAlign, tdClass, tdWidth) {
	var newTD = document.createElement("TD");
	newTD.setAttribute("id", tdId);
	newTD.setAttribute("align", tdAlign);
	newTD.setAttribute("class", tdClass);
	newTD.setAttribute("className", tdClass);
	if (tdWidth != '')
		newTD.setAttribute("width", tdWidth);

	return newTD;
}

// Criar uma label com um elemento de texto
function CreateLabel(lblId, lblText) {
	var newElemLBL = document.createElement("LABEL");
	newElemLBL.setAttribute("id", lblId);
	
	var newElemText = document.createTextNode(lblText);
	newElemLBL.appendChild(newElemText);
	return newElemLBL;
}

// Criar um input
function CreateInput(inputId, inputName, inputType, inputValue) {
	var newElem = document.createElement("INPUT");
	newElem.setAttribute("id", inputId);
	newElem.setAttribute("name", inputName);
	newElem.setAttribute("value", inputValue);
	newElem.setAttribute("type", inputType);

	return newElem;
}

// Detectar tecla
function getKey(e) {
	if (e.keyCode) return String.fromCharCode(e.keyCode);
	if (e.which) return String.fromCharCode(e.which);
}

function limitEntry(e, field) {
	var el = 0, f = field.form, keyChar = getKey(e);
	
	while (f.elements[el]) {
		if (f.elements[el++] == field) break; //find current field
	}
	try
	{
	    if ((field.value.length + 1 == field.maxLength) && f.elements[el]) {
		    f.elements[el-1].value += keyChar;
		    f.elements[el].focus();
		    return false;
	    }
	}
	catch(e) {}
	return true;
}

function limitEntryDigits(e, field) {
	var keyChar = getKey(e);

	if (/\D/.test(keyChar)) return false; //digits only	
	return limitEntry(e, field);
}

function ltrim(argvalue) {

  while (1) {
    if (argvalue.substring(0, 1) != " ")
      break;
    argvalue = argvalue.substring(1, argvalue.length);
  }

  return argvalue;
}

function rtrim(argvalue) {

  while (1) {
    if (argvalue.substring(argvalue.length - 1, argvalue.length) != " ")
      break;
    argvalue = argvalue.substring(0, argvalue.length - 1);
  }

  return argvalue;
}

function trim(argvalue) {
  var tmpstr = ltrim(argvalue);

  return rtrim(tmpstr);

}

// scrollPagina(x,y)
// funcao que faz o scroll da pagina para uma posicao definida pelas coordenadas (x,y)
function scrollPagina(x,y){
	document.parentWindow.scroll(x,y);
}

//Scroll da pagina para o seu topo
function scrollPaginaTopo(){JumpToPageTop();}
var bAgent = navigator.userAgent;
var d = document;
function Sniffer(){this.Win = bAgent.indexOf("Win",0) != -1 ? 1 :0;this.Mac = bAgent.indexOf("Mac",0) != -1 ? 1 :0;this.Moz = ((bAgent.indexOf("Gecko") != -1) && (bAgent.indexOf("Safari",0) == -1)) ? 1 :0;this.OPERA = bAgent.indexOf("Opera",0) != -1 ? 1 :0;this.SAFARI = bAgent.indexOf("Safari",0) != -1 ? 1 :0;	this.checkObj = d.all?(d.getElementById?3:2):(d.getElementById?4:(d.layers?1:0));this.allObj = ((this.checkObj == 1) || (this.checkObj == 2) || (this.checkObj == 3) || (this.checkObj == 4));return this;}
var usr = new Sniffer;
function GetWindowHeight(){if(usr.Mac && usr.checkObj == 1){return window.innerHeight;}else if(usr.Win && usr.checkObj == 1){return window.innerHeight - 16;}else if(usr.checkObj == 4){return window.innerHeight - 15;}else if(usr.OPERA || usr.checkObj == 2 || usr.checkObj == 3){return d.body.clientHeight;}}
function GetWindowXOffset(){if(usr.checkObj == 2 || usr.checkObj == 3){return d.body.scrollLeft;}else if(usr.checkObj == 1 || usr.checkObj == 4){return window.pageXOffset;}}
function GetWindowYOffset(){if(usr.checkObj == 2 || usr.checkObj == 3){return d.body.scrollTop;}else if(usr.checkObj == 1 || usr.checkObj == 4){return window.pageYOffset;}}
function GetDocHeight(){if(usr.checkObj == 1){return GetTagTop('end') + 1;}else if(usr.checkObj == 2 || usr.checkObj == 3 || usr.checkObj == 4){return GetTagTop('end');}}
function GetDistanceMaxY(){if(usr.allObj){return (GetDocHeight() - GetWindowHeight());}}
function SetObj(idName){return d.all ? d.all(idName) : d.getElementById ? d.getElementById(idName) : d.layers[idName];}
function GetTagTop(idName){var obj = SetObj(idName);var tagCoords = new Object();if(usr.OPERA && usr.Mac){return idName;} else if((usr.checkObj == 2) || (usr.checkObj == 3) || (usr.checkObj == 4)) {tagCoords.y = obj.offsetTop;while ((obj = obj.offsetParent) != null){tagCoords.y += obj.offsetTop;}if(usr.Mac && usr.Moz){return tagCoords.y - 12;}else if((usr.Win && usr.Moz) || (usr.Mac && usr.SAFARI)){return tagCoords.y - 9;}else{return tagCoords.y;}} else if(usr.checkObj == 1) {tagCoords.y = d.anchors[idName].y;return tagCoords.y;}return idName;}
/*PageScroller*/
var PageScrollTimer;
function pageScroll(toX,toY,frms,frX,frY){if(PageScrollTimer) clearTimeout(PageScrollTimer);var spd = usr.Mac ? 14 :16;	var actX = GetWindowXOffset();var actY = GetWindowYOffset();if(!toX || toX < 0) toX = 0;if(!toY || toY < 0) toY = 0;if(!frms) frms = usr.NN ? 10 :usr.Mac ? 4 :5;if(!frX) frX = 0 + actX;if(!frY) frY = 0 + actY;frX += (toX - actX) / frms;if (frX < 0) frX = 0;frY += (toY - actY) / frms;if (frY < 0) frY = 0;var posX = Math.ceil(frX);	var posY = Math.ceil(frY);	window.scrollTo(posX, posY);if((Math.floor(Math.abs(actX - toX)) < 1) && (Math.floor(Math.abs(actY - toY)) < 1)){clearTimeout(PageScrollTimer);	window.scroll(toX,toY);	}else if(posX != toX || posY != toY){PageScrollTimer = setTimeout("pageScroll("+toX+","+toY+","+frms+","+frX+","+frY+")",spd);}else{clearTimeout(PageScrollTimer);}}
function JumpToAnchor(idName){if(usr.allObj){if(!!idName){var anchorY = GetTagTop(idName);var dMaxY = GetDistanceMaxY();var setY = (anchorY<1)?0:(anchorY>dMaxY)?dMaxY:anchorY;if(anchorY>1){pageScroll(0,setY);}else if(anchorY<=1){pageScroll(0,0);}else{location.hash = idName;}}else{pageScroll(0,0);}}else{!!idName ? location.hash = idName : location.hash = "top";}}
function JumpToPageTop(){if(usr.allObj){pageScroll(0,0);}else{!!idName ? location.hash = idName : location.hash = "top";}}

/** VALIDACAO DE NUMERO DE CONTRIBUINTE ********
**
** funcao principal: ValidaNumeroContribuinte(nContribuinte)
**	
***********************************************/
// CheckDigitoContribuinte
// Verifica se o nmero de contribuinte é correcto atraves do seu Check Digito
// Retorna boleano (true em caso de sucesso)
function CheckDigitoContribuinte(numeroContribuinte)
{
	var checkDigito, div, soma = 0;
	if(numeroContribuinte.charAt(0).toUpperCase() != 'X')
	{
		if(numeroContribuinte != ""){

			for(var i=0; i < 8; i++)
			{
				soma += (9-i) * numeroContribuinte.charAt(i);
			}
			
			soma = parseInt(soma, 10);
			
			div = parseInt(soma/11, 10);

			checkDigito = 11 - (soma - (div * 11));
			
			if (checkDigito > 9)
				checkDigito = 0;

			if (numeroContribuinte.charAt(8) == checkDigito)
				return true;
			else
				return false;
		}
		else
			return false;
	}
	else
		return true;
}

// ValidaNumeroContribuinte
// Valida o Numero de Contribuinte dado (formato e checkDigito)
function ValidaNumeroContribuinte(nContribuinte)
{
	if(nContribuinte.charAt(0) == 'X')
	{
		return true;
	}
	else
	{
		
		if(!CheckDigitoContribuinte(nContribuinte))
		{
			return false;
		}
		else
		{
			return true;
		}
	} 
}

// Retorna o resto inteiro da divisão
function mod(number1, number2)
{
	return (number1 - (Math.floor(number1/number2)*number2));
}

/** VALIDACAO DE NIB ***************************
**
** funcao principal: validaNIB(nib)
**	
***********************************************/
// Verifica os 2 check digits do NIB
function checkDigitosNIB(nib)
{	
	var soma = 0, checkDigits, checkDigit1, checkDigit2;
	
	// Array usado como chave
	var keyCheckArray = new Array(73, 17, 89, 38, 62, 45, 53, 15, 50, 5, 49, 34, 81, 76, 27, 90, 9, 30, 3);

	for (var i=0; i < 19; i++)
		soma += keyCheckArray[i] * nib.charAt(i);

	checkDigits = 98 - (mod(soma,97));
	checkDigit1 = Math.floor(checkDigits/10);
	checkDigit2 = mod(checkDigits, 10);
	
	if (nib.charAt(19) == checkDigit1 && nib.charAt(20) == checkDigit2)
		return true;
	else
		return false;
}

// Valida o nib especificado (formato e check digits)
function validaNIB(nib){
	if (nib != "" && validaNumero(nib))
	{
		if (nib.length == 21)
			return checkDigitosNIB(nib);
		else
			return false;
	}
	else
		return false;
}

/** VALIDACAO DE HORA *************************
 **
 ** funcao principal: validaHora(hora)
 **	
 ***********************************************/
/*funcao que valida se uma hora se encontra no formato XX:XX:XX ou XX:XX
  argumentos entrada: string hora
  argumentos saida: boolean
 */
function validaHora(hora)
{		
	var formatoValido = hora.match(/^([01][0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?$/);

	if (formatoValido != null)
		return true;
	else
		return false;	
}

/** VALIDACAO DE DATAS *************************
 **
 ** funcao principal: validaData(data)
 **	
 ***********************************************/
/*funcao que valida uma data se encontra no formato aaaa-mm-dd
  argumentos entrada: string data
  argumentos saida: boolean
 */
function validaData(data)
{
	
	var re = {dia:"\\d\\d",mes:"\\d\\d",ano:"\\d\\d\\d\\d" };
	var separador = "\\-";
	
	var re_str  = re.ano + separador + re.mes + separador + re.dia;
	
	//Transforma a data para o formato aaaa-mm-dd
	//data = transforma(data);
	var formatoValido = data.match(new RegExp(re_str,"gmi"));
	//Se o formato estiver valido
	if(formatoValido != null)
	{
		
		var ano = data.substr(0,4);
		var mes = data.substr(5,2);
		var dia = data.substr(8,2);
		
		//validacao da data
		//retorna "" se a data for valida, caso contrario retorna com a mensagem 'Data Invalida'
		if(checkData(dia,mes,ano,"Data Invalida") == "")
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;
	}
}

//coloca data no formato ano-mes-dia
//nao faz qq validacao ao nivel dos campos
function transforma(ano, mes, dia){
	var m = mes; 
	var d = dia;
	//se o mes so tem 1 digito
	if(mes.length == 1){
		m = '0' + mes;
	}
	if(dia.length==1){
		d = '0' + dia;
	}

	var data = ano + '-' + m + '-' + d;
	return data;
			
}

//transforma uma data para o formato aaaa-mm-dd
function transforma(strData){
	var newData = "";
	var re_strChar = "\\w";

	if(strData.length == 8)
	{
		//aaaa-m-d
		if(strData.charAt(4).match(new RegExp(re_strChar,"gmi")) == null && strData.charAt(6).match(new RegExp(re_strChar,"gmi")) == null)
		{
			newData = strData.substr(0,4) + '-0' + strData.substr(5,1) + '-0' + strData.substr(7,1);
		}
		//d-m-aaaa
		else if(strData.charAt(1).match(new RegExp(re_strChar,"gmi")) == null && strData.charAt(3).match(new RegExp(re_strChar,"gmi")) == null)
		{
			newData = strData.substr(4,4) + '-0'+ strData.substr(2,1) + '-'+ '0' + strData.substr(0,1);
		}			 
		else  //ddmmaaaa
		{
			newData = strData.substr(4,4) + '-' + strData.substr(2,2) + '-' + strData.substr(0,2);
		}
	}
	else if(strData.length == 9)
	{
		
		//aaaa-mm-d	
		if(strData.charAt(4).match(new RegExp(re_strChar,"gmi")) == null && strData.charAt(7).match(new RegExp(re_strChar,"gmi")) == null)
		{	
			newData = strData.substr(0,4) + '-' + strData.substr(5,2) + '-0' + strData.substr(8,1);			
		}
		//aaaa-m-dd	
		else if(strData.charAt(4).match(new RegExp(re_strChar,"gmi")) == null && strData.charAt(6).match(new RegExp(re_strChar,"gmi")) == null)
		{	
			
			newData = strData.substr(0,4) + '-0' + strData.substr(5,1) + '-' + strData.substr(7,2);			
		}
		//d-mm-aaaa
		else if(strData.charAt(1).match(new RegExp(re_strChar,"gmi")) == null && strData.charAt(4).match(new RegExp(re_strChar,"gmi")) == null)
		{
			
			newData = strData.substr(5,4) + '-' + strData.substr(2,2) + '-' + '0' + strData.substr(0,1);
		}
		//dd-m-aaaa
		else if(strData.charAt(2).match(new RegExp(re_strChar,"gmi")) == null && strData.charAt(4).match(new RegExp(re_strChar,"gmi")) == null)
		{
			
			newData = strData.substr(5,4) + '-0' + strData.substr(3,1) + '-' + strData.substr(0,2);
		}
	}
	else if(strData.length == 10)
	{
		//aaaa-mm-dd
		if(strData.charAt(4).match(new RegExp(re_strChar,"gmi")) == null && strData.charAt(7).match(new RegExp(re_strChar,"gmi")) == null)
		{	
			newData = strData.substr(0,4) + '-' + strData.substr(5,2) + '-' + strData.substr(8,2);			
		}
		//dd-mm-aaaa	
		else
		{	
			newData = strData.substr(6,4) + '-' + strData.substr(3,2) + '-' + strData.substr(0,2);			
		}
	}
	else
		newData = strData;

	if ((!isNaN(newData.substr(0,4))) && (!isNaN(newData.substr(5,2))) && (!isNaN(newData.substr(9,2))))
		return newData;
	else
		return strData;
}

//funcao que verifica se um codigo postal esta no formato cccc-ccc
function validaCodigoPostal(cp)
{
	var re_str = "\\d\\d\\d\\d\\-\\d\\d\\d";
	var check = cp.match(new RegExp(re_str,"gmi"));
		
	if(check==null)
	{
		return false;
	}
	else{
		return true;
	}
		
}

//funcao que valida se uma string e numero
function isNumero(valor){
	return !isNaN(valor);
}

//TODO:Para Remover e passar a chamar a funcao isNumero() onde for necessario
//funcao que verifica se uma string e formada somente por caracteres numericos
function isStringNumero(valor){
	return isNumero(valor);
}

// Funcao que constroi uma mensagem com os dados contidos na lista de erros
//e retorna essa mensagem 
function constroiMsgErro(listaErros)
{
	var msgErro = "";	

	for (var i = 0; i < listaErros.length; i++)
	{
		if((i+2) < listaErros.length)
		{
			msgErro += listaErros[i] + ', ';
		}
		else if((i+2) == listaErros.length)
		{
			msgErro += listaErros[i] + ' e ';
		}
		else
		{
			msgErro += listaErros[i];
		}
	}
	
	return msgErro;					
}

//retorna uma mensagem completa
function constroiMsgErro2(listaErros){
	var camposInvalidos = "";
	var msgErro = "";
	//Varios Erros		
	if(listaErros.length > 1)
	{	
		for (var i = 0; i < listaErros.length; i++)
		{
			if((i+2) < listaErros.length)
			{
				camposInvalidos += listaErros[i] + ', ';
			}
			else if((i+2) == listaErros.length)
			{
				camposInvalidos += listaErros[i] + ' e ';
			}
			else
			{
				camposInvalidos += listaErros[i];
			}
		}

		msgErro = "Os campos <i>"+ camposInvalidos + "</i> est&atilde;o num formato inv&aacute;lido ou n&atilde;o est&atilde;o especificados.";
	}//1 Erros
	else
	{
		camposInvalidos = listaErros[0];
		msgErro = "O campo <i>"+ camposInvalidos + "</i> est&aacute; num formato inv&aacute;lido ou n&atilde;o est&aacute; especificado.";
	}

		return msgErro;				
}

//funcao que apresenta a mensage de erro em Javascript
function showMsgErro(msgErro){
	//Limpa a mensagem presente no msgServer
	limparMsgErros();
	//Vai para o topo da pagina
	scrollPaginaTopo();
	if(document.getElementById('msgServer') != null)
			document.getElementById('msgServer').visible = false;
	document.getElementById('msgJavascript').visible = true;
	document.getElementById('mensagemJavascript').innerHTML = msgErro;					
}

//Funcao que limpa as mensagens de erros
function limparMsgErros()
{
	if(document.getElementById('msgServer') != null)
	{
		document.all.msgServer.removeNode(true);
	}	

	document.getElementById('msgJavascript').visible = false;
	document.getElementById('mensagemJavascript').innerHTML = "";	
}

//Para ser usado somente em paginas de pesquisa
function limparMsgResultados()
{
	limparMsgResultados('PainelDados');
}

function limparMsgResultados(objID)
{
	if(document.getElementById(objID)!= null)
	{
		document.getElementById(objID).style.visibility = "hidden";
	}
}

// Valida se uma dada string e um numero decimal.
// Retorna true, se a string alem de conter caracteres numericos conter espacos, ou uma virgula
// ou um ponto
// Formatos validos da string de entrada: '9999' ou '9 999.999' ou '99 9999,999'
function validaNumero(str)
{
	//Eliminar espacos
	str = str.replace(/\s/g,'');

	if (str.length != 0)
	{
	
		var tmpStr = new String(str)
		//Obter as substrings que estao separadas por virgulas (1 caso nao exista)
		var splitStringArray1 = tmpStr.split(",");
		//Obter as substrings que estao separadas por pontos (1 caso nao exista)
		var splitStringArray2 = tmpStr.split(".");

		//Se a soma dessas substrings for <= 3, entao e porque contem so uma virgula ou so um ponto (ou nenhum deles)
		if((splitStringArray1.length + splitStringArray2.length) <= 3)
		{
			tmpStr = tmpStr.replace(",", ".");
			return !isNaN(tmpStr);
		}
		else
		{
			// Existem varias virgulas e/ou pontos 
			return false;
		}
	}
	else
		return true;
}
			
function PopUpWebPublishing(parametro, wpSession, opcaoMenuCentral) 
{
	var win;
	var date = new Date();
	
	// Colocamos um parametro sempre diferente de forma que o Browser nunca use a cache
	parametro += "&t=" + date.getTime();

	// Primeiro fechamos a janela antiga caso exista. Caso não exista, nunca aparece no ecrã.
	win = window.open('', wpSession, 'left=3000,top=3000');
	if (win != null) {
		win.close();
	}
	
	win = window.open("/Site/WebPublishing/WebPublishing.aspx?" + parametro + "&OpcaoMenuCentral=" + opcaoMenuCentral, wpSession, "menubar=no,resizable=no,toolbar=no,status=no,location=no,width=640,height=480");
	if (win != null) {
		win.focus();
		return true;
	}
	return false;
}
			
// Esta função é para desaparecer!! Deve-se usar antes a PopUpWebPublishing			
function PopUpWebPublishingHeader(parametro,wpSession) 
{
	var win;

	var date = new Date();
	
	// Colocamos um parametro sempre diferente de forma que o Browser nunca use a cache
	parametro += "&t=" + date.getTime();

	// Primeiro fechamos a janela antiga caso exista. Caso não exista, nunca aparece no ecrã.
	win = window.open('', wpSession, 'left=3000,top=3000');
	if (win != null) {
		win.close();
	}

	win = window.open("/Site/WebPublishing/WebPublishing.aspx?" + parametro, wpSession, "menubar=no,resizable=no,toolbar=no,status=no,location=no,width=640,height=480");
	if (win != null) {
		win.focus();
		return true;
	}
	
	return false;
}

//converte tamanhos com ou sem px para inteiro
function getSizeInt( inSize ) {
	var auxString = new String(inSize);
	var widthInt = 0;
	if (auxString.search('\px') != -1)
		return parseInt(auxString.substring(0,auxString.search('\px'))); 
	else
		return parseInt(auxString);	
}

function ConstroiHTMLListBox(idCombo, widthCampoDescricao, codigoVisible, showInput, codigoSize, onFocus, onBlur, tabIndex, readOnly, widthCampoCodigo, blankOptionDescription)
{
	var strHTML = '';
	var idDiv = 'divListBox_' + idCombo;
	var idCampoCodigo = 'fCodigo_' + idCombo;
	var idCampoDescricao = 'fDescricao_' + idCombo;
	var idBtnOpenClose = 'btnOpenClose_' + idCombo;

	var sizeTable = 0;

	sizeTable = 15 + 5 + getSizeInt(widthCampoDescricao);
	if (codigoVisible == 'True')
		sizeTable += 30;

	strHTML = '<table width="' + sizeTable + '" cellspacing="0" cellpadding="1" border="0"><tr><td>';
	if (readOnly == 'False')			
		strHTML +=	'<input id="' + idBtnOpenClose+ '" type="button" class="txtbotaoPR" value="»" style="width:15px" onClick="showhideListBox(\'' + idCombo + '\',1)";>';
	else
	strHTML +=	'<input id="' + idBtnOpenClose+ '" type="button" class="txtbotaoPR" value="»" style="display:none;width:15px" onClick="showhideListBox(\'' + idCombo + '\',1)";>';
	strHTML +=	'</td>';

			
	if (codigoVisible == 'True'){
		strHTML += '<td><input type="text"';
		if (tabIndex != '')
			strHTML += ' tabIndex="' + tabIndex + '"';
		strHTML += ' maxlength=' + codigoSize + ' style="width:'+ widthCampoCodigo +'px" id=' + idCampoCodigo + ' name='+ idCampoCodigo +' class=';
		
		if (readOnly == 'False')
			strHTML += '"txtedit" onfocus="' + onFocus + '" onblur="hideListBox(\'' + idCombo + '\');' + onBlur + '" onkeyup="SelectEntryValue(\''+ idCombo + '\', event)" onkeydown="checkForOpenCombo(event, \'' + idCombo + '\')"></td>';
		else
			strHTML += '"txtnoedit"></td>';			
		}
	else 
		strHTML += '<td><input type="hidden" style="width:0px" id=' + idCampoCodigo + ' name='+ idCampoCodigo +' class="txtedit"></td>';
	
	
	if (showInput == 'True')
	{
		strHTML += '<td class="txtgeral" align="left"><input myEnabled="true" ';
		if ((tabIndex != '') && (codigoVisible != 'True'))
			strHTML += ' tabIndex="' + tabIndex + '"';
		strHTML += ' style="width:' + widthCampoDescricao + 'px" type="text" id=' + idCampoDescricao + ' name=' + idCampoDescricao + ' value="' + blankOptionDescription + '" class=';
		
		if (readOnly == 'False')
			strHTML += '"txtedit" ReadOnly onkeyup="handleListBoxKeyEvent(event, \'' + idCombo + '\')" onkeydown="checkForOpenCombo(event, \'' + idCombo + '\')" onfocus="' + onFocus + '" onblur="hideListBox(\'' + idCombo + '\');' + onBlur + '"></td>';
		else
			strHTML += '"txtnoedit" ReadOnly></td>';
	}
	else
		strHTML += '<td width='+ widthCampoDescricao +' id=' + idCampoDescricao + ' class="txtgeral" align="left" onkeydown="handleListBoxKeyEvent(event, \'' + idCombo + '\')"></td>';
	
	strHTML += 
		'</tr>' +
		'<tr>' +
			'<td bgcolor="#ffffff" coslpan="3">' +
			'<div id=' + idDiv + ' style=\"POSITION:absolute;Z-INDEX:0;VISIBILITY:hidden; border:0px solid black;background-color:#ffffff;\" ></div>' +
			'</td>' +
		'</tr>' +
	'</table>';
	
	document.write(strHTML);
}

//funcao para gerar a estrutura de dados
//Esta funcao deve ser usada em vez do comboElement
function cE(id,name)
{
	this.id = id;
	this.name = name;
}

//Construcao do array com os elementos é criado um array por cada modulo
function GerarArray(idCombo, jsSource, includeBlankOption, blankOptionDescription)
{	
	var arrayListBoxAux = new Array();
	//Verificar como forma de abastecimento da listbox JsArray ou tabelaCodigos
	if (jsSource != 'false')
	{
		
		var idxCombo = 0;
		var aux;	

		if (includeBlankOption == 'True')
		{
			arrayListBoxAux[0] = new cE("",blankOptionDescription);
			idxCombo = 1;
		}
		
		for (var j = 0; j < eval(jsSource).length; j += 2, idxCombo++)
		{
			aux = eval(jsSource)[j+1].replace(/'/g," ");
			arrayListBoxAux[idxCombo] = new cE(eval(jsSource)[j],aux);	
		}
		return arrayListBoxAux;
	}
	else
	{
		var funcName;
		funcName = 'GerarArraybyTabelaCodigos_'  + idCombo ;
		arrayListBoxAux = eval(funcName)(); 
		return arrayListBoxAux;
	}
}

//funcao responsavel por carregar o array com codigos e descricoes	
function doCombo(idCombo, widthListBox, heightListBox, arrayListBox, filterByCodigo, codigoListBoxVisible, codigoDefaultValue, codigoListBoxVisible, sizeDescricao, sizeTotal, onChange){
	
	var init = new Date().getTime();
	var divtext = document.getElementById("divListBox_" + idCombo);
	var arrayLen = eval(arrayListBox).length;
	var straux = '';
	var id, name;
	var bMostraCodigo = (codigoListBoxVisible == 'True');
	for (var i = 0; i < arrayLen; i++)
	{
			id = eval(arrayListBox)[i].id;
			name = eval(arrayListBox)[i].name;

			if (codigoDefaultValue == id)
			{
				document.getElementById("fCodigo_" + idCombo).value = id;
				document.getElementById("fDescricao_" + idCombo).value = name;
				document.getElementById("fDescricao_" + idCombo).title = name;
			}
			var aux = '<' + id + '><' + name + '>\n';
			straux += aux;
	}

	if (bMostraCodigo) {
		straux = straux.replace(/<([\20-\xff]*)><([\20-\xff]*)>\n/g, '<option value="$1">$1 - $2</option>');
	} else {
		straux = straux.replace(/<([\20-\xff]*)><([\20-\xff]*)>\n/g, '<option value="$1">$2</option>');
	}
	
	//tamanho do numero de opções a mostrar
	var lengthListBox = eval(arrayListBox).length;
	if (lengthListBox > 8)
		lengthListBox = 8;
	//para evitar que apareça a dropdown na lista
	if (lengthListBox == 1)
		lengthListBox = 2;
	//inicio do calculo da largura
	var sizeListBox;
	if (bMostraCodigo)
		sizeListBox = sizeTotal;
	else
		sizeListBox = sizeDescricao;
	//borders da select
	sizeListBox += 8;
	// a barra de scrool
	if (eval(arrayListBox).length > 8)
		sizeListBox += 18;
	//redimensionar caso saiba que não tenho espaço para mostrar tudo

	if (getSizeInt(widthListBox) < sizeListBox)
		widthListBox = sizeListBox;
	//TODO: Fazer o calculo do size="??" conforme o heightListBox (Hugo : Acho que não vale a pena fazer este calculo basta encurtar o size da list box)
	divtext.innerHTML = '<select onchange="' + onChange + '" onclick="listBoxComboClick(\'' + idCombo + '\')" id="fSelect_' + idCombo + '" onblur="hideListBox(\'' + idCombo + '\')" size="'+lengthListBox+'" style="width:' + widthListBox + ';background-color: #ffffff; overflow:auto; FONT-SIZE: 11px; COLOR: #000000; FONT-FAMILY: Arial;" onkeydown="checkForOpenCombo(event, \'' + idCombo + '\')">' + straux + '</select>';
	var selectElement = document.getElementById('fSelect_' + idCombo);
	if (selectElement.options.length >= 0) {
		selectElement.selectedIndex = 0;
		for (var i=0; i < selectElement.options.length; i++) 
			if (selectElement.options[i].value == codigoDefaultValue)
				selectElement.selectedIndex = i;	
	}
	var end = new Date().getTime();
	//document.getElementById("fDescricao_" + idCombo).title += ' -> ' + (end - init);
}

// checkForOpenCombo
// Verifica se a lista está visivel. Caso esteja visivel, coloca o valor seleccionado na combo, e fecha a lista.
function checkForOpenCombo(evt, idCombo)
{
	var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode
	if (document.getElementById('divListBox_' + idCombo).style.visibility == 'visible') {
		// Para o caso do utilizador carregar em BACKSPACE o browser não fazer o BACK
		if (keyCode == 8)  {
			event.keyCode = 0;
			return false;
		}
		if ((keyCode == 13) || (keyCode == 27)) {
			event.keyCode = 0;
			listBoxComboClick(idCombo);
			return false;
		}
	}
}

// Variavel global de forma ser possivel ignorar o hideListBox
var IgnoreNextHideListBox = false;
// Fecha uma lista
function hideListBox(idCombo)
{
	if (IgnoreNextHideListBox == true) {
		IgnoreNextHideListBox = false;
	} else {
		document.getElementById('divListBox_' + idCombo).style.visibility = 'hidden';
		TimerLastOpenedListBoxID = setTimeout('clearLastOpenedListBox()', 500);
	}
}

// Abre uma lista
function showListBox(idCombo)
{	
	//Teste
	var descElement = document.getElementById('fDescricao_' + idCombo);
	var comboElement = document.getElementById('fCodigo_' + idCombo);
	var	divElement = document.getElementById('divListBox_' + idCombo);
	var selectElement = document.getElementById('fSelect_' + idCombo);
	var arrayName = "arrayListBox_" + idCombo
	var arrayLength = selectElement.options.length;
	//var hasChanged = false;
	var index = -1;
	//Fimteste 
	// Assinalamos que abrimos uma ListBox
	LastOpenedListBox = idCombo;

	//Calculo para verificar se a dimensao da div não excede a tabela geral de forma a que a div seja puxada para a esquerda.
	if (document.getElementById('divListBox_' + idCombo).style.left == ''){
		var tabelaGeralRight;
		var tableElements = document.getElementsByTagName("TABLE");
		for (var i = 0 ; i < tableElements.length ; i++)
			if ((tableElements[i].className == 'tblgeral') || (tableElements[i].className == 'tblgeral1'))
			{
				tabelaGeralRight = tableElements[i].offsetLeft + tableElements[i].offsetWidth;
				break;
			}
		var thisDivRight = document.getElementById('divListBox_' + idCombo).offsetLeft + document.getElementById('divListBox_' + idCombo).offsetWidth;
		var tabelaGeralRightNumber = new Number(tabelaGeralRight);
		var thisDivRightNumber = new Number(thisDivRight)
		if ((tabelaGeralRightNumber - thisDivRightNumber) < 0 ){
			document.getElementById('divListBox_' + idCombo).style.left = document.getElementById('divListBox_' + idCombo).offsetLeft + (tabelaGeralRightNumber - thisDivRightNumber) + 'px';
		}
	}
	// Agora sim...
	document.getElementById('divListBox_' + idCombo).style.visibility = 'visible';		
}

//listBoxComboClick
//Coloca no elemento dado por parametro o valor da combo
//Esta funcao é utilizada para em javascript forcar um elemento como o default
function listBoxComboClick(idCombo)
{	
	var comboElement = document.getElementById('fCodigo_' + idCombo);
	var selectElement = document.getElementById('fSelect_' + idCombo);
	var descElement = document.getElementById('fDescricao_' + idCombo);
	var arrayName = "arrayListBox_" + idCombo
	var index = selectElement.selectedIndex;
	if (index == null || index == -1) return false;

	comboElement.value = selectElement.options[index].value;
	
	//atenção martelada
	var separador = " - ";
	var valorDescricao = selectElement.options[index].text;
	valorDescricao = valorDescricao.replace(comboElement.value + separador,"");

	descElement.value = descElement.title = valorDescricao;
	
	MarcaCampoSeleccionado(document.getElementById('fDescricao_' + idCombo));
	hideListBox(idCombo);
}

function MarcaCampoSeleccionado (selectElement)
{
	selectElement.select();	
	selectElement.focus();
}

function clearLastOpenedListBox()
{
	LastOpenedListBox = '';
}

// Variavel global para evitar que aconteca o seguinte fenomeno:
// a) O select com as opções de list box, tem o evento 'onblur' que chama o hideComboBox
// b) Quando se faz o click em cima do botão abre/fecha de uma list box, o browser chama primeiro o evento 'onblur'
//	  do select, fechando a combo box
// c) Quando é chamada a função 'showHideListBox', a list box já está 'hidden', voltando a abrir, nunca chegando 
//    realmente a fechar.
var LastOpenedListBox = '';
// Temporizador que limpa o LastOpenedListBox caso ocorra um onblur (hideListBox) e não seja chamado um showHideListBox
var TimerLastOpenedListBoxID;

//funcao responsavel por efectuar o show/hide da Lisbox
function showhideListBox(idCombo, state)
{	
	var currentObj = document.getElementById("divListBox_" + idCombo).style
	var currentStyle = currentObj.visibility;
	
	// Cancelamos o timer...
	clearTimeout(TimerLastOpenedListBoxID);
	
	if (currentStyle == 'hidden')
	{
		// Assinalamos que abrimos a combo box...
		if (LastOpenedListBox == idCombo) {
			// Limpamos o valor, e para a proxima já vai estar OK!
			LastOpenedListBox = '';
		} else {
			LastOpenedListBox = idCombo;
			showListBox(idCombo);
			document.getElementById('fSelect_' + idCombo).focus();
		}
	}
	else 
	{
		hideListBox(idCombo);
	}
}

/* handleListBoxKeyEvent
 *
 * Trata os eventos de teclado quando estes sao disparados pela lista de opcoes.
 * a) Caso seja primido o cursor para cima/baixo, recua/avança na lista
 * b) Caso seja primida uma letra, avança até ao item cuja descrição comece por essa letra
 * c) Caso seja primida a tecla ESCAPE, ou ENTER, fecha a combo.
*/
function handleListBoxKeyEvent(evt, idCombo)
{	
	var descElement = document.getElementById('fDescricao_' + idCombo);
	var comboElement = document.getElementById('fCodigo_' + idCombo);
	var	divElement = document.getElementById('divListBox_' + idCombo);
	var selectElement = document.getElementById('fSelect_' + idCombo);
	var arrayName = "arrayListBox_" + idCombo
	var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode
	var arrayLength = selectElement.options.length;

	//var hasChanged = false;
	var index = -1;
	
	if (descElement.myEnabled != "true") 
		return false;

	// Para o caso do utilizador carregar em BACKSPACE o browser não fazer o BACK
	if (keyCode == 8) {
		event.keyCode = 0;
		return false;
	} else if (keyCode == 13) {
		// Caso seja carregado em ESCAPE ou ENTER, fechamos a combo box
		hideListBox(idCombo);
		comboElement.value = selectElement.options[selectElement.selectedIndex].value;
		event.keyCode = 0;
		return false;
		
	} else if ((keyCode == 40) || (keyCode == 38)) {
		
		showListBox(idCombo);
		selectElement.focus();
		
		//Teste para marcar a primeira vez quando a combo é aberta com as teclas
		for (var i = 0; i < arrayLength; i++) {
			if (selectElement.options[i].value == comboElement.value)
			{
				index = i;
				break;
			}
		}
		//alert(index)
		// Agora sim...
		selectElement.selectedIndex = index;	
		// Quando o elemento perde o focus, faz o hideListBox, e nós não queremos isso...
		IgnoreNextHideListBox = true;
		return true;
	}
	// Caso seja uma letra, escolhemos a primeira entrada cuja descricao comece pela letra primida
	else if (((keyCode > 64) && (keyCode < 91)) || ((keyCode > 96) && (keyCode < 123)) || ((keyCode > 47) && (keyCode < 58))) {
		// Colocamos em UpperCase
		//alert("aqui");
		if (keyCode > 96) keyCode -= 32;
		for (var i = 0; i < arrayLength; i++) {
			if (selectElement.options[i].text.toUpperCase().charCodeAt(0) == keyCode)
			{
				index = i;
				break;
			}
		}
	
	// Quando o elemento perde o focus, faz o hideListBox, e nós não queremos isso...
		IgnoreNextHideListBox = true;
	if (index != -1) {
		// Caso a div não esteja visivel, passa a ficar!
		showListBox(idCombo);
		
		// Caso não se efectue esta linha, o comportamento é estranho...
		if (selectElement.selectedIndex == -1) {
			selectElement.selectedIndex = 0;
		}
		// Agora sim...
		selectElement.selectedIndex = index;
		selectElement.focus();
		comboElement.value = selectElement.options[index].value;
		descElement.value = selectElement.options[index].text;	
		descElement.title = selectElement.options[index].text;

		}
	}
}

function SelectEntryValue(idCombo, evt)
{
	var selectElement = document.getElementById('fSelect_' + idCombo);
	var descElement = document.getElementById('fDescricao_' + idCombo);
	var comboElement = document.getElementById('fCodigo_' + idCombo);
	var arrayName = "arrayListBox_" + idCombo
	var arrayLength = selectElement.options.length;
	var codeExists = false;
	
	var keyCode;
	if (evt != null)
		keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
	else
		keyCode = 0;

	
	// Caso o keyCode seja 38 (cursor para cima) ou 40 (cursor para baixo), 
	// seleccionamos o item anterior, ou o proximo
	if ((keyCode == 38) || (keyCode == 40) || (keyCode == 27) || (keyCode == 13)) {
		return handleListBoxKeyEvent(evt, idCombo);
	} else {

		descElement.value = '';
		descElement.title = '';

		for (var j = (comboElement.value.length); j >= 0; j--) {
			var valor = comboElement.value.substring(0, j).toUpperCase();
			for (var i = 0; i < arrayLength; i++)
			{
				var id = selectElement.options[i].value;
				if (id.substring(0, j).toUpperCase() == valor && ((keyCode == 0 && id.length == valor.length) || keyCode != 0 ))
				{
					comboElement.value = valor;
					descElement.value = selectElement.options[i].text;	
					descElement.title = selectElement.options[i].text;
					

					
					codeExists = true;

					// Seleccionamos a entrada certa...
					var newElement = document.getElementById(idCombo + '__' + selectElement.options[i].value);
					// Caso nao se efectue esta linha, o comportamento é estranho...
					if (selectElement.selectedIndex == -1) {
						selectElement.selectedIndex = 0;
					}
					// Agora sim...
					selectElement.selectedIndex = i;

					// Para o caso em que a função é chamada directamente
					if (evt != null) {	
						// Forcamos o focus na linha da div com o valor actual de forma a fazer o scroll da lista...
						showListBox(idCombo);
					}

					break;
				}
			}
			if (codeExists == true) break;
		}
	}
}

function FilterListBoxValues(idCombo, filter, blankOption, testText){
	var selectElement = document.getElementById('fSelect_' + idCombo);
	var descElement = document.getElementById('fDescricao_' + idCombo);
	var comboElement = document.getElementById('fCodigo_' + idCombo);

	var arrayLen = eval('arrayListBox_'+idCombo).length;
	var RexExpression = new RegExp(	filter , '');
	var option,value,text,testValue;
	var index = 0;
	selectElement.length = 0;
	descElement.value = "";
	comboElement.value = "";
	
	if (blankOption)
		selectElement.options[index++] = new Option("-- Seleccionar --", "", false);
		
	for (i = 0; i < arrayLen; i++) {
		value = eval('arrayListBox_'+idCombo)[i].id;
		text = eval('arrayListBox_'+idCombo)[i].name;
		if (testText)
			testValue = text;
		else
			testValue = value;
		
		if (RexExpression.test(testValue))
			selectElement.options[index++] = new Option(text, value, false);
	}
	selectElement.selectedIndex = 0;
	descElement.value = selectElement.options[0].text;
	comboElement.value = selectElement.options[0].value;
}

function GetListBoxSelect(idCombo){
	return document.getElementById('fSelect_' + idCombo);
}

function GetListBoxDescricao(idCombo){
	return document.getElementById('fDescricao_' + idCombo);
}

function GetListBoxCodigo(idCombo){
	return document.getElementById('fCodigo_' + idCombo);
}

// Chama a pop up com os Detalhes de um User da FidelidadeMundial.
/*
	Funcao que abre uma pop-up(780x550) com a pagina de Detalhe Lista Telefonica.
	Parametros: userName	-> String UserName					
*/
function PopUpConsultarListaTelefonica(userName, url)
{
//	showMsgErro("");
	if (userName == "")
		return 0;

	var url =  url + "Site/Comum/Utilitarios/PopUpPesquisarListaTelefonica.aspx?detalhe=expandido&fUserName=" + userName;
	var name = "DetalheListaTelefonica";
	var height = "450";
	var width = "790";
	var positionX = "0";
	var positionY = "0";
	var scrollbar = "yes";
		
	win = NewWindow(url, name, width,height, scrollbar, positionX, positionY);
		
	if(win != null)
		win.focus();
}

// Chama a pop up com os modelos EuroTax.
/*
	Funcao que abre uma pop-up(640x550) com a pagina de Motivos de Alteracao.
	Parametros: NApolice	-> Numero de apolice
				NTransaccao -> Numero de transaccao W424B
				NURisco		-> Numero da unidade de Risco (Não aplicavel nesta página)
				Produto		-> Tipo de Produto
				Lob			-> Line of Business
					
*/

// Adiciona um determinado numero de espacos a uma chave do tipo string.
function AdicionaEspacosChave(chave, numeroEspacos)
{
	while(chave.length < numeroEspacos)
	{
		chave += " ";
	}

	return chave;
}


// Funcao que permite receber o id de uma listBox e colocar o input da descricao
// not enable, desaparece o botao e nao permite visualizar a listbox ( Simula o readonly do modulo da listBox)
function ListBoxReadOnly(id,flag)
{
    var idCampoDescricao = 'fDescricao_' + id;
    var idCampoCodigo = 'fCodigo_' + id;
	var tmpClass;
	var tmpDisplay;
	
	if (flag){
	tmpClass = "txtnoedit";
	tmpDisplay ="none";
	if (document.getElementById("fCodigo_" +id).value == '')
	    document.getElementById("fDescricao_"+id).value = '';
	}else
	{
	tmpClass = "txtedit";
	tmpDisplay ="";
	}
	var inputDescricao = document.getElementById("fDescricao_"+id);
	var inputSelect = document.getElementById("fSelect_" +id).value;
	
	inputDescricao.className = tmpClass;
	inputDescricao.readOnly = flag;
	inputSelect.checked = flag;
	inputDescricao.myEnabled = (!flag).toString();
	
	document.getElementById("btnOpenClose_"+id).style.display = tmpDisplay;
}

function ListBoxHide(id,flag)
{
	var tmpDisplay;
	
	if (flag)
		tmpDisplay ="none";
	else
		tmpDisplay ="";
	
	var inputDescricao = document.getElementById("fDescricao_"+id);
	
	inputDescricao.style.display = tmpDisplay;
	document.getElementById("btnOpenClose_"+id).style.display = tmpDisplay;
}


function InputTextReadOnly(id,flag){
	var tmpClass;
	
	if (flag)
		tmpClass = "txtnoedit";
	else
		tmpClass = "txtedit";

	var inputDescricao = document.getElementById(id);
	inputDescricao.className = tmpClass;
	inputDescricao.readOnly = flag;
}

function URLEncode(inString)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = inString;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" + ch + "' cannot be encoded using standard URL encoding.\n" +
				        "(URL encoding only supports 8-bit characters.)\n" +
						"A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
};

function URLDecode(inString)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var encoded = inString;
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;
}
function ColocaBotoesDisable(arrayBotoes)
{	
	for(var i=0; i < arrayBotoes.length;i++)
	{
		if (document.getElementById(arrayBotoes[i]) != null)
			document.getElementById(arrayBotoes[i]).disabled = true;
	}	
	
}

function VerificaBotoesDisable(arrayBotoes)
{
	for(var i=0; i < arrayBotoes.length;i++)
	{
		if ((document.getElementById(arrayBotoes[i]) != null) && (document.getElementById(arrayBotoes[i]).disabled == false))
				return false;
	}
	if (i == arrayBotoes.length)
		return true;
	else
		return false;
}

function LimparCamposGenerico(ArrayCamposInput, ArrayListBoxes) {
	if ((ArrayCamposInput != null)&& (ArrayCamposInput.length != 0))
		for (var i = 0 ; i < ArrayCamposInput.length ; i = i+2 )
			document.getElementById(ArrayCamposInput[i]).value = ArrayCamposInput[i+1];
	
	if ((ArrayListBoxes != null) && (ArrayListBoxes.length != 0))
		for (var i = 0 ; i < ArrayListBoxes.length ; i = i+2) {
			document.getElementById('fCodigo_' + ArrayListBoxes[i]).value = ArrayListBoxes[i+1];
			SelectEntryValue(ArrayListBoxes[i]);
	}
}

function ValidaDadosPaginaGenerico(ArrayCamposData, ArrayCamposHora, ArrayCamposObrigatorios,ArrayCamposNumero,ArrayCamposCodigoPostal){
	var dadosInvalidosTotal = new Array(0);
	
	if ((ArrayCamposObrigatorios != null) && (ArrayCamposObrigatorios.length != 0))
		dadosInvalidosTotal = dadosInvalidosTotal.concat(ValidaCamposObrigatoriosGenerico(ArrayCamposObrigatorios));
		
	if ((ArrayCamposData != null) && (ArrayCamposData.length != 0))
		dadosInvalidosTotal = dadosInvalidosTotal.concat(ValidaDatasGenerico(ArrayCamposData));

	if ((ArrayCamposHora != null) && (ArrayCamposHora.length != 0))
		dadosInvalidosTotal = dadosInvalidosTotal.concat(ValidaHorasGenerico(ArrayCamposHora));

	if ((ArrayCamposNumero != null) && (ArrayCamposNumero.length != 0))
		dadosInvalidosTotal = dadosInvalidosTotal.concat(ValidaNumerosGenerico(ArrayCamposNumero));
	
	if ((ArrayCamposCodigoPostal != null) && (ArrayCamposCodigoPostal.length != 0))
		dadosInvalidosTotal = dadosInvalidosTotal.concat(ValidaCodigosPostaisGenerico(ArrayCamposCodigoPostal));

	return dadosInvalidosTotal;
}

function ValidaDatasGenerico(ArrayCamposData){
	var dadosInvalidosTemp = new Array(0);
	for (var i = 0 ; i < ArrayCamposData.length ; i = i + 2){
		if (document.getElementById(ArrayCamposData[i]) == null)
			alert("Campo " + ArrayCamposData[i] + " não encontrado");	
		document.getElementById(ArrayCamposData[i]).value = transforma(document.getElementById(ArrayCamposData[i]).value);
		if((!validaData(document.getElementById(ArrayCamposData[i]).value)) && (document.getElementById(ArrayCamposData[i]).value != ''))
			dadosInvalidosTemp = dadosInvalidosTemp.concat(ArrayCamposData[i+1]);	
	}
	return dadosInvalidosTemp;
}

function ValidaHorasGenerico(ArrayCamposHora){
	var dadosInvalidosTemp = new Array(0);
	for (var i = 0 ; i < ArrayCamposHora.length ; i = i + 2){
		if (document.getElementById(ArrayCamposHora[i]) == null)
			alert("Campo " + ArrayCamposHora[i] + " não encontrado");	
		document.getElementById(ArrayCamposHora[i]).value = transforma(document.getElementById(ArrayCamposHora[i]).value);
		if((!validaHora(document.getElementById(ArrayCamposHora[i]).value)) && (document.getElementById(ArrayCamposHora[i]).value != ''))
			dadosInvalidosTemp = dadosInvalidosTemp.concat(ArrayCamposHora[i+1]);				
	}		
	return dadosInvalidosTemp;
}

function ValidaCamposObrigatoriosGenerico(ArrayCamposObrigatorios){
	var dadosInvalidosTemp = new Array(0);
	for (var i = 0 ; i < ArrayCamposObrigatorios.length ; i = i + 2){
		if (document.getElementById(ArrayCamposObrigatorios[i]) == null)
			alert("Campo " + ArrayCamposObrigatorios[i] + " não encontrado");
		if (document.getElementById(ArrayCamposObrigatorios[i]).value == "")		
			dadosInvalidosTemp = dadosInvalidosTemp.concat(ArrayCamposObrigatorios[i+1]);
	}
	return dadosInvalidosTemp;
}		

function ValidaNumerosGenerico(ArrayCamposNumero){
	var dadosInvalidosTemp = new Array(0);
	for (var i = 0 ; i < ArrayCamposNumero.length ; i = i + 2){
		if (document.getElementById(ArrayCamposNumero[i]) == null)
			alert("Campo " + ArrayCamposNumero[i] + " não encontrado");
		if((!validaNumero(document.getElementById(ArrayCamposNumero[i]).value)) && (document.getElementById(ArrayCamposNumero[i]).value != ''))
			dadosInvalidosTemp = dadosInvalidosTemp.concat(ArrayCamposNumero[i+1]);	
	}
	return dadosInvalidosTemp;
}

function ValidaCodigosPostaisGenerico(ArrayCamposCodigoPostal){
	var dadosInvalidosTemp = new Array(0);
	for (var i = 0 ; i < ArrayCamposCodigoPostal.length ; i = i + 3){
		var cpBase = document.getElementById(ArrayCamposCodigoPostal[i]).value;
		var cpExtensao = document.getElementById(ArrayCamposCodigoPostal[i+1]).value;
		if((!validaNumero(cpBase) || !validaNumero(cpExtensao) || cpBase.length != 4 || cpExtensao.length != 3) &&
		   (cpBase != '' || cpExtensao != ''))
			dadosInvalidosTemp = dadosInvalidosTemp.concat(ArrayCamposCodigoPostal[i+2]);
		};
	return dadosInvalidosTemp;
}

function InicializaFrmPostInputsHidden(arrayInpupsHidden,frm)
{
	var inputHidden;
	
	for (var i = 0 ; i < arrayInpupsHidden.length ; i = i + 2)
	{	
		if(document.getElementById(arrayInpupsHidden[i]) == null)
		{
			inputHidden = CreateInput(arrayInpupsHidden[i], arrayInpupsHidden[i], 'Hidden', arrayInpupsHidden[i+1]);
			frm.appendChild(inputHidden);
		}
		else
			document.getElementById(arrayInpupsHidden[i]).value = arrayInpupsHidden[i+1];
	}
	return true;
}

//Funcao que informa o modulo de navegação que deve colocar a página actual da listagem a 1
function resetListagem()
{
	var frm = document.frmPostBack;
	var inputHidden;

	if(frm.fPrimeiraPaginaPost == null)
	{
		inputHidden = CreateInput('fPrimeiraPaginaPost', 'fPrimeiraPaginaPost', 'Hidden', '1');
		frmPostBack.appendChild(inputHidden);
	}
	else
		frm.fPrimeiraPaginaPost.value = '1';
}

// Esta funcao valida se e necessario informar a morada quando estamos a subscrever uma apolice.
function ValidaMoradaObrigatoria(codigoProduto)
{
	var	moradaObrigatoria = true;

	switch (codigoProduto)
	{
		case 'APIN1':
		case 'VIAGE':
		case 'RCFAM':
		case 'RCANI':
		case 'APGBM':
		case 'APGPC':
		case 'APGPO':
		case 'APGR1':
		case 'APGES':
		case 'APGOT':
		case 'APGBB':
		case 'APGAU':
		case 'PRVIA':
			moradaObrigatoria = false;
			break;
		default:
			break;
	}
	return moradaObrigatoria;
}

//Funcao que permite enviar o recibo a reclassificar
//a partir de uma página de consulta de recibo
function ReclassificarRecibo(numeroRecibo, sistemaOrigem)
{
	var xmlPost = '&lt;ListaRecibos&gt;';	
	
	xmlPost = xmlPost.concat('&lt;Recibo&gt;&lt;NumeroRecibo&gt;' + numeroRecibo + '&lt;/NumeroRecibo&gt;&lt;SistemaOrigem&gt;' + sistemaOrigem + '&lt;/SistemaOrigem&gt;&lt;/Recibo&gt;');
			
	xmlPost = xmlPost.concat('&lt;/ListaRecibos&gt;');

	var inputHidden = CreateInput('fListaRecibosReclassificarPost', 'fListaRecibosReclassificarPost', 'Hidden', xmlPost);

	document.frmPost.appendChild(inputHidden);
	document.frmPost.action = "/Site/Comum/PagamentosRecebimentos/Recibos/ReclassificarRecibos.aspx";
	document.frmPost.submit();				
}

//Função COMPUWARE (TEMPORÁRIO) - Diagnóstico de performance à aplicação LEVE
function SampleEvent(strFireEvent)	
{
	//alert(strFireEvent);
	try
		{
		   var CVEvent = new ActiveXObject('CVUserDefined.CVUserDefined');
		   CVEvent.FireEvent(strFireEvent);
	  } 
	catch(e) {}
}


function LockUISubmit() 
{
    if (document.getElementById('masterLoader')) 
    {
        document.getElementById('masterLoader').style.display = 'block';
        document.getElementById('masterLoader').innerHTML = '<table width="100%" height="100%"><tr><td align="center"><img src="/Site/Suporte/Imagens/ajax-loader.gif"></td></tr></table>';
    }
}
