/*** Inicia Ajax ******************************************/
function runAjax() {
	// verifica se é IE
	if (window.ActiveXObject) {
		//estancia o objeto Active X
		var ajax = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		//outros navegadores estancia o XMLHttpRequest
		var ajax = new XMLHttpRequest();
	}
	return ajax;
}

/*** Select Cidades ***************************************/

function selectCidades(){
	var id_estados = document.getElementById('id_estados').value;
	
	if (id_estados == 0){
		document.getElementById('showCidades').innerHTML = "";
		alert("Por favor selecione um Estado!");		
	} else {
		ajax = runAjax();
		ajax.onreadystatechange = showCidades;
		ajax.open("GET","cidades.php?id_estados=" + id_estados);
		ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		ajax.send(null);
	}
}

function showCidades() {
	if (ajax.readyState == 4){
		if (ajax.status == 200) {
			if (ajax.responseText != 0){
				document.getElementById('showCidades').innerHTML = ajax.responseText;		
			} else {
				alert("Nenhuma cidade publicada no momento.");
				document.getElementById('showCidades').innerHTML = "";		
			}
			
		} else {
			alert("Houve um problema ao carregar o texto:\n " + ajax.statusText);
		}
	}
}

function validCidades() {
	var id_estados = document.getElementById('id_estados').value;
	var bairro = document.getElementById('bairro').value;
	var msg = "";
	
	if (id_estados == 0){
		msg += "Selecione um estado!";
	}
	if (bairro == ""){
		msg += "O campo bairro é obrigatório!";
	}
	if (msg != ""){
		alert(msg);
		return false;
	} else {
		return true;
	}
}

/*** Select Cidades Adm ************************************/

function selectCidadesAdm(){
	var id_estados = document.getElementById('id_estados').value;
	
	if (id_estados == 0){
		document.getElementById('showCidades').innerHTML = "";
		alert("Por favor selecione um Estado!");		
	} else {
		ajax = runAjax();
		ajax.onreadystatechange = showCidadesAdm;
		ajax.open("GET","cidades.php?id_estados=" + id_estados);
		ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		ajax.send(null);
	}
}

function showCidadesAdm() {
	if (ajax.readyState == 4){
		if (ajax.status == 200) {
			if (ajax.responseText != 0){
				document.getElementById('showCidades').innerHTML = ajax.responseText;		
			} else {
				alert("Nenhuma cidade publicada no momento.");
				document.getElementById('showCidades').innerHTML = "";		
				document.getElementById('showBairros').innerHTML = "";		
			}
			
		} else {
			alert("Houve um problema ao carregar o texto:\n " + ajax.statusText);
		}
	}
}

/*** Cadastramento de cidades ******************************/
var nameCities = "";
var idEstados = "0";

function exeAddCidades(){
	ajax = runAjax();
	ajax.open("GET", "add_cidades.php?cidade=" + nameCities + "&id_estados=" + idEstados);
	ajax.send(null);	
	alert("Cidade cadastrada com sucesso!");	
	selectCidades();
}
function validCities(city){		
	ajax = runAjax();
	ajax.onreadystatechange = checkCities;
	ajax.open("GET", "check_cidades.php?cidade=" + city + "&id_estados="+ idEstados);
	ajax.send(null);
}

function checkCities(){
	if (ajax.readyState == 4){     		
		if (ajax.status == 200){
			if(ajax.responseText != 0){	
				alert("Já existe uma cidade cadastrada com esse nome!");		
				addCities(nameCities);				
			} else {
				exeAddCidades();
			}			
        } else {
            alert("Houve um problema:\n" + ajax.statusText);
		}
    }	 	
}

function addCities(city){
	idEstados = document.getElementById('id_estados').value;
	
	if (idEstados == 0){
		alert("Selecione um estado!");
	} else {
		var nameOf = prompt("Digite o nome da cidade", city);
		if(nameOf == ""){
			alert("Preenchimento obrigatório!");
			addCities(nameOf);
		} else if(nameOf != null) {
			nameCities = nameOf;
			validCities(nameCities);
		}
	}
}

