var xmlHttp = false;

function callServer() {
      xmlHttp = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari, ...
         xmlHttp = new XMLHttpRequest();
         if (xmlHttp.overrideMimeType) {
            xmlHttp.overrideMimeType('text/html; charset=iso-8859-1');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!xmlHttp) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
}
/*
var xmlHttp1 = callServer();

if(xmlHttp1) {
	url = antiCacheRand(url)
    xmlHttp1.onreadystatechange = ajaxOnReady
    xmlHttp1.open("GET", url ,true);
    xmlHttp1.setRequestHeader("Cache-Control", "no-cache");
    xmlHttp1.setRequestHeader("Pragma", "no-cache");
    
	xmlHttp1.send(null)
    return true;
}else{
    return false;
}

function ajaxOnReady(){
	if (xmlHttp1.readyState==4){
    	if(xmlHttp1.status == 200){
        	var texto=xmlHttp1.responseText;
            if(texto.indexOf(" ")<0) texto=texto.replace(/\+/g," ");
            //texto=unescape(texto); //descomente esta linha se tiver usado o urlencode no php ou asp
            	printResult(texto);
        }else{
        	if(exibe_carregando) {
				printResult("Erro: . " + httpStatus(xmlHttp1.status));
			}
        }
        
		xmlHttp1 = null
    }
}
	
function callServer() {
	if(typeof(XMLHttpRequest)!='undefined') {
		return new XMLHttpRequest();
	}
    var axO=['Microsoft.XMLHTTP','Msxml2.XMLHTTP','Msxml2.XMLHTTP.6.0','Msxml2.XMLHTTP.4.0','Msxml2.XMLHTTP.3.0'];
    for(var i=0; i<axO.length; i++) { 
		try { 
			return new ActiveXObject(axO[i]);
		}catch(e){} }
    return null;
}

function httpStatus(stat) {
	switch(stat){
    	case 400: return "400: Solicitação incompreensível"; break;
        case 403: case 404: return "404: Não foi encontrada a URL solicitada"; break;
        case 405: return "405: O servidor não suporta o m&eacute;todo solicitado"; break;
        case 500: return "500: Erro desconhecido de natureza do servidor"; break;
        case 503: return "503: Capacidade m&aacute;xima do servidor alcançada"; break;
        default: return "Erro " + stat + ". Mais informaç&otilde;es em http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html"; break;
    }
}

function printResult(valor) { //coloca o valor na variavel/elemento de retorno
	if ((typeof(elemento_retorno)).toLowerCase()=="string") { //se for o nome da string
    	if(valor!="Falha no carregamento"){
        	eval(elemento_retorno + '= unescape("' + escape(valor) + '")')
        }
   	}else if(elemento_retorno.tagName.toLowerCase()=="input"){
            valor = escape(valor).replace(/\%0D\%0A/g,"")
            elemento_retorno.value = unescape(valor);
    }else if(elemento_retorno.tagName.toLowerCase()=="select"){        
            select_innerHTML(elemento_retorno,valor)
    }else if(elemento_retorno.tagName){
            elemento_retorno.innerHTML = valor;
            //alert(elemento_retorno.innerHTML)
    }    
}

function antiCacheRand(aurl){
	var dt = new Date();
    if(aurl.indexOf("?")>=0){ // já tem parametros
    	return aurl + "&" + encodeURI(Math.random() + "_" + dt.getTime());
    }else { return aurl + "?" + encodeURI(Math.random() + "_" + dt.getTime());}
}

function select_innerHTML(objeto, innerHTML) {
    objeto.innerHTML = ""
    var selTemp = document.createElement("micoxselect")
    var opt;
    selTemp.id="micoxselect1"
    document.body.appendChild(selTemp)
    selTemp = document.getElementById("micoxselect1")
    selTemp.style.display="none"
    if (innerHTML.toLowerCase().indexOf("<option")<0) { //se não é option eu converto
        innerHTML = "<option>" + innerHTML + "</option>"
    }
    innerHTML = innerHTML.replace(/<option/g,"<span").replace(/<\/option/g,"</span")
    selTemp.innerHTML = innerHTML
    for (var i=0;i<selTemp.childNodes.length;i++){
        if (selTemp.childNodes[i].tagName){
            opt = document.createElement("OPTION")
            for (var j=0;j<selTemp.childNodes[i].attributes.length;j++){
                opt.setAttributeNode(selTemp.childNodes[i].attributes[j].cloneNode(true))
            }
            opt.value = selTemp.childNodes[i].getAttribute("value")
            opt.text = selTemp.childNodes[i].innerHTML
            if (document.all){ //IEca
                objeto.add(opt)
            } else{
                objeto.appendChild(opt)
            }                    
        }    
    }
    document.body.removeChild(selTemp)
    selTemp = null
}

*/

