var isIe = (document.all);
function $(id){
	return document.getElementById(id);
}
function $$(name){
	return document.getElementsByName(name);
}

var __docIsLoaded = false;
function appendOnLoad(ev){
	if(typeof __docIsLoaded != 'undefined' && __docIsLoaded){
		ev();
		return;
	}
	
	var tmp = window.onload;
	window.onload = function(){
		__docIsLoaded = 'ok';
		if(tmp){
			tmp();
		}
		ev();
	};
}

// Abas
function aba(td_ids, sel, theme){
	this.tabs = [];
	this.enable(td_ids);
	this.showing  = td_ids[0];
	this.callback = false;
	this.theme    = theme?theme:1;
	
	if(sel){
		this.change(sel);
	}
}
aba.prototype.setCb   = function(cb_function){
	this.callback = cb_function;
}
aba.prototype.enable  = function(td_ids){
	var t = this;
	for(var i = 0; i < td_ids.length; i++){
		var o = $(td_ids[i]);
		this.tabs[this.tabs.length] = o;
		
		o.style.cursor = isIe?'hand':'pointer';
		o.onclick      = function(){ t.change(this.id); return false; }
		o.childNodes[0].onclick = function(){ return false };
	}
}
aba.prototype.show    = function(id, yesno){
	var a = $(id);
	var b = $(id+'_body');
	if(!b)
		return alert("Div "+id+"_body não existe!");
	
	var ob = a.style.background;
	if(this.theme == 1) var nb = "url(images/menu"+(yesno?2:1)+".jpg)";
	if(this.theme == 2) var nb = "url(images/fundo_cinza"+(yesno?'':'1')+".png)";
	
	if(ob != nb) a.style.background = nb;
	b.style.display    = yesno?'block':'none';
}
aba.prototype.change  = function(id){
	if(this.callback)
		this.callback(id);
	
	this.showing = id;
	this.refresh();
}
aba.prototype.refresh = function(){
	if($('aba_sel'))
		$('aba_sel').value = this.showing;
	for(var i = 0; i < this.tabs.length; i++){
		this.show(this.tabs[i].id, this.tabs[i].id==this.showing);
	}
}

// login
function login(){}
login.toProceed = function(link){
	login.proceedTo = link;
	login.createPopup();
}
login.onSubmit  = function(){
	var usr = $('pop_log_user').value;
	var pwd = $('pop_log_pwd') .value;
	draw.setLoginStatus("Aguarde...");
	dHttp.call("ajax.login.php", "user="+usr+"&pass="+pwd, login.onReturn);
}
login.onReturn  = function(ret){
	if(ret == 'OK'){
		draw.setLoginStatus("Sucesso, redirecionando...");
		top.location.href = login.proceedTo;
	}
	else{
		draw.setLoginStatus("Usuário ou Senha não encontrados");
	}
}
login.createPopup = function(){
	draw.background();
	draw.loginScreen();
}
login.forgot    = function(){
	dHttp.call("ajax.esqueci_senha.php", false, function(ret){
		draw.logElement.innerHTML = ret;
	});
}
login.forgotSub = function(){
	var email = $('pop_forg_email');
	top.location.href = "esqueceu_senha.php?email="+email.value;
}
login.goBack    = function(){
	var nd = draw.logElement;
	dHttp.call("ajax.login.php", false, function(ret){ nd.innerHTML = ret; $('pop_log_user').focus(); });
}

