function isEmptyString(strString)	{
	return Trim(strString) == "";
}

function IsDigit(strString)	{
	var strValidChars = "0123456789";
	var strChar;
	var blnResult = true;
	
	//test strString consists of valid characters listed above
	for (i = 0; i < strString.length && blnResult == true; i++)
	{
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1)
		{
			blnResult = false;
		}
	}
	return blnResult;
}

function IsNegativeDigit(strString)	{
	var strValidChars = "-0123456789";
	var strChar;
	var blnResult = true;
	
	//test strString consists of valid characters listed above
	for (i = 0; i < strString.length && blnResult == true; i++)
	{
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1)
		{
			blnResult = false;
		}
	}
	return blnResult;
}

function IsNumeric(strString){
	var strValidChars = "0123456789.";
	var strChar;
	var blnResult = true;
  
	for (i = 0; i < strString.length && blnResult == true; i++){
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1) {
			blnResult = false;
		}
	}
	return blnResult;
}

/*function virtualKeyPressed(field, event) {
	var intCharCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
		
	strInputBoxValue = field.value;

	if ((intCharCode < 48 || intCharCode > 57) && (intCharCode != 13)) {
	event.returnValue = false;
	}	
}*/

function virtualKeyPressed(field, event, extraCods) {
	//extraCods: lista de caracteres q são aceites
	var intCharCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	
	strCods = new String("48,49,50,51,52,53,54,55,56,57");
	
	if(extraCods != "" && extraCods != undefined){
		arrCods = extraCods.split(",");
		for(i=0; i!=arrCods.length; i++){
			strCods += "," + (arrCods[i].charCodeAt(0));
		}
	}
	
	if(strCods.indexOf(intCharCode) == -1){
		event.returnValue = false;
	}
}

function virtualKeyPressedMaxLength(field, event, lenght) {
	if(parseInt(field.value.length) >= parseInt(lenght)){
		event.returnValue = false;
	}
}

function IsData(ano, mes, dia, txt){
	if(ano.value.length != 0 || mes.value.length != 0 || dia.value.length != 0){
		if(ano.value.length < 4 || !(IsDigit(ano.value))) {
			alert("O ano de " + txt + " tem de ser preenchido com valores numéricos. \nPreencha, por favor a o ano de " + txt + " correctamente.");
			ano.focus();
			return false;
		}	

		var data_actual = new Date();
	    var ano_actual = 1900 + data_actual.getYear();

		if(ano.value < 1900 || ano.value > ano_actual){
			alert("Por favor, preencha o ano de " + txt + " correctamente.");
			ano.focus();
			return false;
		}

		if(mes.value == 0 || mes.value.length == 0 || !(IsDigit(mes.value))) {
			alert("O mes de " + txt + " tem de ser preenchido com valores numéricos. \nPreencha, por favor a o mes de " + txt + " correctamente.");
			mes.focus();
			return false;
		}
		
		if(mes.value > 12){
			alert("Por favor, preencha o mes de " + txt + " correctamente.");
			mes.focus();
			return false;
		}
		
		if(dia.value == 0 || dia.value.length == 0 || !(IsDigit(dia.value))) {
			alert("O dia de " + txt + " tem de ser preenchido com valores numéricos. \nPreencha, por favor a o dia de " + txt + " correctamente.");
			dia.focus();
			return false;
		}
		
		if(mes.value == "01" || mes.value == "1" || mes.value == "03" || mes.value == "3" || mes.value == "05" || mes.value == "5" || mes.value == "07" || mes.value == "7" || mes.value == "08" || mes.value == "8" || mes.value == "10" || mes.value == "12"){
			if(dia.value > 31){
				alert("Por favor, preencha o dia de " + txt + " correctamente.");
				dia.focus();
				return false;
			}
		} 
		
		if(mes.value == "02" || mes.value == "2" ){
			if(dia.value > 29){
				alert("Por favor, preencha o dia de " + txt + " correctamente.");
				dia.focus();
				return false;
			}	
		} 	

		if(mes.value == "04" || mes.value == "4" || mes.value == "06" || mes.value == "6" || mes.value == "09" || mes.value == "9" || mes.value == "11"){
			if(dia.value > 30){
				alert("Por favor, preencha o dia de " + txt + " correctamente.");
				dia.focus();
				return false;
			}
		} 
	}
	return true;
}

