﻿/*
  Método que valida a introdução de valores numéricos.
*/
function numeric_Validate(e, obj)
{
  var evt = e ? e : window.event;
  var keycode;
  if(document.all)
    keycode = evt.keyCode;
  else
    keycode = evt.which;
  if(keycode>=48 && keycode<=57 || (keycode==0 || keycode==8))
    return true;
  else
	e.preventDefault ? e.preventDefault() : e.returnValue = false;
}

/*
  Método que formata o valor a apresentar num campo numérico.
*/
function numeric_Format(value)
{       
  var comma = '.';
  var dec = '.';
  var postDecimal = '';
  var decPlaces = 3;
  
  try 
  {
	// Obtém o valor numérico introduzido
	value = value.replace(/\./g, "")
	// Verifica se não foi introduzido num número
    if (value.length < 1)
    {
       return "";
    }
	// Verifica se foi introduzido o valor "0"
	if (parseInt(value) == 0)
    {
       return "";
    }
	// Retorna o valor introduzido caso, não ultrapasse o número de caracteres das casas decimais
    if (value.length <= decPlaces)
    {
      return value;
    }

    if (value.length > decPlaces)
    {
      postDecimal = dec + value.substring(value.length - decPlaces, value.length);
      value = value.substring(0, value.length - decPlaces);
    }
    var regex = new RegExp('(-?[0-9]+)([0-9]{3})');
    while(regex.test(value))
    {
      value = value.replace(regex, '$1' + comma + '$2');
    }
  }
  catch (exception) {}
  return value + postDecimal;
}

/*
  Método que configura a seleccção da localização (Mapa, Distrito, Concelho e Freguesia).
*/
function pesqAvancada_ddlPais_SelectedIndexChanged() {	
  // Obtém o clientID do controlo
  var _client = document.getElementById("_control").value;
  var _pais = document.getElementById(_client+"ddlPais").value;

  // Configura o acesso aos objectos "Distrito" e "Concelho"
  var _distrito = document.getElementById(_client+"lstDistrito");
  
  if(_pais == "1") {
    bind(document.getElementById(_client+"ddlPais"),false,3);
  } else {
    clear_dropdown("lstDistrito");
	clear_dropdown("lstConcelho");
    clear_dropdown("lstFreguesia");
  }
}
function clear_dropdown(ddl) {
  // Obtém o clientID do controlo
  var _client = document.getElementById("_control").value;	
  var _obj = document.getElementById(_client+ddl);
  _obj.options.length = 0;
}

/*
  Método que apresenta a lista de características em função do tipo de imóvel seleccionado.
*/
function ddlTipo_SelectedIndexChanged(dropdown) {
  var _max = 2;
  var _uc = document.getElementById("_control").value;
  var _update = true;
  var _grupo;
	
  // Esconde todas as características  
  for(_row=1; _row<=_max; _row++) {
	document.getElementById(_uc+"divGrupo"+_row).style.visibility = "hidden";
	document.getElementById(_uc+"divGrupo"+_row).style.display = "none";
  }
  
  switch(dropdown.value) {
    case "224":
	case "":
	  _update = false;
	  break;
	case "225":
	  _grupo = "divGrupo2";
	  chkGrupo_Clear(2);
	  break;
	default:
	  _grupo = "divGrupo1";
	  chkGrupo_Clear(1);
  }
  // Apresenta o grupo de características pretendidas
  if(_update) {
	document.getElementById(_uc+_grupo).style.visibility = "visible";
	document.getElementById(_uc+_grupo).style.display = "block";  
  }
}
/*
  Método que limpa a seleccção das características de um grupo de imóveis.
*/
function chkGrupo_Clear(_grupo) {
  var _uc = document.getElementById("_control").value;
  var _elem = document.getElementById(_uc+"divGrupo"+_grupo).getElementsByTagName("*");
  var _chk;
  
  // Percorre todos os elementos do elemento Div
  for(_row=0; _row<_elem.length; _row++) {
	_chk = _elem[_row];
    if(_chk.type == "checkbox") {
	  _chk.checked = false;
	}
  }
}

/*
  Método que acrescenta um campo obrigatório à mensagem de validação do formulário.
*/
function pesqAvancada_cfgMessage(_dropdown, _label, _text, _return) {
  if(_dropdown.value.length == 0) {
    _label.style.color = "#DC423B";
    if(_return) return String.fromCharCode(187)+" "+_text+"\n";
  } else {
    _label.style.color = "#777777";
  }
}