// Drawing
function draw(){}
draw.background       = function(){
	if(draw.bgElement){
		draw.bgElement.style.display = 'block';
		return;
	}
	
	var md = document.createElement('div');
	md.style.position = 'absolute';
	md.style.left     = 0;
	md.style.top      = 0;
	md.style.zIndex   = 15;
	md.style.background = '#000000';
	md.style.width    = '100%';
	md.style.height   = document.body.offsetHeight+"px";
	md.style.opacity  = 0.45;
	md.style.filter   = "alpha(opacity=45)";
	document.body.appendChild(md);
	window.scroll(0, 0);
	
	draw.bgElement = md;
}
draw.welcomeScreen    = function(){
	if(draw.welElement){
		draw.welElement.style.display = 'block';
		$('pop_wel_dropUf').focus();
		return;
	}
	
	var nd = document.createElement('div');
	nd.style.textAlign = 'center';
	nd.style.position = 'absolute';
	nd.style.width    = '300px';
	nd.style.left     = (document.body.offsetWidth/2-300/2)+"px";
	nd.style.top      = 0;
	nd.style.zIndex   = 16;
	nd.style.marginTop = '100px';
	nd.innerHTML       = "Aguarde...";
	document.body.appendChild(nd);
	dHttp.call("ajax.index_local.php", false, function(ret){ nd.innerHTML = ret; $('pop_wel_dropUf').focus(); wel_refreshCid(); });
	
	draw.welElement = nd;
}
draw.welcomeClear     = function(){
	if(draw.welElement)
		draw.welElement.style.display = 'none';
}
draw.loginScreen      = function(){
	if(draw.logElement){
		draw.logElement.style.display = 'block';
		$('pop_log_user').focus();
		return;
	}
	
	var nd = document.createElement('div');
	nd.style.textAlign = 'left';
	nd.style.position = 'absolute';
	nd.style.width    = '500px';
	nd.style.left     = (document.body.offsetWidth/2-500/2)+"px";
	nd.style.top      = 0;
	nd.style.zIndex   = 16;
	nd.style.marginTop = '50px';
	nd.innerHTML       = "Aguarde...";
	document.body.appendChild(nd);
	dHttp.call("ajax.login.php", false, function(ret){ nd.innerHTML = ret; $('pop_log_user').focus(); });
	
	draw.logElement = nd;
}
draw.setLoginStatus   = function(str){
	$('pop_log_status').innerHTML = str;
}
draw.clearBackground  = function(){
	if(draw.bgElement)
		draw.bgElement.style.display = 'none';
}
draw.clearLoginScreen = function(){
	if(draw.logElement)
		draw.logElement.style.display = 'none';
}
draw.clearAll         = function(){
	draw.clearBackground();
	draw.clearLoginScreen();
	draw.welcomeClear();
}

function wel_changeCity(now){
	wel_selId = now;
	draw.background();
	draw.welcomeScreen();
}
function wel_refreshUf(){
	var duf = $('pop_wel_dropUf');
	var dci = $('pop_wel_dropCid');
	
	if(!duf.value){
		selectObj.clearAll(dci, "Selecione o Estado...");
		wel_refreshCid();
	}
	else{
		var uf = duf.value;
		selectObj.clearAll(dci, "Carregando cidades...");
		wel_refreshCid();
		dHttp.call("ajax.loadRegioes.php?uf="+uf, false, function(ret){
			selectObj.clearAll(dci, 'Selecione...');
			var lines = ret.split("\n");
			for(var i = 0; i < lines.length; i++){
				var tmp = lines[i].split(":::::");
				selectObj.insert(dci, tmp[0], tmp[1]);
			}
		});
	}
}
function wel_refreshCid(){
	var regId = $('pop_wel_dropCid').value;
	
	dHttp.call("ajax.loadRegioes.php?reg="+regId, false, function(ret){
		$('loginOrCity_List').innerHTML = ret;
	});
}
function wel_confirmCid(){
	var dciv = $('pop_wel_dropCid').value;
	if(!dciv){
		alert("Por favor, escolha uma cidade para continuar.");
		return false;
	}
	
	if(dciv == wel_selId){
		dHttp.call("ajax.setCidade.php", "cid="+dciv, function(ret){});
		draw.clearAll();
		return;
	}
	
	dHttp.call("ajax.setCidade.php", "cid="+dciv, function(ret){
		if(window.location.href.indexOf("?") == -1){
			window.location.replace(window.location.href+"?");
		}
		else{
			var goTo = window.location.href;
			
			if(goTo.indexOf('?ref=') != -1){
				goTo = '/?';
			}
			else{
				goTo = goTo.replace(/cid=([0-9+])&regiao=.+?&/,   "");
				goTo = goTo.replace(/&cid=([0-9+])&regiao=.+?$/,  "");
				goTo = goTo.replace(/\?cid=([0-9+])&regiao=.+?$/, "?");
				goTo = goTo.replace("&r=1",  "");
			}
			window.location.replace(goTo+"&r=1");
		}
	});
}