/*** Select Bairros ****************************************/

function selectBairros(){
	var id_cidades = document.getElementById('id_cidades').value;
	
	if (id_cidades == 0){
		document.getElementById('showBairros').innerHTML = "";
		alert("Por favor selecione uma cidade!");		
	} else {
		ajax = runAjax();
		ajax.onreadystatechange = showBairros;
		ajax.open("GET","bairros.php?id_cidades=" + id_cidades);
		ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		ajax.send(null);
	}
}

function showBairros() {
	if (ajax.readyState == 4){
		if (ajax.status == 200) {
			if (ajax.responseText != 0){
				document.getElementById('showBairros').innerHTML = ajax.responseText;		
			} else {
				alert("Nenhum bairro publicado no momento.");
				document.getElementById('showBairros').innerHTML = "";		
			}
			
		} else {
			alert("Houve um problema ao carregar o texto:\n " + ajax.statusText);
		}
	}
}

/*** Cadastramento de bairros ******************************/
var nameBairro = "";
var idCidades = "0";

function exeAddBairro(){
	ajax = runAjax();
	ajax.open("GET", "add_bairros.php?bairro=" + nameBairro + "&id_cidades=" + idCidades);
	ajax.send(null);	
	alert("Bairro cadastrado com sucesso!");	
	selectBairros();
}
function validBairro(bairro){		
	ajax = runAjax();
	ajax.onreadystatechange = checkBairro;
	ajax.open("GET", "check_bairros.php?bairro=" + bairro + "&id_cidades="+ idCidades);
	ajax.send(null);
}

function checkBairro(){
	if (ajax.readyState == 4){     		
		if (ajax.status == 200){
			if(ajax.responseText != 0){	
				alert("Já existe um bairro cadastrado com esse nome!");		
				addBairro(nameBairro);				
			} else {
				exeAddBairro();
			}			
        } else {
            alert("Houve um problema:\n" + ajax.statusText);
		}
    }	 	
}

function addBairro(bairro){
	idCidades = document.getElementById('id_cidades').value;
	
	if (idCidades == 0){
		alert("Selecione uma cidade!");
	} else {
		var nameOf = prompt("Digite o nome do bairro", bairro);
		if(nameOf == ""){
			alert("Preenchimento obrigatório!");
			addBairro(nameOf);
		} else if(nameOf != null) {
			nameBairro = nameOf;
			validBairro(nameBairro);
		}
	}
}

/*** Validacao imovel **************************************/
function validImovel() {
	var id_estados = document.getElementById('id_estados').value;
	var codigo = document.getElementById('codigo').value;
	var tit = document.getElementById('tit').value;
	var endereco = document.getElementById('endereco').value;
	var msg = "";
	
	if (id_estados == 0){
		msg += "Selecione um estado!";
	} else {
		var id_cidades = document.getElementById('id_cidades').value;
		if (id_cidades == 0){
			msg += "Selecione uma cidade!";
		} 
	}
	if (codigo == ""){
		msg += "O campo Código é obrigatório!";
	} else {
		if (codigo.length > 255){
			msg += "O campo Código aceita somente 255 caracteres!";
		}
	}
	if (tit == ""){
		msg += "O campo Título é obrigatório!";
	} else {
		if (tit.length > 255){
			msg += "O campo Título aceita somente 255 caracteres!";
		}
	}
	if (endereco == ""){
		msg += "O campo Endereço é obrigatório!";
	} else {
		if (endereco.length > 255){
			msg += "O campo Endereço aceita somente 255 caracteres!";
		}
	}
	if (msg != ""){
		alert(msg);
		return false;
	} else {
		return true;
	}
}

/*** Exibe imagem ******************************************/
function showImg(folder,img, zoomIn, title) {
	var detail = document.getElementById('zoomImg');
	detail.innerHTML = "<img src='/inc/gera_thumb.inc.php?imagem=../img/imoveis/0" + folder + "/" + img + "' border='0' />";
	//detail.innerHTML = "<a href='img/imoveis/0" + folder + "/" + zoomIn + "' rel='lightbox' title='" + title + "'><img src='/inc/gera_thumb.inc.php?imagem=../img/imoveis/0" + folder + "/" + img + "' border='0' /></a>";
}