function IsEndereco(cod4, cod3, loc){

	//if((cod4.value.length != 0) && ((cod4.value.length < 4) || !(IsDigit(cod4.value)))) {
	if(cod4.value.length > 0){
		if(cod4.value.length < 4 || !(IsDigit(cod4.value))) {
			alert("O campo Código Postal deve ser preenchido com valores numéricos. \nPor favor, preencha o campo Código Postal correctamente (4 dígitos).");
			cod4.focus();
			return false;
		}
	}
 	
	//if(((cod3.value.length != 0) && (cod3.value.length < 3))  || !(IsDigit(cod3.value))) {
	if(cod3.value.length > 0){	
		if(cod3.value.length < 3 || !(IsDigit(cod3.value))) {
			alert("O campo Código Postal deve ser preenchido com valores numéricos. \nPor favor, preencha o campo Código Postal correctamente (3 dígitos).");
			cod3.focus();
			return false;
		}
	}
	if(cod4.value.length != 0 && loc.value.length == 0){
		alert("Por favor, preencha o campo Localidade.");
		loc.focus();
		return false;
	}
	
	if(cod4.value.length == 0 && loc.value.length != 0){
		alert("Por favor, preencha o campo Código Postal.");
		cod4.focus();
		return false;
	}
	
	if(cod4.value.length == 0 && cod3.value.length > 0){
		alert("Por favor, preencha o campo Código Postal.");
		cod4.focus();
		return false;
	}
	return true;
}

function IsPhoneNumber(strString){
	var strValidChars = "0123456789/ ";
	var strChar;
	var blnResult = true;
	
	//test strString consists of valid characters listed above
	for (i = 0; i < strString.length && blnResult == true; i++)
	{
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1)
		{
			blnResult = false;
		}
	}
	return blnResult;
}

function IsFoto(img, boolObrig){
	if(boolObrig){
		if(img.value.length == 0){
			alert("Escolha uma Fotografia");
			img.focus();
			return false;
		}
	}
	
	if(img.value.length > 0){
		if(invalidName(img.value)) {
			img.focus();
			return false;
		}
		
		if(invalidNameChar(img.value)) {
			img.focus();
			return false;
		}	
	
	/*	if(invalidExtension(img.value)){
			img.focus();
			return false;
		}*/
	}
	
	return true;
}

function invalidName(filePath){
	var last = filePath.lastIndexOf("/");
	if(last == -1) last = filePath.lastIndexOf("\\");
	var fileName = filePath.substr(last+1);
	last = fileName.lastIndexOf(" ");
	if(last != -1){
		alert("O nome do ficheiro não pode ter espaços!");
		return true;
	}
	return false;
}

function invalidNameChar(filePath){
	var last = filePath.lastIndexOf("/");
	var myArrayChar = new Array("á", "à", "ã", "â" ,"é", "ê", "í", "ú", "ç" , "(" , ")" , "+" , "ª" , "º" , "*" , "&" , "[" , "]");

	if(last == -1) last = filePath.lastIndexOf("\\");
	var fileName = filePath.substr(last+1);	
	var letra="";
	for (var i=0; i < myArrayChar.length; i++){
		letra = myArrayChar[i];
		last =  fileName.lastIndexOf(letra);
		if(last != -1)
			break;		
	}
	
	if(last != -1){
		alert("O nome do ficheiro não pode ter o caracter '"+letra+"' !\nAltere o nome da fotografia usando um editor gráfico!");
		return true;
	}
	return false;
}

function invalidExtension(filePath){
	var last = filePath.lastIndexOf(".");
	var fileExt = (filePath.substr(last+1)).toLowerCase();
	/*if((fileExt!="jpeg") && (fileExt!="jpg")){
		alert("Ficheiro de Imagem não Suportado!\nEscolha uma Fotografia com Extensão\njpeg ou jpg.");
		return true;
	}*/
	return false;
}