// SelectObj
function selectObj(){}
selectObj.clearAll   = function(obj, defaultValue){
	obj.options.length = 0;
	if(defaultValue)
		selectObj.insert(obj, '', defaultValue);
}
selectObj.insert     = function(obj, value, text){
	var elOptNew = document.createElement('option');
	elOptNew.value = value;
	elOptNew.text  = text;
 	try{
		obj.add(elOptNew, null);
	}
	catch(e){
		obj.add(elOptNew);
	}
}
selectObj.insertList = function(obj, list){
	for(var i = 0; i < list.length; i++){
		(typeof list[i] == "string")?
			selectObj.insert(obj, list[i], list[i]):
			selectObj.insert(obj, list[i][0], list[i][1]);
	}
}
selectObj.select     = function(obj, value){
	for(var i = 0; i < obj.options.length; i++){
		if(obj.options[i].value == value){
			obj.selectedIndex = i;
			continue;
		}
	}
}



// dCEP
function cep(){}
cep.init     = function(){
	if(cep.inited)
		return;
	cep.inited = true;
	cep.autoId = 1;
	cep.lastVl = [];
	cep.fillIn = [];
}
cep.help     = function(){
	alert(
		"CEP.activate(field, fillInto)\n"+
		"\n"+
		"Sendo:\n"+
		"field:    Objeto do campo 'CEP'\n"+
		"fillInto: Array[uf,cidade,endereco,bairro]\n"
	);
}
cep.$ = function(id){
	return document.getElementById(id);
}
cep.$$ = function(name){
	return document.getElementsByName(name)[0];
}
cep.activateByNames = function(field, fillInto){
	cep.activate(cep.$$(field), [cep.$$(fillInto[0]), cep.$$(fillInto[1]), cep.$$(fillInto[2]), cep.$$(fillInto[3])]);
}
cep.activateByIds   = function(field, fillInto){
	cep.activate(cep.$(field), [cep.$(fillInto[0]), cep.$(fillInto[1]), cep.$(fillInto[2]), cep.$(fillInto[3])]);
}
cep.activate = function(field, fillInto){
	cep.init();
	if(!field.id)
		field.id = 'cep_auto_id'+(cep.autoId++);
	
	cep.fillIn[field.id] = fillInto;
	cep.lastVl[field.id] = field.value;
	
	var ku = field.onkeyup;
	field.onkeyup = function(){ if(ku) ku(); cep.keyUp(field) }
}
cep.keyUp    = function(field){
	var c = field.value;
	if(c.length != 9)
		return;
		
	if(c == cep.lastVl[field.id])
		return;
	
	cep.lastVl[field.id] = c;
	dHttp.call("ajax.loadCep.php", 'cep='+c, function(ret){ cep.cb(field, ret) });
}
cep.cb       = function(field, ret){
	var parts = ret.split("=");
	var fUF  = cep.fillIn[field.id][0];
	var fCID = cep.fillIn[field.id][1];
	var fEND = cep.fillIn[field.id][2];
	var fBAI = cep.fillIn[field.id][3];
	
	if(parts[0] == "OK " || parts[0] == "OK+" || parts[0] == "ERR"){
		if(parts[0] == "ERR") 
			var subparts = "||||||||".split("||");
		else
			var subparts = parts[1].split("||");
		
		fUF.value  = subparts[4];
		fCID.value = subparts[3];
		fEND.value = subparts[0]+" "+subparts[1];
		if(fBAI)
			fBAI.value = subparts[2];
	}
	
	fUF.readonly  = 
	fCID.readonly = 
	fEND.readonly = false; // !(parts[0] == "OK+" || parts[0] == "ERR");
	if(fBAI) fBAI.readonly = fEND.readonly;
}


