var _objXML = [
  function () {return new XMLHttpRequest()},
  function () {return new ActiveXObject("Microsoft.XMLHTTP")},
  function () {return new ActiveXObject("Msxml3.XMLHTTP")},
  function () {return new ActiveXObject("Msxml2.XMLHTTP")}
];

// Propriedades do pedido GET
var _httpReq;
var _textField;
var _valueField;
var _method;
// Propriedades de objectos
var _htmlCol;
var _dropdown;
var _clientId;
var _ucClientId;
// Propriedades de controlo
var _initNames;
var _empty;
var _deep=0;

[].indexOf || (Array.prototype.indexOf = function(v) {
  for(var i = this.length; i-- && this[i] !== v;);
  return i;
});
  
function initArray(obj) {
  _htmlCol = new Array("Distrito","Concelho","Freguesia","Tipo","SubTipo");
  var _prefix;
  // Obtém o prefixo do objecto (DropDownList, Listbox)
  switch(obj.type) {
    case "select-one":
      _prefix = "ddl";
      break;
    case "select-multiple":
	  _prefix = "lst";
	  break;
  }
  
  var id = obj.id;
  _ucClientId = id.substring(0,id.lastIndexOf("_")+1); 
  
  // Actualiza o nome dos objectos
  for(var i=0; i<_htmlCol.length; i++) {
    _htmlCol[i] = _ucClientId + _prefix + _htmlCol[i];
  }
  _initNames = obj.type;
}

function initArrayPAvancada(obj) {
  _htmlCol = new Array("Pais","Distrito","Concelho","Freguesia","Tipo","SubTipo");
  var _prefix = "ddl";
  var id = obj.id;
  _ucClientId = id.substring(0,id.lastIndexOf("_")+1); 

  // Actualiza o nome dos objectos
  for(var i=0; i<_htmlCol.length; i++) {
	_htmlCol[i] = _ucClientId + _prefix + _htmlCol[i];
  }
  // Verifica se o filtro "Distrito" é do tipo 'DropDownList' ou 'ListBox'
  if(document.getElementById(_htmlCol[1]) == null) {
    for(var i=1; i<=3; i++) {
      _htmlCol[i] = _htmlCol[i].replace("_ddl", "_lst");
    }
  }
  
  _initNames = obj.type;
}

function initReq() {
  var objRequest = null;
  for(var i=0; i<_objXML.length; i++) {
    try {
	  objRequest = _objXML[i]();
	} catch(ex) {
	  continue;
	}
	break;
  }
  return objRequest;
}
  
function getValues(_select) {
  var _return = _select.value;
  // Verifica se o objecto é uma ListBox
  if(_select.type == "select-multiple") {
    _return = "";
    for(var i=0; i<_select.options.length; i++) {
	  if(_select.options[i].selected) {
	    _return += _select.options[i].value + ","
	  }
  	}
	_return = _return.slice(0, -1);
  }
  return _return;
}

function bind(obj, empty, deep) {
  this._clientId = obj.id;
  this._empty = empty;
  this._deep = deep;
  
  if(_initNames != obj.type) initArray(obj);
  
  var _param = new Array();
  // Obtém o valor da opção seleccionada
  var value = document.getElementById(_clientId).value;

  if(value.length == 0) {
	clear(true);
  } else {
    // Realiza o pedido HTTP
	_httpReq = initReq();
	switch(_clientId) {
	  case _htmlCol[0]:
		_method = "GetConcelhos";
		_textField = "Descricao"
		_valueField = "ID";
		_dropdown = document.getElementById(_htmlCol[1]);		
		// Define os parametros a enviar no pedido POST		  
		_param.push("d="+getValues(document.getElementById(_htmlCol[0])));
		_param.push("&cod="+document.getElementById("__codigo").value);
        _param.push("&chv="+document.getElementById("__chave").value);
		break;
		
	  case _htmlCol[1]:
		_method = "GetFreguesias";
		_textField = "Descricao"
		_valueField = "ID";
		_dropdown = document.getElementById(_htmlCol[2]);		
		// Define os parametros a enviar no pedido POST
		_param.push("c="+getValues(document.getElementById(_htmlCol[1])));
		_param.push("&cod="+document.getElementById("__codigo").value);
        _param.push("&chv="+document.getElementById("__chave").value);
		break;
	}
	
	var _proxyURL = "http://"+document.getElementById("__server").value+"/proxy.aspx?"+_param.join('');
	
	_httpReq.onreadystatechange = getHTTP;
	_httpReq.open("get", _proxyURL, true);
	_httpReq.setRequestHeader("User-Agent", "xmlHttpRequest");
	_httpReq.send(null);
  }
}