function isJPEG(filePath){
	var last = filePath.lastIndexOf(".");
	var fileExt = (filePath.substr(last+1)).toLowerCase();
	if((fileExt!="jpeg") && (fileExt!="jpg")){
		alert("Ficheiro de Imagem não Suportado!\nEscolha uma Fotografia com Extensão jpeg ou jpg.");
		return false;
	}
	return true;
}

function isGIF(filePath){
	var last = filePath.lastIndexOf(".");
	var fileExt = (filePath.substr(last+1)).toLowerCase();
	if(fileExt!="gif"){
		alert("Ficheiro de Imagem não Suportado!\nEscolha uma Fotografia com Extensão gif.");
		return false;
	}
	return true;
}

function validFileExtension(filePath, validExtensions){
	var last = filePath.lastIndexOf(".");
	var fileExt = (filePath.substr(last+1)).toLowerCase();
	if(validExtensions.indexOf(fileExt) == -1){
		alert("Ficheiro não Suportado!\nEscolha um ficheiro com Extensão " + validExtensions + ".");
		return false;
	}
	return true;
}

/*
==================================================================
LTrim(string) : Returns a copy of a string without leading spaces.
==================================================================
*/
function LTrim(str)
/*
   PURPOSE: Remove leading blanks from our string.
   IN: str - the string we want to LTrim
*/
{
   var whitespace = new String(" \t\n\r");

   var s = new String(str);

   if (whitespace.indexOf(s.charAt(0)) != -1) {
	  // We have a string with leading blank(s)...

	  var j=0, i = s.length;

	  // Iterate from the far left of string until we
	  // don't have any more whitespace...
	  while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
		 j++;

	  // Get the substring from the first non-whitespace
	  // character to the end of the string...
	  s = s.substring(j, i);
   }
   return s;
}

/*
==================================================================
RTrim(string) : Returns a copy of a string without trailing spaces.
==================================================================
*/
function RTrim(str)
/*
   PURPOSE: Remove trailing blanks from our string.
   IN: str - the string we want to RTrim

*/
{
   // We don't want to trip JUST spaces, but also tabs,
   // line feeds, etc.  Add anything else you want to
   // "trim" here in Whitespace
   var whitespace = new String(" \t\n\r");

   var s = new String(str);

   if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
	  // We have a string with trailing blank(s)...

	  var i = s.length - 1;       // Get length of string

	  // Iterate from the far right of string until we
	  // don't have any more whitespace...
	  while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
		 i--;


	  // Get the substring from the front of the string to
	  // where the last non-whitespace character is...
	  s = s.substring(0, i+1);
   }

   return s;
}

/*
=============================================================
Trim(string) : Returns a copy of a string without leading or trailing spaces
=============================================================
*/
function Trim(str)
/*
   PURPOSE: Remove trailing and leading blanks from our string.
   IN: str - the string we want to Trim

   RETVAL: A Trimmed string!
*/
{
   return RTrim(LTrim(str));
}

/*
=============================================================
GetSelectDistritos() : Popula o Select option dos Distritos
=============================================================
*/
function GetSelectDistritos(strFirstOptionText) {
	
		var head    = document.getElementsByTagName("head").item(0);
	//	var old     = document.getElementById("lastLoadedConcelhos");
	//	if(old)
	//		head.removeChild(old);

		script = document.createElement("script");
		script.src = "/js/portugal/distritos/distrito.js";
		script.type = "text/javascript";
		script.defer = true;
	//	script.id = "lastLoadedConcelhos";
		void(head.appendChild(script));		
	
}


/*
=============================================================
OnChangeDistrito() : Faz reset às caixas de Concelhos e Freguesias
=============================================================
*/
function OnChangeDistrito(strFirstOptionText) {
	try{
		populateSelect(document.getElementsByName("freguesia_id")[0], new Array(), new Array(), strFirstOptionText);
	}catch(e){}
	if(document.getElementById('distrito_id').options[document.getElementById('distrito_id').selectedIndex].value == 0) {
		populateSelect(document.getElementsByName("concelho_id")[0], new Array(), new Array(), strFirstOptionText);
	}
	else {
		var head    = document.getElementsByTagName("head").item(0);
		var old     = document.getElementById("lastLoadedConcelhos");
		if(old)
			head.removeChild(old);

		script = document.createElement("script");
		script.src = "/js/portugal/concelhos/" + document.getElementById('distrito_id').options[document.getElementById('distrito_id').selectedIndex].value+ ".js";
		script.type = "text/javascript";
		script.defer = true;
		script.id = "lastLoadedConcelhos";
		void(head.appendChild(script));
	}
}