/*
  Método que valida um intervalo de preços (DropDownList).
*/
function pesqAvancada_ddlValidate(_min, _max, _labelL, _labelR, _resource) {
  // Obtém o clientID do controlo
  var _client = document.getElementById("_control").value;
  _ddlMin = document.getElementById(_client+_min).selectedIndex;
  _ddlMax = document.getElementById(_client+_max).selectedIndex;
  
  if(_ddlMin != 0 && _ddlMax != 0) {
    if(_ddlMin > _ddlMax) {
	  document.getElementById(_client+_labelL).style.color = "#DC423B";
	  document.getElementById(_client+_labelR).style.color = "#DC423B";
	  return String.fromCharCode(187)+' '+_resource+'\n';
	}
  }
  document.getElementById(_client+_labelL).style.color = "#777777";
  document.getElementById(_client+_labelR).style.color = "#777777";
  return "";
}
/*
  Método que valida um intervalo de preços (TextBox).
*/
function pesqAvancada_txtValidate(_min, _max, _labelL, _labelR, _resource) {
  // Obtém o clientID do controlo
  var _client = document.getElementById("_control").value;
  _txtMin = document.getElementById(_client+_min).value;
  _txtMax = document.getElementById(_client+_max).value;
  
  if(_txtMin.length > 0 && _txtMax.length > 0) {
    if((_txtMin * 1) > (_txtMax * 1)) {
	  document.getElementById(_client+_labelL).style.color = "#DC423B";
	  document.getElementById(_client+_labelR).style.color = "#DC423B";
	  return String.fromCharCode(187)+' '+_resource+'\n';
	}
  }
  document.getElementById(_client+_labelL).style.color = "#777777";
  document.getElementById(_client+_labelR).style.color = "#777777";
  return "";
}


/*
  Método que obtém a endereço da página de resultado da pesquisa de imóveis.
*/
function getURL() {
  // Obtém o clientID do controlo
  var _client = document.getElementById("_control").value;
  // Cria o endereço da página do Resultado da Pesquisa
  var _url = "/Default.aspx?tabid=" + document.getElementById(_client+"__tabid").value;
  
  // Mediador
  _url += add_value(_client, "_idmed", "idMed", false);
  // Finalidade
  _url += add_value(_client, "ddlFinalidade", "tNeg", false);
  // Estado
  _url += add_value(_client, "ddlEstado", "iEst", false);
  // Tipo de Imóvel
  _url += add_value(_client, "ddlTipo", "gImo", false);
  // SubTipo de Imóvel
  _url += add_value(_client, "ddlSubTipo", "tImo", false);
  // País	  
  _url += add_value(_client, "ddlPais", "lPai", false);
  if(document.getElementById(_client+"ddlPais").value == 1) {
    // Distrito
    _url += addListBox_values(_client, "lstDistrito", "lDis", false);
    // Concelho
    _url += addListBox_values(_client, "lstConcelho", "lCon", false);
    // Freguesia
    _url += addListBox_values(_client, "lstFreguesia", "lFre", false);
  } 
  // Tipologia
  _url += add_value(_client, "ddlTipologiaMin", "tMin", false);
  _url += add_value(_client, "ddlTipologiaMax", "tMax", false);
  // Área
  _url += add_value(_client, "txtAreaMin", "aMin", true);
  _url += add_value(_client, "txtAreaMax", "aMax", true);
  // Preço
  _url += add_value(_client, "txtPrecoMin", "pMin", true);
  _url += add_value(_client, "txtPrecoMax", "pMax", true);
  // Características
  _url += add_Binary(_client, "cImo");
  // Fotos
  _url += add_flag(_client, "chkFotos", "bImg");
  // Fotos 360º
  _url += add_flag(_client, "chkFotos360", "bImg360");
  // Vídeos
  _url += add_flag(_client, "chkVideos", "bVideos");
  // Empreendimentos
  _url += add_flag(_client, "chkEmpreendimento", "bEmp");
  _url += "&language=" + document.getElementById(_client+"__idioma").value;

  return _url;
}



/*
  Método que adiciona um valor à QueryString.
*/
function add_value(_client, _name, _query, _replace) {
  var _value = document.getElementById(_client+_name).value;
  if(_value.length > 0) {
    return _replace ? "&" + _query + "=" + _value.replace(/\D/, "") : "&" + _query + "=" + _value;
  }
  return "";
}
/*
  Método que retorna as valores seleccionados de uma ListBox.
*/
function addListBox_values(_client, _name, _query) {
  var _lst = document.getElementById(_client+_name);
  var _value = "";
  for(_row=0; _row<_lst.options.length; _row++) {
    if(_lst.options[_row].selected) _value += _lst.options[_row].value + ","
  }
  if(_value.length > 0) {
	_value = _value.slice(0, -1)
    return "&" + _query + "=" + _value;
  }
  return "";
}
/*
  Metódo que permite adicionar uma característica CheckBox.
*/
function add_flag(_client, _name, _query) {
  if(document.getElementById(_client+_name).checked) {
    return "&" + _query + "=1";
  }
  return "";
}
/*
  Método que obtém o valor das características seleccionadas de um grupo de imóveis.
*/
function add_Binary(_client, _query) {
  var _grupo;
  var _chk, _chkid;
  var _value=0;
  
  switch(document.getElementById(_client+"ddlTipo").value) {
    case "224":
	case "":
	  _grupo = "";
	  break;
	case "225":
	  _grupo = "divGrupo2";
	  break;
	default:
	  _grupo = "divGrupo1";
  }

  if(_grupo.length > 0) {
    // Percorre todos os elementos do elemento Div
    var _elem = document.getElementById(_client+_grupo).getElementsByTagName("*");
    for(_row=0; _row<_elem.length; _row++) {
	  _chk = _elem[_row];
      if(_chk.type == "checkbox" && (_chk.checked)) {
	    _chkid = _chk.id;
  	    _value = _value + (_chkid.substring(_chkid.lastIndexOf("_") + 1) * 1);
	  }
    }
	if(_value > 0) return "&" + _query + "=" + _value;
  }
  
  return "";
}