function bindPAvancada(obj, empty, deep) {
  this._clientId = obj.id;
  this._empty = empty;
  this._deep = deep;
  
  if(_initNames != obj.type) initArrayPAvancada(obj);
  
  var _param = new Array();
  // Obtém o valor da opção seleccionada
  var value = document.getElementById(_clientId).value;

  if(value.length == 0) {
	clear(true);
  } else {
    // Realiza o pedido HTTP
	_httpReq = initReq();

	switch(_clientId) {
	  case _htmlCol[0]:
		_textField = "Descricao"
		_valueField = "ID";
		_dropdown = document.getElementById(_htmlCol[1]);		
		// Define os parametros a enviar no pedido POST		  
		_param.push("p="+document.getElementById(_ucClientId+"ddlPais").value);
		_param.push("&cod="+document.getElementById("__codigo").value);
        _param.push("&chv="+document.getElementById("__chave").value);
		break;
		
	  case _htmlCol[1]:  
		_textField = "Descricao"
		_valueField = "ID";
		_dropdown = document.getElementById(_htmlCol[2]);		
		// Define os parametros a enviar no pedido POST		  
		_param.push("p="+document.getElementById(_ucClientId+"ddlPais").value);
		_param.push("&d="+getValues(document.getElementById(_htmlCol[1])));
		_param.push("&cod="+document.getElementById("__codigo").value);
        _param.push("&chv="+document.getElementById("__chave").value);
		break;
		
	  case _htmlCol[2]:
		_textField = "Descricao"
		_valueField = "ID";
		_dropdown = document.getElementById(_htmlCol[3]);		
		// Define os parametros a enviar no pedido POST
		_param.push("p="+document.getElementById(_ucClientId+"ddlPais").value);
		_param.push("&d="+getValues(document.getElementById(_htmlCol[1])));
		_param.push("&c="+getValues(document.getElementById(_htmlCol[2])));
		_param.push("&cod="+document.getElementById("__codigo").value);
        _param.push("&chv="+document.getElementById("__chave").value);
		break;
		
	  case _htmlCol[4]:
		_textField = "Descricao"
		_valueField = "Valor";
		_dropdown = document.getElementById(_htmlCol[5]);		
		// Define os parametros a enviar no pedido POST
		_param.push("gi="+getValues(document.getElementById(_htmlCol[4])));
		_param.push("&i="+document.getElementById(_ucClientId+"__idioma").value);
		_param.push("&cod="+document.getElementById("__codigo").value);
        _param.push("&chv="+document.getElementById("__chave").value);
		break;
	}
	// Define o tipo de consulta
	__condition = document.getElementById("__condition")
	if((__condition != null) && __condition.value == "all") _param.push("&type=1");
		
	
	var _proxyURL = ""; //"http://localhost:50268/DNN_Improxy_full/proxy.aspx?";
	
	if (_proxyURL == "")
	    _proxyURL = "http://"+document.getElementById("__server").value+"/proxy.aspx?";
    _proxyURL = _proxyURL + _param.join('');
       

	_httpReq.onreadystatechange = getHTTP;
	_httpReq.open("get", _proxyURL, true);
	_httpReq.setRequestHeader("User-Agent", "xmlHttpRequest");
	_httpReq.send(null);
  }
}
  
function clear(disabled) {
  var index = _htmlCol.indexOf(_clientId)+1;
  for(var i=index; i<index+_deep; i++) {
	var _obj = document.getElementById(_htmlCol[i]);
  	_obj.disabled = true;
    var _default = _obj.options[0];
	_obj.options.length = 0;
	if(_empty) {
 	  var _option = new Option(_default.text, "");
	  _obj.options[_obj.options.length] = _option;
	}
  }
  document.getElementById(_htmlCol[index]).disabled = disabled;
}
  
function getHTTP() {
  if(_httpReq.readyState == 4) {
	if(_httpReq.status == 200) {
	  var XMLDoc = _httpReq.responseXML;
	  // Reset dos objectos DropDownList
	  clear(false);  
	  
	  var _nodes = XMLDoc.getElementsByTagName("Table");	  
	  for(var i=0; i<_nodes.length; i++) {
		_nodeValue = _nodes[i].getElementsByTagName(_valueField).item(0)
		_nodeText = _nodes[i].getElementsByTagName(_textField).item(0)

		// Adiciona as opções ao objecto
		var _option = new Option(_nodeText.firstChild.data, _nodeValue.firstChild.data);
		_dropdown.options[_dropdown.options.length] = _option;
	  }
    }
  }
}