function alterarVersoes(obj) {
//    document.getElementById('Submit_search').disabled = true;
//    document.getElementById('Submit_search').value = "A pesquisar...";

    //Build the URL to connect to
    var url = "/web2go_standpt/commons/ajax_files/runtime/functions.ajax.php?function=dropdownVersoes&id_modelo="
              + encodeURI( document.getElementById("id_modelo").value ) + "&id_versao="
			  + encodeURI( document.getElementById("id_versao").value );
	
    // Open a connection to the server
    callServer();
    xmlHttp.open("POST", url, true);

    // Setup a function for the server to run when it's done
    xmlHttp.onreadystatechange = listarVersoes;

    // Send the request
    xmlHttp.send(null);

//    document.getElementById('Submit_search').value = "Pesquisar";
//    document.getElementById('Submit_search').disabled = false;
}

function listarVersoes() {
    if (xmlHttp.readyState == 4) {
       if (xmlHttp.status == 200) {

          result = xmlHttp.responseText;
		  document.getElementById('versoes').innerHTML = decodeURI( result );

       } else {
          alert('There was a problem with the request.');
       }
    }
}

function alterarConcelhos(obj) {
//    document.getElementById('Submit_search').disabled = true;
//    document.getElementById('Submit_search').value = "A pesquisar...";

    //Build the URL to connect to
    var url = "/web2go_standpt/commons/ajax_files/runtime/functions.ajax.php?function=dropdownConcelhos&cod_distrito="
              + encodeURI( document.getElementById("cod_distrito").value ) + "&cod_concelho="
			  + encodeURI( document.getElementById("cod_concelho").value );
	
    // Open a connection to the server
    callServer();
    xmlHttp.open("POST", url, true);

    // Setup a function for the server to run when it's done
    xmlHttp.onreadystatechange = listarConcelhos;

    // Send the request
    xmlHttp.send(null);

//    document.getElementById('Submit_search').value = "Pesquisar";
//    document.getElementById('Submit_search').disabled = false;
}

function listarConcelhos() {
    if (xmlHttp.readyState == 4) {
       if (xmlHttp.status == 200) {

          result = xmlHttp.responseText;
		  document.getElementById('concelhos').innerHTML = decodeURI( result );

       } else {
          alert('There was a problem with the request.');
       }
    }
}


function alterarModelos(obj) {
//    document.getElementById('Submit_search').disabled = true;
//    document.getElementById('Submit_search').value = "A pesquisar...";

    //Build the URL to connect to
    var url = "/web2go_standpt/commons/ajax_files/runtime/functions.ajax.php?function=dropdownModelos&id_marca="
              + encodeURI( document.getElementById("id_marca").value ) + "&id_modelo="
			  + encodeURI( document.getElementById("id_modelo").value );
	
    // Open a connection to the server
    callServer();
    xmlHttp.open("POST", url, true);

    // Setup a function for the server to run when it's done
    xmlHttp.onreadystatechange = listarModelos;

    // Send the request
    xmlHttp.send(null);

//    document.getElementById('Submit_search').value = "Pesquisar";
//    document.getElementById('Submit_search').disabled = false;
}


function listarModelos() {
    if (xmlHttp.readyState == 4) {
       if (xmlHttp.status == 200) {

          result = xmlHttp.responseText;
		  document.getElementById('modelos').innerHTML = decodeURI( result );

       } else {
          alert('There was a problem with the request.');
       }
    }
}