// Template:
function tplTab(){}
tplTab.$              = function(id){
	return document.getElementById(id);
}
tplTab.init           = function(settings){
	tplTab.tab = 1;
	tplTab.set = settings;
	tplTab.refreshTab();
	
	// Insere a ação nas abas
	if(!tplTab.set.onlyAnunc){
		tplTab.$('nav_qsearch_tabs').children[0].children[0].onclick = function(){ tplTab.setTab(1); return false; };
		tplTab.$('nav_qsearch_tabs').children[1].children[0].onclick = function(){ tplTab.setTab(2); return false; };
	}
	
	// Insere a ação nos drop-downs
	var tplFields = [];
	if(tplTab.set.theme == 1) var tplFields = ['TPL_dropTipo',  'TPL_dropCateg', 'TPL_dropTipoI', 'TPL_dropRooms', 'TPL_dropVal', 'TPL_dropCida'];
	if(tplTab.set.theme == 2) var tplFields = ['TPL_dropRooms', 'TPL_dropVal',   'TPL_dropArea', 'TPL_dropCida'];
	for(var i = 0; i < tplFields.length; i++){
		var obj = tplTab.$(tplFields[i]);
		if(!obj)
			alert("Object "+tplFields[i]+" not found. Theme="+tplTab.set.theme);
		else{
			tplTab.makeDrop(obj, i+1);
			obj.options[0].text  = "Indiferente";
			obj.options[0].value = '';
			if(tplFields[i] == 'TPL_dropVal' && tplTab.set.theme == 1 && __isIE){
				var expandIt     = function(){
					var ta = tplTab.$('TPL_dropTipo');
					var tb = tplTab.$('TPL_dropCateg');
					var _useWidth = 0;
					
					if(ta.value == 'aluguel') _useWidth = 170;
					if(ta.value == 'venda')   _useWidth = 210;
					
					if(_useWidth && obj.style.position != 'absolute'){
						var pos = _getElementAbsPos(obj);
						obj.style.position            = 'absolute';
						obj.style.width               = _useWidth+'px';
						obj.style.top                 = (pos.y)+"px";
					}
				}
				var backToNormal = function(){
					obj.style.width    = '';
					obj.style.position = '';
				}
				
				// Globals:
				__tplIsOver    = false;
				__tplKeepLarge = false;
				
				obj.onmouseover = function(){
					__tplIsOver = true;
					expandIt();
				}
				obj.onmouseout  = function(){
					__tplIsOver = false;
					if(!__tplKeepLarge)
						backToNormal();
				}
				
				obj.onchange    = function(){
					setTimeout("__tplKeepLarge = false;", 10);
					backToNormal();
				};
				obj.onblur      = function(){
					__tplKeepLarge = false;
					backToNormal();
				};
				obj.onclick     = function(){
					__tplKeepLarge = true;
				}
				/*
				var debugIt = function(){
					var str = "";
					if(typeof(__tplKeepLarge) != 'undefined')
						str = __tplKeepLarge?"SIM":"NÃO";
					else
						str = "UNSET";
					
					if(typeof __tplIsOver != 'undefined')
						str = str+"/"+(__tplIsOver?"OVER":"OUT");
					
					$('TPL_quartosStr').innerHTML = str;
					
					setTimeout(debugIt, 100);
				}
				debugIt();
				*/
			}
		}
	}
	
	// Prefill values
	if(tplTab.set.theme == 1){
		tplTab.refreshQSearch(1, 1);
		tplTab.refreshQSearch(1, 2);
		tplTab.refreshQSearch(1, 3);
		tplTab.refreshQSearch(1, 4);
		tplTab.refreshQSearch(1, 5);
	}
	if(tplTab.set.theme == 2){
		tplTab.refreshQSearch(2, 1);
		tplTab.refreshQSearch(2, 2);
		tplTab.refreshQSearch(2, 3);
	}
	
	if(tplTab.set.theme == 1
	|| tplTab.set.theme == 2
	|| tplTab.set.theme == 5){
		var els = document.getElementsByName('tpl_cbtipo');
		for(var i = 0; i < els.length; i++)
			els[i].onclick = tplTab.achange;
		
		tplTab.achange();
	}
}
tplTab.makeDrop       = function(drop, n){
	drop.onchange = function(){ tplTab.refreshQSearch(tplTab.set.theme, n); }
}
tplTab.setTab         = function(n){
	tplTab.tab = n;
	tplTab.refreshTab();
}
tplTab.refreshTab     = function(){
	tplTab.$('nav_qsearch_tabs').children[0].className = (tplTab.tab == 1)?'sel':'';
	
	if(!tplTab.set.onlyAnunc){
		tplTab.$('nav_qsearch_tabs').children[0].children[0].children[0].src = 'images/'+tplTab.set.image+'_'+((tplTab.tab == 1)?'azul':'cinza')+".png";
		tplTab.$('nav_qsearch_tabs').children[1].className = (tplTab.tab == 2)?'sel':'';
		
		tplTab.$('nav_qsearch_tabs').children[1].children[0].children[0].src = 'images/anunciantes_'+((tplTab.tab == 2)?'azul':'cinza')+".png";
		tplTab.$('nav_qsearch_body1').style.display = (tplTab.tab == 1)?'block':'none';
		tplTab.$('nav_qsearch_body2').style.display = (tplTab.tab == 2)?'block':'none';
	}
}
tplTab.refreshQSearch = function(theme, n){
	if(theme == 1){
		var ta = tplTab.$('TPL_dropTipo');
		var tb = tplTab.$('TPL_dropCateg');
		var tc = tplTab.$('TPL_dropTipoI');
		var td = tplTab.$('TPL_dropRooms'); var td2 = tplTab.$('TPL_quartosStr');
		var te = tplTab.$('TPL_dropVal');
		
		if(n==1){
			selectObj.clearAll(te, 'Indiferente');
			if(ta.value == 'aluguel'){
				selectObj.insert(te, "-300", "Menos de R$ 300,00");
				selectObj.insert(te, "300-600",   "Entre R$ 300,00 e R$ 600,00");
				selectObj.insert(te, "600-900",   "Entre R$ 600,00 e R$ 900,00");
				selectObj.insert(te, "900-1200",  "Entre R$ 900,00 e R$ 1.200,00");
				selectObj.insert(te, "1200-1500", "Entre R$ 1.200,00 e R$ 1.500,00");
				selectObj.insert(te, "1500-2000", "Entre R$ 1.500,00 e R$ 2.000,00");
				selectObj.insert(te, "2000-",     "Acima de R$ 2.000,00");
			}
			else if(ta.value == 'venda'){
				selectObj.insert(te, "-50000",          "Menos de R$ 50.000,00");
				selectObj.insert(te, "50000-100000",    "Entre R$ 50.000,00 e R$ 100.000,00");
				selectObj.insert(te, "100000-200000",   "Entre R$ 100.000,00 e R$ 200.000,00");
				selectObj.insert(te, "200000-300000",   "Entre R$ 200.000,00 e R$ 300.000,00");
				selectObj.insert(te, "300000-400000",   "Entre R$ 300.000,00 e R$ 400.000,00");
				selectObj.insert(te, "400000-500000",   "Entre R$ 400.000,00 e R$ 500.000,00");
				selectObj.insert(te, "500000-700000",   "Entre R$ 500.000,00 e R$ 700.000,00");
				selectObj.insert(te, "700000-1000000",  "Entre R$ 700.000,00 e R$ 1.000.000,00");
				selectObj.insert(te, "1000000-1500000", "Entre R$ 1.000.000,00 e R$ 1.500.000,00");
				selectObj.insert(te, "1500000-2000000", "Entre R$ 1.500.000,00 e R$ 2.000.000,00");
				selectObj.insert(te, "2000000-",        "Acima de R$ 2.000.000,00");
			}
		}
		if(n==2){
			var tx = tb.options[tb.selectedIndex].text.toLowerCase();
			
			td2.innerHTML =  (tx == 'comercial')?"salas":"quartos";
			td.disabled   = !(tx == 'comercial' || tx == 'residencial' || tx == 'temporada' || tx == 'estudante');
			if(td.disabled)
				td.selectedIndex = 0; 
			
			selectObj.clearAll(tc, 'Carregando lista...');
			dHttp.call("ajax.loadTipos.php?categ="+tx, false, function(ret){
				selectObj.clearAll(tc, 'Indiferente');
				var lines = ret.split("\n");
				for(var i = 0; i < lines.length; i++){
					var tmp = lines[i].split(":::::");
					selectObj.insert(tc, tmp[0], tmp[1]);
				}
			});
		}
	}
	if(theme == 2){
		// Onde: exclusivos | imobiliarios
		if((typeof _theme2Loaded) != 'undefined')
			return
		
		_theme2Loaded = true;
		var tv = tplTab.$('TPL_dropVal');
		var ta = tplTab.$('TPL_dropArea');
		selectObj.clearAll(ta);
		selectObj.clearAll(tv);
		
		selectObj.insert(tv, "",  "Indiferente");
		selectObj.insert(ta, "",  "Indiferente");
		
		selectObj.insert(tv, "-50000",          "Menos de R$ 50.000,00");
		selectObj.insert(tv, "50000-100000",    "Entre R$ 50.000,00 e R$ 100.000,00");
		selectObj.insert(tv, "100000-200000",   "Entre R$ 100.000,00 e R$ 200.000,00");
		selectObj.insert(tv, "200000-300000",   "Entre R$ 200.000,00 e R$ 300.000,00");
		selectObj.insert(tv, "300000-400000",   "Entre R$ 300.000,00 e R$ 400.000,00");
		selectObj.insert(tv, "400000-500000",   "Entre R$ 400.000,00 e R$ 500.000,00");
		selectObj.insert(tv, "500000-700000",   "Entre R$ 500.000,00 e R$ 700.000,00");
		selectObj.insert(tv, "700000-1000000",  "Entre R$ 700.000,00 e R$ 1.000.000,00");
		selectObj.insert(tv, "1000000-1500000", "Entre R$ 1.000.000,00 e R$ 1.500.000,00");
		selectObj.insert(tv, "1500000-2000000", "Entre R$ 1.500.000,00 e R$ 2.000.000,00");
		selectObj.insert(tv, "2000000-",        "Acima de R$ 2.000.000,00");
		
		selectObj.insert(ta, "-50",          "Menos de 50m²");
		selectObj.insert(ta, "50-100",       "De 50 a 100m²");
		selectObj.insert(ta, "100-200",      "De 100 a 200m²");
		selectObj.insert(ta, "200-300",      "De 200 a 300m²");
		selectObj.insert(ta, "300-400",      "De 300 a 400m²");
		selectObj.insert(ta, "400-500",      "De 400 a 500m²");
		selectObj.insert(ta, "500-1000",     "De 500 a 1.000m²");
		selectObj.insert(ta, "1000-2000",    "De 1.000 a 2.000m²");
		selectObj.insert(ta, "2000-3000",    "De 2.000 a 3.000m²");
	}
}
tplTab.achange        = function(){
	var tpanunclst = tplTab.$('tpl_anunciantes');
	var lookFor    = document.getElementsByName('tpl_cbtipo')[0].checked?'i':'c';
	dHttp.call("ajax.loadUsers.php", "perf="+lookFor, function(ret){
		selectObj.clearAll(tpanunclst, 'Selecione:');
		var lines = ret.split("\n");
		for(var i = 0; i < lines.length; i++){
			var tmp = lines[i].split(":::::");
			selectObj.insert(tpanunclst, tmp[0], tmp[1]);
		}
	});
	
	tplTab.$('tpl_qs_ctipo').style.display = (lookFor == 'c')?'block':'none';
}