/*** Busca *************************************************/
function searchCidades(){
	var searchCategorias = document.getElementById('searchCategorias').value;
	var searchTipo = document.getElementById('searchTipo').value;

	if (searchTipo == 0){
		alert("Por favor selecione um tipo!");		
	} else {
		ajax = runAjax();
		ajax.onreadystatechange = displayCidades;
		ajax.open("GET","inc/cidades.php?searchCategorias=" + searchCategorias + "&searchTipo=" + searchTipo);
		ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		ajax.send(null);
	}	
}

function displayCidades() {
	if (ajax.readyState == 4){
		if (ajax.status == 200) {
			if (ajax.responseText != 0){
				document.getElementById('displayCidades').style.display = "block";
				document.getElementById('displayCidades').innerHTML = ajax.responseText;		
			} else {
				alert("Nenhuma cidade publicada no momento.");
				document.getElementById('displayCidades').innerHTML = "";	
				document.getElementById('displayCidades').style.display = "none";	
			}
			
		} else {
			alert("Houve um problema ao carregar o texto:\n " + ajax.statusText);
		}
	}
}


function searchBairros(){
	var searchCategorias = document.getElementById('searchCategorias').value;
	var searchTipo = document.getElementById('searchTipo').value;
	var searchCidades = document.getElementById('searchCidades').value;

	if (searchCidades == 0){
		document.getElementById('displayBairros').innerHTML = "";
		document.getElementById('displayBairros').style.display = "none";
		alert("Por favor selecione uma cidade!");		
	} else {
		ajax = runAjax();
		ajax.onreadystatechange = displayBairros;
		ajax.open("GET","inc/bairros.php?searchCidades=" + searchCidades + "&searchCategorias=" + searchCategorias + "&searchTipo=" + searchTipo);
		ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		ajax.send(null);
	}
}

function displayBairros() {
	if (ajax.readyState == 4){
		if (ajax.status == 200) {
			if (ajax.responseText != 0){
				document.getElementById('displayBairros').style.display = "block";
				document.getElementById('displayBairros').innerHTML = ajax.responseText;		
			} else {
				alert("Nenhum bairro publicado no momento.");
				document.getElementById('displayBairros').innerHTML = "";	
				document.getElementById('displayBairros').style.display = "none";	
			}
			
		} else {
			alert("Houve um problema ao carregar o texto:\n " + ajax.statusText);
		}
	}
}

function searchType(){
	var searchCategorias = document.getElementById('searchCategorias').value;
	
	ajax = runAjax();
	ajax.onreadystatechange = displayType;
	ajax.open("GET","inc/tipo.php?searchCategorias=" + searchCategorias);
	ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	ajax.send(null);
}

function displayType() {
	if (ajax.readyState == 4){
		if (ajax.status == 200) {
			if (ajax.responseText != 0){
				document.getElementById('displayType').style.display = "block";
				document.getElementById('displayType').innerHTML = ajax.responseText;		
			} else {
				alert("Nenhum imóvel publicado no momento.");
				document.getElementById('displayType').innerHTML = "";	
				document.getElementById('displayType').style.display = "none";	
			}
			
		} else {
			alert("Houve um problema ao carregar o texto:\n " + ajax.statusText);
		}
	}
}

function searchCategory(){
	
	var searchCidades = document.getElementById('searchCidades').value;
	var searchBairro = document.getElementById('searchBairro').value;
	var searchTipo = document.getElementById('searchTipo').value;
	
	if (searchCidades == 0){
		document.getElementById('displayBairros').innerHTML = "";
		document.getElementById('displayBairros').style.display = "none";
		alert("Por favor selecione uma cidade!");		
	} else {
		if (searchBairro == 0){
			document.getElementById('displayType').innerHTML = "";
			document.getElementById('displayType').style.display = "none";
			alert("Por favor selecione um bairro!");		
		} else {
			if (searchTipo == 0){
			document.getElementById('displayCategoria').innerHTML = "";
			document.getElementById('displayCategoria').style.display = "none";
			alert("Por favor selecione um tipo!");		
			} 
			else
			{
				ajax = runAjax();
				ajax.onreadystatechange = displayCategoria;
				ajax.open("GET","inc/categoria.php?searchCidades=" + searchCidades + "&searchBairro=" + searchBairro + "&searchTipo=" + searchTipo);
				ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
				ajax.send(null);
			}
		}
	}
}