function Modelos(obj) {
//    document.getElementById('Submit_search').disabled = true;
//    document.getElementById('Submit_search').value = "A pesquisar...";

    //Build the URL to connect to
    var url = "/web2go_standpt/commons/ajax_files/runtime/functions.ajax.php?function=Modelos&id_marca="
              + encodeURI( document.getElementById("id_marca").value ) + "&id_modelo="
			  + encodeURI( document.getElementById("id_modelo").value );
	
    // Open a connection to the server
    callServer();
    xmlHttp.open("POST", url, true);

    // Setup a function for the server to run when it's done
    xmlHttp.onreadystatechange = MostrarModelos;

    // Send the request
    xmlHttp.send(null);

//    document.getElementById('Submit_search').value = "Pesquisar";
//    document.getElementById('Submit_search').disabled = false;
}


function MostrarModelos() {
    if (xmlHttp.readyState == 4) {
       if (xmlHttp.status == 200) {

          result = xmlHttp.responseText;
		  document.getElementById('modelos').innerHTML = decodeURI( result );

       } else {
          alert('There was a problem with the request.');
       }
    }
}

function alterarTipologia(obj) {
//    document.getElementById('Submit_search').disabled = true;
//    document.getElementById('Submit_search').value = "A pesquisar...";

    //Build the URL to connect to
    var url = "/web2go_standpt/commons/ajax_files/runtime/functions.ajax.php?function=dropdownTipologia&id_natureza="
              + encodeURI( document.getElementById("id_natureza").value ) + "&id_tipologia="
			  + encodeURI( document.getElementById("id_tipologia").value );

	// Open a connection to the server
    callServer();
    xmlHttp.open("POST", url, true);

    // Setup a function for the server to run when it's done
    xmlHttp.onreadystatechange = listarTipologia;

    // Send the request
    xmlHttp.send(null);
	setTimeout("callServer()",5000);
//    document.getElementById('Submit_search').value = "Pesquisar";
//    document.getElementById('Submit_search').disabled = false;
}

function listarTipologia() {
    if (xmlHttp.readyState == 4) {
       if (xmlHttp.status == 200) {

          result = xmlHttp.responseText;
		  document.getElementById('tipologia').innerHTML = decodeURI( result );

       } else {
          alert('There was a problem with the request.');
       }
    }
}

function countSearch() {
    //Build the URL to connect to if span exists
	if (document.getElementById("searchTotal") !== null) {
    	var url = "/web2go_standpt/commons/ajax_files/runtime/functions.ajax.php?function=countSearchProperties&id_natureza="
     	          + encodeURI( document.getElementById("id_natureza").value ) + "&id_tipologia="
				  + encodeURI( document.getElementById("id_tipologia").value ) + "&id_negocio="
				  + encodeURI( document.getElementById("tipo_negocio").value ) + "&cod_distrito=" 
				  + encodeURI( document.getElementById("cod_distrito").value ) + "&cod_concelho="
				  + encodeURI( document.getElementById("cod_concelho").value );
//		alert(url);
		while (!(xmlHttp.readyState == 0)) {
			// Open a connection to the server
			document.getElementById('searchTotal').innerHTML = "***";
    		//alert('Actualizando pesquisa...');
			callServer();
	    	xmlHttp.open("POST", url, true);

    		// Setup a function for the server to run when it's done
   			xmlHttp.onreadystatechange = listTotalProperties;

    		// Send the request
    		xmlHttp.send(null);
			setTimeout("callServer()",1000);
			if (xmlHttp.readyState == 1) break;
		}
	}
}

function listTotalProperties() {
    if (xmlHttp.readyState == 4) {
       if (xmlHttp.status == 200) {

          result = xmlHttp.responseText;
		  document.getElementById('searchTotal').innerHTML = decodeURI( result );

       } else {
          alert('There was a problem with the request.');
       }
    }
}

/* Confirm Step */
function confirmStep() {
   option = confirm('Confirmar operação?');
   if (option) {
   	return true;
   }else return false;
}

/* Block Button on Form select */
function blockButton(button) {
    document.getElementById(button).disabled = true;

    return false;
}

/* Enable textfield when checkbox checked */
function onCheckboxSelect(textfield, checkbox) {
        document.getElementById(textfield).disabled = (document.getElementById(checkbox).checked == false);
		if (document.getElementById(textfield).value == "")	{
			document.getElementById(textfield).value = 1;
			document.getElementById(textfield).focus();
		}
}
/* Enable textfield with for */
function onCheckboxSelect_for(textfield, checkbox) {
        document.getElementById(textfield).disabled = (document.getElementById(checkbox).checked == false);
		if (document.getElementById(textfield).value == "") document.getElementById(textfield).focus();
}