function keepMeLogged(){
	dHttp.call("ajax.loadCidadesEBairros.php", false, function(ret){});
	setTimeout(keepMeLogged, 60*1000);
}
function callFlash(_path,_w,_h){
	var flash = '';
	if(isIe){
		flash += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="' + _w + '" height="' + _h + '">';
		flash += '<param name="allowScriptAccess" value="never" />'; // sameDomain
		flash += '<param name="allowFullScreen" value="false" />';
		flash += '<param name="quality" value="high" />';
		flash += '<param name="wmode" value="transparent" />';
		flash += '<param name="movie" value="' + _path + '" />';
		flash += '</object>';
	}
	else{
		flash += '<embed src="' + _path + '" quality="high" width="' + _w + '" height="' + _h + '" wmode="transparent" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />';
	}
	document.write(flash);
}
function loadScript(sScriptSrc, oCallback) {
	var oHead   = document.getElementsByTagName('head')[0];
	var oScript = document.createElement('script');
	oScript.type = 'text/javascript';
	oScript.src = sScriptSrc;
	if(oCallback){
		oScript.onload = oCallback;
		oScript.onreadystatechange = function() {
			if (this.readyState == 'complete') {
				oCallback();
			}
		}
	}
	oHead.appendChild(oScript);
}
function gMapInit(div, lat, lng){
	if (GBrowserIsCompatible()) {
		var dv = $(div);
		var map = new GMap2($(div));
		var cen = new GLatLng(lat, lng);
		map.setCenter(cen, 16);
		map.addControl(new GLargeMapControl());
		map.addControl(new GOverviewMapControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new GScaleControl());
		
		var icon              = new GIcon;
		icon.image            = "images/mark.png";
		icon.shadow           = "images/marks.png";
		icon.iconSize         = new GSize (46,40);
		icon.iconAnchor       = new GPoint(23,20);
		icon.infoWindowAnchor = new GPoint(23,20);
		
		var mk = new GMarker(cen, { icon: icon });
		map.addOverlay(mk);
		
		return { map: map, marker: mk }
	}
	return false;
}