function displayCategoria() {
	if (ajax.readyState == 4){
		if (ajax.status == 200) {
			if (ajax.responseText != 0){
				document.getElementById('displayCategoria').style.display = "block";
				document.getElementById('displayCategoria').innerHTML = ajax.responseText;		
			} else {
				alert("Nenhum imóvel publicado no momento.");
				document.getElementById('displayType').innerHTML = "";	
				document.getElementById('displayType').style.display = "none";	
				document.getElementById('displayCategoria').innerHTML = "";	
				document.getElementById('displayCategoria').style.display = "none";	
			}
			
		} else {
			alert("Houve um problema ao carregar o texto:\n " + ajax.statusText);
		}
	}
}

function validSearch() 
{
	var Codigo = document.getElementById('searchCodigo').value;
	var Cidades = document.getElementById('searchCidades').value;
	var msg = "";
	
	if (Cidades == 0)
	{
		msg += "Selecione uma cidade!";
	} 
	else 
	{
		var Bairro = document.getElementById('searchBairro').value;
		if (Bairro == 0) {
			msg += "Selecione um bairro!";
		} 
		else 
		{
			var Tipo = document.getElementById('searchTipo').value;
			if (Tipo == 0){
				msg += "Selecione um tipo de imóvel!";
			} 
		}
	}

	if (msg != "") {
		alert(msg);
		return false;
	} 
	else {
		return true;
	}
}

/************************************************************************************************************
(C) www.dhtmlgoodies.com, November 2005

This is a script from www.dhtmlgoodies.com. You will find this and a lot of other scripts at our website.	

Terms of use:
You are free to use this script as long as the copyright message is kept intact. However, you may not
redistribute, sell or repost it without our permission.

Thank you!

www.dhtmlgoodies.com
Alf Magne Kalleland

************************************************************************************************************/
	
var tableWidget_okToSort = true;
var tableWidget_arraySort = new Array();
tableWidget_tableCounter = 1;
var activeColumn = new Array();
var currentColumn = false;

function sortNumeric(a,b){
	
	a = a.replace(/,/,'.');
	b = b.replace(/,/,'.');
	a = a.replace(/[^\d\.\/]/g,'');
	b = b.replace(/[^\d\.\/]/g,'');
	if(a.indexOf('/')>=0)a = eval(a);
	if(b.indexOf('/')>=0)b = eval(b);
	return a/1 - b/1;
}


function sortString(a, b) {

  if ( a.toUpperCase() < b.toUpperCase() ) return -1;
  if ( a.toUpperCase() > b.toUpperCase() ) return 1;
  return 0;
}
	