/*
=============================================================
OnChangeDistritoLPi() : Faz reset à caixa de Zonas LPi
=============================================================
*/
function OnChangeDistritoLPi(strFirstOptionText) {
	if(document.getElementById('distrito_id').options[document.getElementById('distrito_id').selectedIndex].value == 0) {
		populateSelect(document.getElementsByName("zona_lpi_id")[0], new Array(), new Array(), strFirstOptionText);
	}
	else {
		populateSelect(document.getElementsByName("zona_lpi_id")[0], new Array(), new Array(), "...Todas");
		
		var head    = document.getElementsByTagName("head").item(0);
		var old     = document.getElementById("lastLoadedZonas");

		if(old)
			head.removeChild(old);
		
		script = document.createElement("script");
		script.src = "/js/zonasLpi/" + document.getElementById('distrito_id').options[document.getElementById('distrito_id').selectedIndex].value+ ".js";
		script.type = "text/javascript";
		script.defer = true;
		script.id = "lastLoadedZonas";
		void(head.appendChild(script));
	}
}

function OnChangeDistritoLPi(strFirstOptionText, distrito_id) {
	if(distrito_id == 0) {
		populateSelect(document.getElementsByName("zona_lpi_id")[0], new Array(), new Array(), strFirstOptionText);
	}
	else {
		populateSelect(document.getElementsByName("zona_lpi_id")[0], new Array(), new Array(), "...Todas");
		
		var head    = document.getElementsByTagName("head").item(0);
		var old     = document.getElementById("lastLoadedZonas");

		if(old)
			head.removeChild(old);
		
		script = document.createElement("script");
		script.src = "/js/zonasLpi/" + distrito_id+ ".js";
		script.type = "text/javascript";
		script.defer = true;
		script.id = "lastLoadedZonas";
		void(head.appendChild(script));
	}
}

/*
=============================================================
OnChangeConcelho() : Faz reset à caixa de Freguesias
=============================================================
*/
function OnChangeConcelho(strFirstOptionText) {
	if(document.getElementById('concelho_id').options[document.getElementById('concelho_id').selectedIndex].value == 0) {
		populateSelect(document.getElementsByName("freguesia_id")[0], new Array(), new Array(), strFirstOptionText);
	}
	else {
		var head    = document.getElementsByTagName("head").item(0);
		var old     = document.getElementById("lastLoadedFreguesias");
		if(old)
			head.removeChild(old);

		script = document.createElement("script");
		script.src = "/js/portugal/freguesias/" + document.getElementById('concelho_id').options[document.getElementById('concelho_id').selectedIndex].value + ".js";
		script.type = "text/javascript";
		script.defer = true;
		script.id = "lastLoadedFreguesias";
		void(head.appendChild(script));
	}
}

/*
=============================================================
OnChangeConcelho() : Faz reset à caixa de Tipologias
=============================================================
*/
andarTxt = new Array("T0","T1","T2","T3","T4","T5","T6","T7+");
andarVal = new Array("1","2","3","4","5","6","7","8");
moradiaTxt = new Array("T0","T1","T2","T3","T4","T5","T6","T7+");
moradiaVal = new Array("9","10","11","12","13","14","15","16");
escritorioTxt = new Array("Independente","Centro Empresarial");
escritorioVal = new Array("17","18");
garagemTxt = new Array("Box","Lugar");
garagemVal = new Array("19","20");
armazemTxt = new Array("Independente","Centro Industrial");
armazemVal = new Array("21","22");
lojaTxt = new Array("Independente","Centro Comercial");
lojaVal = new Array("23","24");

//Terreno Industrial passa para fracções ***************************
//terrenoTxt = new Array("Industrial","Agrícola","Rústico","Urbano");
//terrenoVal = new Array("25","26","27","28");
terrenoTxt = new Array("Agrícola","Rústico","Urbano");
terrenoVal = new Array("26","27","28");