function indicar(ref){
	window.open('indique_para_um_amigo.php?ref='+ref, 'indicar', 'width=300,height=280,toolbar=no');
}
function addToFav_cb(obj, oStr, ret){
	var opos = _getElementAbsPos(obj);
	var favc = $('fav_cb');
	var nStr = "";
	
	if(ret == '0')               nStr = "Falha ao adicionar o imóvel aos favoritos!";
	if(ret == '1' || ret == '2') nStr = "Imóvel adicionado aos seus favoritos!";
	
	obj.innerHTML = (nStr=="")?ret:nStr;
	if(ret=='0')
		setTimeout(function(){ obj.innerHTML = oStr }, 3500);
	
	//~ $('fav_cb').style.position = 'absolute';
	//~ $('fav_cb').style.display  = 'block';
	//~ $('fav_cb').style.left     = opos.x+obj.offsetWidth-25;
	//~ $('fav_cb').style.top      = opos.y+obj.offsetHeight-5;
}
function addToFav(obj, ref){
	var o  = obj;
	var os = obj.innerHTML;
	o.innerHTML = "Adicionando aos favoritos...";
	dHttp.call("ajax.toggleFav.php", "ref="+ref, function(ret){ addToFav_cb(obj, os, ret) }, 'addfav');
}

function addGlobalFav(){
    var url      = "http://www.clicmeuimovel.com.br/";
    var title    = "CliCMeuImóvel.com.br - O maior portal de imóveis do Brasil!";
    if (window.sidebar) window.sidebar.addPanel(title, url,"");
    else if(window.opera && window.print){
        var mbm = document.createElement('a');
        mbm.setAttribute('rel','sidebar');
        mbm.setAttribute('href',url);
        mbm.setAttribute('title',title);
        mbm.click();
    }
    else if(document.all){window.external.AddFavorite(url, title);}
}