function sortTable()
{
	if(!tableWidget_okToSort)return;
	tableWidget_okToSort = false;
	/* Getting index of current column */
	var obj = this;
	var indexThis = 0;
	while(obj.previousSibling){
		obj = obj.previousSibling;
		if(obj.tagName=='TD')indexThis++;		
	}
	
	if(this.getAttribute('direction') || this.direction){
		direction = this.getAttribute('direction');
		if(navigator.userAgent.indexOf('Opera')>=0)direction = this.direction;
		if(direction=='ascending'){
			direction = 'descending';
			this.setAttribute('direction','descending');
			this.direction = 'descending';	
		}else{
			direction = 'ascending';
			this.setAttribute('direction','ascending');		
			this.direction = 'ascending';		
		}
	}else{
		direction = 'ascending';
		this.setAttribute('direction','ascending');
		this.direction = 'ascending';
	}
	
	var tableObj = this.parentNode.parentNode.parentNode;
	var tBody = tableObj.getElementsByTagName('TBODY')[0];
	
	var widgetIndex = tableObj.getAttribute('tableIndex');
	if(!widgetIndex)widgetIndex = tableObj.tableIndex;
	
	if(currentColumn)currentColumn.className='';
	document.getElementById('col' + widgetIndex + '_' + (indexThis+1)).className='highlightedColumn';
	currentColumn = document.getElementById('col' + widgetIndex + '_' + (indexThis+1));

		
	var sortMethod = tableWidget_arraySort[widgetIndex][indexThis]; // N = numeric, S = String
	if(activeColumn[widgetIndex] && activeColumn[widgetIndex]!=this){
		if(activeColumn[widgetIndex])activeColumn[widgetIndex].removeAttribute('direction');			
	}

	activeColumn[widgetIndex] = this;
	
	var cellArray = new Array();
	var cellObjArray = new Array();
	for(var no=1;no<tableObj.rows.length;no++){
		var content= tableObj.rows[no].cells[indexThis].innerHTML+'';
		cellArray.push(content);
		cellObjArray.push(tableObj.rows[no].cells[indexThis]);
	}
	
	if(sortMethod=='N'){
		cellArray = cellArray.sort(sortNumeric);
	}else{
		cellArray = cellArray.sort(sortString);
	}
	
	if(direction=='descending'){
		for(var no=cellArray.length;no>=0;no--){
			for(var no2=0;no2<cellObjArray.length;no2++){
				if(cellObjArray[no2].innerHTML == cellArray[no] && !cellObjArray[no2].getAttribute('allreadySorted')){
					cellObjArray[no2].setAttribute('allreadySorted','1');	
					tBody.appendChild(cellObjArray[no2].parentNode);				
				}				
			}			
		}
	}else{
		for(var no=0;no<cellArray.length;no++){
			for(var no2=0;no2<cellObjArray.length;no2++){
				if(cellObjArray[no2].innerHTML == cellArray[no] && !cellObjArray[no2].getAttribute('allreadySorted')){
					cellObjArray[no2].setAttribute('allreadySorted','1');	
					tBody.appendChild(cellObjArray[no2].parentNode);				
				}				
			}			
		}				
	}
	
	for(var no2=0;no2<cellObjArray.length;no2++){
		cellObjArray[no2].removeAttribute('allreadySorted');		
	}

	tableWidget_okToSort = true;
	
	
}
function initSortTable(objId,sortArray)
{
	var obj = document.getElementById(objId);
	obj.setAttribute('tableIndex',tableWidget_tableCounter);
	obj.tableIndex = tableWidget_tableCounter;
	tableWidget_arraySort[tableWidget_tableCounter] = sortArray;
	var tHead = obj.getElementsByTagName('THEAD')[0];
	var cells = tHead.getElementsByTagName('TD');
	for(var no=0;no<cells.length;no++){
		if(sortArray[no]){
			cells[no].onclick = sortTable;	
		}else{
			cells[no].style.cursor = 'default';	
		}
	}		
	for(var no2=0;no2<sortArray.length;no2++){	/* Right align numeric cells */
		if(sortArray[no2] && sortArray[no2]=='N')obj.rows[0].cells[no2].style.textAlign='right';
	}		
	
	tableWidget_tableCounter++;
}

/*** Sort **************************************************/
function selectSort(param,begin,results){
	
	ajax = runAjax();
	ajax.onreadystatechange = showSort;
	ajax.open("GET","imoveis_sort.php?param=" + param + "&begin=" + begin + "&results=" + results);
	ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	ajax.send(null);
}

function showSort() {
	if (ajax.readyState == 4){
		if (ajax.status == 200) {
			if (ajax.responseText != 0){
				document.getElementById('showResults').innerHTML = ajax.responseText;		
			} 
			
		} else {
			alert("Houve um problema ao carregar o texto:\n " + ajax.statusText);
		}
	}
}

/*** Block **************************************************/
function click() {
	if (event.button==2||event.button==3) {
		oncontextmenu='return false';
	}
}
document.onmousedown=click;
document.oncontextmenu = new Function("return false;");