quintaTxt = new Array("Monte","Quinta");
quintaVal = new Array("29","30");
predioTxt = new Array("Habitação","Misto");
predioVal = new Array("33","35");

function OnChangeTipoid(strFirstOptionText) {
	valor = parseInt(document.getElementById('tipoId').value);
	document.getElementById('tipologiaId').disabled = false;
	switch (valor){
		case 0:
			populateSelect(document.getElementsByName("tipologiaId")[0], new Array(), new Array(), strFirstOptionText);
			break;
		case 1:     //Andar
			populateSelect(document.getElementsByName("tipologiaId")[0], andarVal, andarTxt, strFirstOptionText);
			break;
		case 2:     //Moradia
			populateSelect(document.getElementsByName("tipologiaId")[0], moradiaVal, moradiaTxt, strFirstOptionText);
			break;
		case 3:     //Escritorio
			populateSelect(document.getElementsByName("tipologiaId")[0], escritorioVal, escritorioTxt, strFirstOptionText);
			break;
		case 4:     //Garagem
			populateSelect(document.getElementsByName("tipologiaId")[0], garagemVal, garagemTxt, strFirstOptionText);
			break;
		case 5:     //Armazem
			populateSelect(document.getElementsByName("tipologiaId")[0], armazemVal, armazemTxt, strFirstOptionText);
			break;
		case 6:     //Loja
			populateSelect(document.getElementsByName("tipologiaId")[0], lojaVal, lojaTxt, strFirstOptionText);
			break;
		case 7:     //Terreno
			populateSelect(document.getElementsByName("tipologiaId")[0], terrenoVal, terrenoTxt, strFirstOptionText);
			break;
		case 8:     //Quinta
			populateSelect(document.getElementsByName("tipologiaId")[0], quintaVal, quintaTxt, strFirstOptionText);
			break;
		case 10:     //Predio
			populateSelect(document.getElementsByName("tipologiaId")[0], predioVal, predioTxt, strFirstOptionText);
			break;
		case 9:     //Outros
		default:
			//populateSelect(document.getElementsByName("tipologiaId")[0], new Array(), new Array(), strFirstOptionText);
			document.getElementById('tipologiaId').disabled = true;
			break;
	}
}

function onChangeFotoName(){
	alert("\tNão pode alterar o nome da fotografia neste local.\nPode apenas selecionar outra fotografias clicando no botão \"Browse\" ou \"Seleccionar\"");
	event.returnValue = false;
}

function onChangeFileName(){
	alert("\tNão pode alterar o nome do ficheiro neste local.\nPode apenas selecionar outro ficheiro clicando no botão \"Browse\" ou \"Seleccionar\"");
	event.returnValue = false;
}

function roundNumber(num, numDecimal){
	strNum = new String(num);
	
	if(strNum.lastIndexOf(".") > -1){
		valInt = strNum.substring(0 , strNum.lastIndexOf("."));
		valDec = strNum.substring(strNum.lastIndexOf(".") + 1, strNum.lastIndexOf(".") + numDecimal + 1);
		valLastDec = strNum.charAt(strNum.lastIndexOf(".") + numDecimal + 1);
		
		if(valLastDec >= 5){
			valDec = parseInt(valDec) + 1;
		}
		valTot = valInt + "." + valDec;
	}else{
		valTot = strNum;
	}
	
	return valTot;
}

function replaceChars(entry) {
	out = "“"; // replace this
	out1 = "”"; // replace this
	add = "'"; // with this
	temp = "" + entry; // temporary holder

	while (temp.indexOf(out)>-1) {
		pos= temp.indexOf(out);
		pos1= temp.indexOf(out1);
		temp = "" + (temp.substring(0, pos) + add + temp.substring((pos + out.length), temp.length));
		if(pos1 > -1)
			temp = "" + (temp.substring(0, pos1) + add + temp.substring((pos1 + out.length), temp.length));
	}
	
	return temp;
}

function round(number,X) {
// rounds number to X decimal places, defaults to 2
    X = (!X ? 2 : X);
    return Math.round(number*Math.pow(10,X))/Math.pow(10,X);
}