var __isIE         = navigator.appVersion.match(/MSIE/);
var __userAgent    = navigator.userAgent;
var __isFireFox    = __userAgent.match(/firefox/i);
function _getElementAbsPos(obj){
    var res = new Object();
    res.x = 0; res.y = 0;
    if (obj !== null) {
        res.x = obj.offsetLeft;
        res.y = obj.offsetTop;
        
        var offsetParent = obj.offsetParent;
        var parentNode = obj.parentNode;
        var borderWidth = null;

        while (offsetParent != null) {
            res.x += offsetParent.offsetLeft;
            res.y += offsetParent.offsetTop;
            
            var parentTagName = offsetParent.tagName.toLowerCase();    

            if ((__isIE && parentTagName != "table") || 
                (parentTagName == "td")) {            
                borderWidth = _geabp2(offsetParent);
                res.x += borderWidth.left;
                res.y += borderWidth.top;
            }
            
            if (offsetParent != document.body && 
                offsetParent != document.documentobj) {
                res.x -= offsetParent.scrollLeft;
                res.y -= offsetParent.scrollTop;
            }

            //next lines are necessary to support FireFox problem with offsetParent
               if (!__isIE) {
                while (offsetParent != parentNode && parentNode !== null) {
                    res.x -= parentNode.scrollLeft;
                    res.y -= parentNode.scrollTop;
                    parentNode = parentNode.parentNode;
                }    
            }

            parentNode = offsetParent.parentNode;
            offsetParent = offsetParent.offsetParent;
        }
    }
    return res;
}
function _geabp1(width){   // parseBorderWidth
    var res = 0;
    if (typeof(width) == "string" && width != null 
                && width != "" ) {
        var p = width.indexOf("px");
        if (p >= 0) {
            res = parseInt(width.substring(0, p));
        }
        else {
             //do not know how to calculate other 
             //values (such as 0.5em or 0.1cm) correctly now
             //so just set the width to 1 pixel
            res = 1; 
        }
    }
    return res;
}
function _geabp2(element){ // getBorderWidth
	var res   = new Object();
    res.left = 0; res.top = 0; res.right = 0; res.bottom = 0;
    if (window.getComputedStyle) {
        //for Firefox
        var e  = window.getComputedStyle(element, null);
		var pi = parseInt;
        res.left    = pi(e.borderLeftWidth  .slice(0, -2));  
        res.top     = pi(e.borderTopWidth   .slice(0, -2));  
        res.right   = pi(e.borderRightWidth .slice(0, -2));  
        res.bottom  = pi(e.borderBottomWidth.slice(0, -2));  
    }
    else {
		var parse = _geabp1;
		var es    = element.style;
        res.left   = parse(es.borderLeftWidth);
        res.top    = parse(es.borderTopWidth);
        res.right  = parse(es.borderRightWidth);
        res.bottom = parse(es.borderBottomWidth);
    }
   
    return res;
}

