﻿function init(evt)
{   
    OrderByTable("table_data_imoveis");    
    setConfigFieldsForms();    
    
    // Executa somente na Home
    var refr = ID("ref_imoveis");
    if(refr) 
    {
    	superDestaques(10);
    	
        refr.focus(); 
        setKeyPress([refr],[13],function(){ ID("form1").onsubmit = function(){ return false; }; location.href="default.aspx?action=search&p=find&ref=" + refr.value.trim(); } )        
        
	    Hints.set(
	        { element:ID("ref_imoveis"), text:"Código identificador do imóvel.<br /><small>Usado em anúncios de <em>jornal e vitrine</em>.<br />Digite valores separados por vírgula.</small>", type:2 },
	        { element:ID("localizacao_imoveis"), text:"Bairro, rua, travessa, praça,<br />cidade ou condomínio!<br /><small>Digite valores separados por vírgula.</small>", type:2 }
	    );
	    
	    if(ID("bar_list_imoveis")) getListImoveis("Apartamento", "3", "Aparts. 3 qtos", "Destaque", "tipo, dorm, id", 20, 1); 
	    
	    
	    letreiroImoveis.start(ID("list_lancamentos"),7);
    } 
}
Initialize.add(init);
//---------------------------

function sendMail(_this)
{    
    var s = "";
    var name = "name_email".nvl();
    var email = "email_email".nvl();
    var phones = "phones_email".nvl();
    var message = "message_email".nvl();
    
    if(name.length==0) s += "» Digite seu nome!\n";
    if(phones.length==0) s += "» Digite seu telefone!\n";
    if(email.length==0) s += "» Digite seu e-mail!\n"; else if(!isEmail(email)) s += "» E-mail inválido!\n";            
    if(message.length==0) s += "» Digite sua mensagem!\n";
    
    if(s.length>0) dialog(s);
    else
    {
        if(dialog("Enviar email agora?"))
        {           
            "status_sendmail".setValue("Aguarde, enviando e-mail...");  
            StandByButton(_this);
            var qs = {
            	csrfmiddlewaretoken: "csrfmiddlewaretoken".nvl(),
                to: "to_email".nvl(),
                subject: "subject_email".nvl(),
                name: name,
                email: email,
                phones: phones,
                message: message                
            };  
            
            var action = function(data)
            {
                StandByButton(_this);
                if(data.result!="ok") alert("ATENÇÃO [" + data.result + "]:\n\n" + data.html);
                "status_sendmail".setValue(data.html); 
            }
            ajax.go("/sendmail/", qs, action, action);                   
        }      
    }
}

//--------------------------------------------------------

function getDetailsImovel(row)
{
    windowPopup("details", "/detalhes/" + (typeof row=="number" ? row : row.cells[0].innerHTML), 970, 550, true);
    return void(0);
}

//--------------------------------------------------------

function gotoPage(i)
{
    var f = document.forms[0];
    f.page.value = i;
    f.method = "POST";
    f.submit();
    return void(0);    
}

//--------------------------------------------------------


//funcao chama pelo Flash. Para evitar chamada simultanea e provocar travamento da aplicacao
var _isLoadedFlash = false;
function initListImoveisByTipo()
{
    _isLoadedFlash = true;
    return void(0);
}

//---------------------------------
function status_list_imoveis()
{
	  var bkg = ID('bkg_list_imoveis'), leg = ID('leg_list_imoveis'); 
	  if(!bkg)
	  {
		  bkg = Div('bkg_list_imoveis','','bkg_list_imoveis',document.body);
		  leg = Div('leg_list_imoveis','Aguarde, listando imóveis em destaque...','leg_list_imoveis',document.body);
	  }
	  bkg.style.display = leg.style.display = bkg.style.display == 'block' ? 'none' : 'block';
	  
	  leg.style.top = (document.documentElement.scrollTop + document.body.scrollTop + (document.documentElement.offsetHeight/2) - 20) + 'px';
	  bkg.style.height = (ID('main').offsetHeight) + 'px';
}

function getListImoveis(tipo, dorm, label, expor, orderby, limit, count_max_medias, fcAn)
{      
    if(ajax.isComplete)
    {    
        var ct = ID("list_imoveis");    
        var tp, btOn, bts = ID("bar_list_imoveis").childNodes; 
        for(var i = 0; i<bts.length; i++)
        {
            bts[i].className = bts[i].innerHTML == label ? "bar-bt-active" : "";
            if(bts[i].innerHTML == label) btOn = bts[i];
        }    
        var lb = btOn ? btOn.innerHTML : ( tipo.replace("Apartamento", "Apart.") + ( dorm.length>0 ? " " + dorm + " qto(s)" : "" ) ); 
        ct.innerHTML = "<strong>Aguarde, carregando imóveis " + lb.replaceAll("´","").replace(",", " e ") + "...</strong>";    
           
        var _timerCheckLoadedFlash = setInterval(
        function()
        {
            if(_isLoadedFlash)
            {
            	status_list_imoveis();
                clearInterval(_timerCheckLoadedFlash);                
	            var qs = {
	            	csrfmiddlewaretoken: "csrfmiddlewaretoken".nvl(),
	                tipo: tipo.replaceAll("´","'"),
                    dorm: dorm,
                    expor: expor,
                    orderby: orderby,
                    limit: limit,
                    count_max_medias:count_max_medias,
                    content_type:"html"               
	            };  	            
	            var action = function(data)
	            {
	                ct.innerHTML = data;
                    if(fcAn) fcAn();
                    status_list_imoveis();
	            }
	            ajax.go("/list_imoveis/", qs, action, action, 'html', false);
            }
        }
        , 10);
    }
     
    return 0;
}
//----------------------------------------------------------------------
function superDestaques(delay)
{
	var sd = ID("super_destaques");
	if(sd)
	{
		var items = sd.getElementsByTagName("A");
		if(items.length)
		{
			$(sd).fadeIn('slow', function()
			{		
				$(items[0]).fadeIn('slow');
				if(items.length>1)
				{
					var idx = 0;					
					setInterval(function()
					{
						$(items[idx]).fadeOut('slow', function()
						{
							idx++;
							if(idx>=items.length) idx = 0;
							$(items[idx]).fadeIn('slow'); 
						});
						
					}, delay*1000);					
				}				
			});
		} 
	}
}