/*
the third argument to changeKey should be a function function exampleKeyChecker (keyCode, key)
which returns an object { cancelKey: boolean, replaceKey: boolean, newKeyCode: number, newKey:string }
Not all properties need to be present, if cancelKey is set to true the other properties are not needed.
If replaceKey is set to true then at least newKeyCode needs to be set.
the fourth argument is an object used to allow others Keys like (backspace)
all properties need to be present...
{ backaspaceKey: boolean }
*/
function CheckKey (textControl, evt, keyChecker,opts) {
	var keyCode = evt.keyCode ? evt.keyCode : evt.charCode ? evt.charCode : evt.which ? evt.which : void 0;
	var key;
	if (keyCode) 
		key = String.fromCharCode(keyCode);
	var keyCheck = keyChecker(keyCode, key);
	if(!SpecialOptsKeys(keyCode,opts))
	{
		if (keyCode && window.event && !window.opera) {
			if (keyCheck.cancelKey)
				return false;
			else if (keyCheck.replaceKey) {
				window.event.keyCode = keyCheck.newKeyCode;
				if (window.event.preventDefault)
					window.event.preventDefault();
				return true;
			}
			else
				return true;
		}
		else if (typeof textControl.setSelectionRange != 'undefined') {
			if (keyCheck.cancelKey) {
				if (evt.preventDefault)
					evt.preventDefault();
				return false;
			}
			else if (keyCheck.replaceKey) {
				// cancel the key event and insert the newKey for the current selection
				if (evt.preventDefault)
					evt.preventDefault();
				var oldSelectionStart = textControl.selectionStart;
				var oldSelectionEnd = textControl.selectionEnd;
				var selectedText = textControl.value.substring(oldSelectionStart,oldSelectionEnd);
				var newText = typeof keyCheck.newKey != 'undefined' ? keyCheck.newKey : String.fromCharCode(keyCheck.newKeyCode);
				textControl.value = textControl.value.substring(0, oldSelectionStart) + newText + textControl.value.substring(oldSelectionEnd);textControl.setSelectionRange(oldSelectionStart + newText.length,oldSelectionStart + newText.length);
				return false;
			}
			else {
			return true;
			} 
		}
		else if (keyCheck.cancelKey) {
			if (evt.preventDefault) {
				evt.preventDefault();
			}
			return false;
		}
		else {
		return true;
		}
	}else
		return true;
}
// options	{ backaspaceKey: boolean}
function SpecialOptsKeys(keyCode,opts){
	var result = false;
	if(opts.backaspaceKey)
		if(keyCode == 8)
			result = true;
	if(opts.ponto)
		if(keyCode == 46)
			return true;
	if(opts.negativo)
		if(keyCode==45)
			return true;
	return result;
}

// apenas permite a introdução de digitos returnamdo "true" quando a key de entrada não o for...
function Cancel_No_Digits (keyCode, key) {
  return { cancelKey: !isDigit(keyCode, key) };
}

// apenas permite a introdução de digitos e "/" returnamdo "true" quando a key de entrada não o for...
var DTSplit_Code = 47; //    "/"
function Cancel_No_Date (keyCode, key) {
  return { cancelKey: isDigit(keyCode, key) ? false : keyCode == DTSplit_Code ? false : true };
}

function isDigit (keyCode, key) {
  return "0123456789".indexOf(key) != -1;
}

/**
*	Como invocar:
* <input onkeypress='return CheckKey(this, event, Cancel_No_Digits,{ backaspaceKey: true,ponto:true/false});'>
*/

function showHideSpan(elementId) {
		 if (document.getElementById(elementId).style.visibility == "hidden") {
			 document.getElementById(elementId).style.visibility = "visible";
	         document.getElementById(elementId).style.display = "block";
			 document.getElementById('infoToogle_image').src = "/web2go_standpt/commons/images/infoToogle_hide.gif";
		 }else {
			 document.getElementById(elementId).style.visibility = "hidden";
	         document.getElementById(elementId).style.display = "none";
			 document.getElementById('infoToogle_image').src = "/web2go_standpt/commons/images/infoToogle_show.gif";
		}
}

function loadImage(element, url) {
	document.getElementById(element).src = url; return false;
}