function openTermos(){
	window.open('termos_e_condicoes.php?pop=1', 'termos', 'width=450,height=550,scrollbars=yes,toolbar=yes');
	return false;
}

function dI2_NMask(o, m, c, true_if_success){
	if(c == 0){ // special chars
		return true;
	}
	if(m.indexOf('||') != -1){
		var parts = m.split('||');
		for(var i = 0; i < parts.length; i++){
			if(dI2_NMask(o, parts[i], c, true)){
				return true;
			}
		}
		
		var str      = o.value;
		var emptyStr = '';
		for(var i = 0; i < str.length; i++)
			if(!isNaN(str.substr(i, 1)))
				emptyStr += str.substr(i, 1);
		
		o.value = emptyStr;
		
		return true;
	}
	
	var maxL = 0;
	if(m.indexOf('|') != -1){
		var parts = m.split('|');
		m     = parts[0];
		maxL  = parseInt(parts[1]);
	}
	
	if(!maxL && o.value.length >= m.length)
		return false;
	
	var str      = o.value;// + '' + String.fromCharCode(c);
	var emptyStr = '';
	for(var i = 0; i < str.length; i++)
		if(!isNaN(str.substr(i, 1)) && str.substr(i, 1) != ' ')
			emptyStr += str.substr(i, 1);
	
	if(maxL && emptyStr.length+1 > maxL){
		return false;
	}
	
	if(maxL && emptyStr.length+1 != maxL){
		return true_if_success?false:true;
	}
	
	var carrier = 0;
	for(var i = 0; i < m.length; i++){
		if(m.substr(i, 1) == '#'){
			if(carrier+1 > emptyStr.length){
				m = m.substr(0, i);
				break;
			}
			
			m = m.substr(0, i)+emptyStr.substr(carrier, 1)+m.substr(i+1);
			carrier++;
			
			if(carrier == emptyStr.length){
				if(c >= 48 && c <= 57){
				}
				else{
					m = m.substr(0, i+1)+emptyStr.substr(carrier, 1);
					break;
				}
			}
		}
	}
	o.value = m;
	
	return true;
}
function blockFotos(){
	var els = document.getElementsByTagName('img');
	for(var i = 0; i < els.length; i++)
		els[i].oncontextmenu = function(){ return false; };
}
function makeRestrictedButtons(){
	var el  = false;
	var els = document.getElementsByTagName('a');
	var nl  = false;
	for(var x = 0; x < els.length; x++){
		el = els[x];
		if(el.getAttribute('needlogin')){
			el.onclick = function(){ login.toProceed(this.href); return false; }
		}
	}
}
function updateLocation(cid, cidade, uf){
	$('info_log').innerHTML =
		"Você está em <b>"+cidade+", "+uf+"</b>. "+
		"&nbsp; &nbsp; para mudar de localização, "+
		"<b><a href='#' onclick='wel_changeCity("+cid+"); return false;'>CliC aqui!</a></b>";
}




