﻿//Este arquivo contém javascript que manipula objetos Ajax
//Copyright: Vericia Internet Ltda
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////// Função para balão////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Objetivo:Redesenhar o balão de recomendação quando ocorrer um Resize no Form. Esta função foi necessário, devido ao workaround da this dentro Window.
//Versão: 1.0
//Data: 14/08/2007
function OnResizeRedraw() {
	if (navigator.appName=="Netscape")
		winW = window.innerWidth-16;
	else if (navigator.appName.indexOf("Microsoft")!=-1)
		winW = document.body.offsetWidth-20;
	if (winW<1014) winW=1014;
		winMW = winW/2;
	document.getElementById('searchHelp').style.visibility="visible";	
	if (navigator.appName.indexOf("Microsoft")!=-1)
		document.getElementById('searchHelp').style.top = "375px";
	else		
		document.getElementById('searchHelp').style.top = "365px";
	document.getElementById('searchHelp').style.left = (winMW-460)+"px";    
};

//Objetivo:Imprimir o balão de recomendação
//Versão: 1.0
//Data: 06/08/2007
//Autor: luciano@vericia.com
function CBallon() {
    var idElement;
    this.Init = function(id) {        
        var self = this;
        self.idElement = id;
        settings = {tl: { radius: 20 },tr: { radius: 20 },bl: { radius: 20 },br: { radius: 20 },antiAlias: true,autoPad: true,validTags: ["div"] };
	    var myBoxObject = new curvyCorners(settings, "balloonHelpBox");
	    myBoxObject.applyCornersToAll();
	    self.Redraw();
	    
    };
    
    this.Redraw = function()  {
        var self;
        self = this;
	    if (navigator.appName=="Netscape")
  		    winW = window.innerWidth-16;
	    else if (navigator.appName.indexOf("Microsoft")!=-1)
		    winW = document.body.offsetWidth-20;
	    if (winW<1014) winW=1014;
	        winMW = winW/2;
        document.getElementById(self.idElement).style.visibility="visible";	
		if (navigator.appName.indexOf("Microsoft")!=-1)
			document.getElementById(self.idElement).style.top = "375px";
		else		
			document.getElementById(self.idElement).style.top = "365px";
		document.getElementById(self.idElement).style.left = (winMW-460)+"px";    
    };
    
    this.Remove =  function() {
        var self = this;
	    document.getElementById(self.idElement).style.visibility="hidden";    
    };
    
    this.Restore =  function() {
    	Redraw();
    };
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////// Função para Recomendação////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Objetivo:Realizar o mecanismo de recomendação do balão
//Versão: 1.0
//Data: 06/08/2007
//Autor: luciano@vericia.com
function CRecomendation() {
    //declaração de membros
    this.Parameters = '';
    this.idElementDestination = '';
    this.Url = "";
    this.LenRecom = 0;
    this.idElementPaginator = null;
    this.ActualPage = 0;
    this.RecomPerPage = 15;

   
    //declaração de métodos
    this.Init = function (Url, Parameters,idElementDestination,idElementPaginator, LenRecom) {
        var self = this;
        self.idElementDestination = idElementDestination;
        self.LenRecom = LenRecom;
        self.idElementPaginator = idElementPaginator;
        self.Parameters = Parameters;
        self.ActualPage = 1;
        self.Url=Url;
        self.DrawPaginator();        
    }
	
    this.DrawPaginator = function() {
        var intContador = 0;
        var strHtml = '';
        var self = this;
        var PagesQtde = 0;
		if(self.LenRecom > self.RecomPerPage) {		
			PagesQtde = Math.ceil(self.LenRecom/self.RecomPerPage);
			strHtml = "<p>";
			//Caso não tenha mais que 6 páginas de dados
			if (PagesQtde < 6) {		
				strHtml = '';
				for(intContador = 1; intContador <= PagesQtde; intContador ++) {                       
	                if(intContador != self.ActualPage)                 
	                    strHtml += '&nbsp;<a class="clsLinkQuadro" href="javascript:objRecom.GetPage(' + intContador +');">' + intContador + '</a>';
	                else
	                    strHtml += '&nbsp;<a class="clsLinkQuadroAtivo" href="#">' + intContador + '</a>';
	             }
			}
			//Caso para ter mais de 6 paginas de dados
	        else {
	            //É o primeiro elemento
				if (self.ActualPage == 1) {
					strHtml += '<a class="clsLinkQuadroAtivo" href="#">' + self.ActualPage + '</a>';
					strHtml += '<a class="clsLinkQuadro" href="javascript:objRecom.GetPage(2);">2</a>...';
					strHtml += '<a class="clsLinkQuadro" href="javascript:objRecom.GetPage(' + PagesQtde + ');">' + PagesQtde + '</a>';				
				}
				else {
					//É o ultimo elemento
					if (self.ActualPage == PagesQtde) {
						strHtml += '<a class="clsLinkQuadro" href="javascript:objRecom.GetPage(1);">1</a>...';
						strHtml += '<a class="clsLinkQuadro" href="javascript:objRecom.GetPage('  + (PagesQtde-1) + ');">' + (PagesQtde-1) + '</a>';
						strHtml += '<a class="clsLinkQuadroAtivo" href="#">' + PagesQtde + '</a>';	
					}
					else {
						//São elementos intercalados
						//São os 4 primeiros.
						if (self.ActualPage < 4) {					
							strHtml = '';
							for(intContador = 1;intContador <= (self.ActualPage+1);intContador++) {
								if(self.ActualPage != intContador) 
									strHtml += '<a class="clsLinkQuadro" href="javascript:objRecom.GetPage(' + intContador +');">' + intContador +'</a>';
								else
									strHtml += '<a class="clsLinkQuadroAtivo" href="#">' + intContador +'</a>';
							}
							strHtml += '...<a class="clsLinkQuadro" href="javascript:objRecom.GetPage(' + PagesQtde +');">' + PagesQtde + '</a>';	
						}
						else {
							if (self.ActualPage == (PagesQtde-1)) {
								strHtml += '<a class="clsLinkQuadro" href="javascript:objRecom.GetPage(1);">1</a>...';
								strHtml += '<a class="clsLinkQuadro" href="javascript:objRecom.GetPage(' + (self.ActualPage-1) +');">' + (self.ActualPage-1) +'</a>';
								strHtml += '<a class="clsLinkQuadroAtivo" href="#">' + self.ActualPage +'</a>';
								strHtml += '<a class="clsLinkQuadro" href="javascript:objRecom.GetPage(' + PagesQtde +');">' + PagesQtde + '</a>';
							}
							else {
								strHtml += '<a class="clsLinkQuadro" href="javascript:objRecom.GetPage(1);">1</a>...';
								strHtml += '<a class="clsLinkQuadro" href="javascript:objRecom.GetPage(' + (self.ActualPage-1) +');">' + (self.ActualPage-1) +'</a>';
								strHtml += '<a class="clsLinkQuadroAtivo" href="#">' + self.ActualPage +'</a>';
								strHtml += '<a class="clsLinkQuadro" href="javascript:objRecom.GetPage(' + (self.ActualPage+1) +');">' + (self.ActualPage+1) +'</a>';
								strHtml += '...<a class="clsLinkQuadro" href="javascript:objRecom.GetPage(' + PagesQtde +');">' + PagesQtde + '</a>';
							}	
						}					
					}
				}   
			}			
	        strHtml += '</p>';  
	        document.getElementById(self.idElementPaginator).innerHTML = strHtml;
		}
    };
    
    this.GetPage = function(intPagina) {  
        var self = this;          
        var objAjax = new Ajax();
        var hldTrataRetorno = function(valor) {
            if(valor.length > 0) {
                document.getElementById(self.idElementDestination).style.display = 'block'; 
                document.getElementById(self.idElementDestination).innerHTML = valor; 
                self.DrawPaginator();           
            }
            else {
                alert('Houve um problema na busca da próxima página ');
            }
            //Esconde o loader    
            document.getElementById('soap').style.visibility = 'hidden';     
                    
        }        
        var formData = '';
        formData += 'page=' + escape(intPagina);
        formData += '&' + self.Parameters;
        //Exibe o loader
        document.getElementById('soap').style.visibility = 'visible';         
        document.getElementById(self.idElementDestination).style.display = 'none'; 
        self.ActualPage = intPagina;    
        objAjax.doGet(self.Url + formData,hldTrataRetorno);
    };
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////// Função para Gestão da tela de salvar imóveis////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Objetivo: Excluir um item selecionando da Lista de imóveis salvos
//Versão 1.0
//Data: 27/08/2007
function ProperySavedDeleteItem(ProperyId, Url) {
	var objAjax = new Ajax();
	var hldTrataRetorno = function(valor) {
		var objResult = new CResult();
		objResult.Init(valor);
		if(objResult.ResultIsOK == true) {
			ShowStatus("Excluido com sucesso !");
		}
		else {
			alert('Houve um problema na exclusão do Imóvel ');
		}
		//Esconde o loader    
		document.getElementById('soap').style.visibility = 'hidden';    
		objSavedProperties.GetList(); //Chama a lista para ser atualizada				
	}        
	var formData = '';
	formData += 'propertid=' + escape(ProperyId);
	//Exibe o loader
	document.getElementById('soap').style.visibility = 'visible';         
	objAjax.doGet(Url + formData,hldTrataRetorno);	
}

//Objetivo: Realiza o efeito de fade_effect
//Versão 1.0
//Data: 27/08/2007
function fade_effect(el, start, end, dis, speed)
{
  var timer = 0;
  
  // check that speed is defined and valid
    if (typeof(speed) == 'undefined')
      speed = 700;
    else if (speed > 1000)
      speed = 1000;
    else if (speed < 10)
      speed = 10;
  
  speed = Math.round(speed / 100);
  
  // check that start defined
  if (typeof(start) == 'undefined')
  {
    if (end >= 50)
      start = 0;
    else
      start = 100;      
  }
  
  // check that end defined
  if (typeof(end) == 'undefined')
  {
    if (start >= 50)
      end = 0;
    else
      end = 100;      
  }

  // check that start valid
  if (start > 100)
    start = 100;
  else if (start < 0)
    start = 0;
      
  // check that end valid
  if (end > 100)
    end = 100;
  else if (end < 0)
    end = 0;
   
   // appear   
  if (end > start)
    var eff = 1;
  // fade
  else
  {
    var eff = -1;
    dis = 'none'
  }
    
  // do effect
  while (eff * start <= eff * end)
  {
    setTimeout('set_opac("' + el + '",' + start + ',"' + dis + '")', timer * speed);
    // Math.round used to fix js binary num representation of fraction issues + '")', timer);
    start = Math.round((start + eff) * 100) / 100 ; 
    timer++;
  }
  
}

//Objetivo: Realiza o efeito de opacidade
//Versão 1.0
//Data: 27/08/2007
function set_opac(el, opac, dis)
{
  // get element
  if (typeof(el) == 'undefined' || !el)
    return;
  else if (!el.style)
  {
    if (document.getElementById(el))
      el = document.getElementById(el);
    else
      return;
  }
  
  // element in ie needs to have specified width and/or height for opacity to work
  if (navigator.appName.indexOf("Microsoft") != -1 && !el.style.width && !el.style.height)
  {
      var dim = get_object_dimensions(el);
      el.style.height = dim.height;
      
      // unset width if it's 0
      if (dim.height === 0)
        el.style.height = '';
  }
  
  // check that opacity specified and valid
  if (typeof(opac) == 'undefined' || opac > 100)
    opac = 100;
  if (opac < 0)
    opac = 0;
  
  // set opacity
  el.style.opacity = opac / 100;
  el.style.MozOpacity = opac / 100;
  el.style.KhtmlOpacity = opac / 100;
  el.style.filter = 'alpha(opacity=' + opac + ')';    

  // if opac is at 0 or less, set the style.display
  if (opac === 0)
  {
    if (typeof(dis) == 'undefined' || (dis != 'none' && dis != 'block' && dis != 'inline'))
      el.style.display = '';
    else
      el.style.display = dis;
  }
}

//Objetivo: Remove a mensagem de status da tela
//Versão: 1.0
//Data: 28/08/2007
function kill_feedback(fast)
{
  if (typeof(fast)!='undefined' && fast==true)
    kill('idMessageBlockMsg');
  else
    fade_effect('idMessageBlockMsg');
}

//Objetivo: Remove um elemento da tela
//Versão: 1.0
//Data: 28/08/2007
function kill(id)
{
  var el = document.getElementById(id);
  if (el)
    el.parentNode.removeChild(el);
}

//Objetivo: Pega a posição de rolagem da tela
//Versão: 1.0
//Data: 28/08/2007
function get_scroll_top()
{
  var pos;
  if (window.innerHeight)
  {
    pos = window.pageYOffset;
  }
  else if (document.documentElement && document.documentElement.scrollTop)
  {
    pos = document.documentElement.scrollTop;
  }
  else if (document.body)
  {
    pos = document.body.scrollTop;
  }
  return pos;
}

//Objetivo: Exibir a mensagem de situação
//Versão: 1.0
//Data: 28/08/2007
function ShowStatus(strMessage) {
	var fb, is_error;
	fb = document.getElementById('idMessageBlock');
	if (!fb)		
		return;
	is_error = (typeof(error) != 'undefined' && error == 1);
	if (document.getElementById('idMessageBlockMsg'))
		kill('idMessageBlockMsg');
	var d = document.createElement('div');

	d.innerHTML = strMessage;
	d.id = 'idMessageBlockMsg';
	d.style.display = 'none';
	d.className = 'feedback_block';
	// if the user has scrolled, move it down 
	fb.style.top = (10+get_scroll_top())+'px';
	
	fb.appendChild(d);
	// var poof = new Effect.Appear('feedback_block_msg');
	fade_effect('idMessageBlockMsg', 0);
	if (!is_error)
		setTimeout('kill_feedback()', 2000);
}

//Objetivo: Excluir todos os items da Lista de imóveis salvos
//Versão 1.0
//Data: 27/08/2007
//Autor: luciano@vericia.com
function PropertySavedDeleteAll(Url) {
	var objAjax = new Ajax();
	var hldTrataRetorno = function(valor) {
		var objResult = new CResult();
		objResult.Init(valor);
		if(objResult.ResultIsOK == true) {
			alert("Excluido com sucesso !");
		}
		else {
			alert('Houve um problema na exclusão do Imóvel ');
		}
		//Esconde o loader    
		document.getElementById('soap').style.visibility = 'hidden';    
		objSavedProperties.GetList(); //Chama a lista para ser atualizada		
	}        
	var formData = '';
	//Exibe o loader
	document.getElementById('soap').style.visibility = 'visible';         
	objAjax.doGet(Url + formData,hldTrataRetorno);	
}

//Objetivo:Realiza o mecanismo de imóveis salvos
//Versão: 1.0
//Data: 27/08/2007
//Autor: luciano@vericia.com
function CDisplaySavedProperties() {
	
    //declaração de membros
    this.idElementDestination = '';
    this.UrlList = "";
    this.LenRecom = 0;
	this.UrlCount = "";
   
    //declaração de métodos
    this.Init = function (UrlList, UrlCount, idElementDestination,LenRecom) {
        var self = this;
        self.idElementDestination = idElementDestination;
        self.LenRecom = LenRecom;
        self.UrlList=UrlList;
		self.UrlCount = UrlCount;
		document.getElementById("idNumberHomes").innerText = "Imóveis salvos (" + LenRecom + ")";
    }
	
	this.GetCount = function() {
        var self = this;          
        var objAjax = new Ajax();
        var hldTrataRetorno = function(valor) {
			var objResult = new CResult();
			objResult.Init(valor);
			if(objResult.ResultIsOK) {
                document.getElementById(self.idElementDestination).style.display = 'block'; 
//                document.getElementById(self.idElementDestination).innerHTML = valor; 
				document.getElementById("idNumberHomes").innerText = "Imóveis salvos (" + objResult.Message + ")";				
            }
            else {
                alert('Houve um problema ao retornar a quantidade de elementos.');
            }
            //Esconde o loader    
            document.getElementById('soap').style.visibility = 'hidden';     

        }        
        var formData = '';
        //Exibe o loader
        document.getElementById('soap').style.visibility = 'visible';         
        document.getElementById(self.idElementDestination).style.display = 'none'; 
        objAjax.doGet(self.UrlCount + formData,hldTrataRetorno);
	
	}

	this.GetList = function() {  
        var self = this;          
        var objAjax = new Ajax();
        var hldTrataRetorno = function(valor) {
			if(valor.length > 0) {
                document.getElementById(self.idElementDestination).style.display = 'block'; 
                document.getElementById(self.idElementDestination).innerHTML = valor; 	
				self.GetCount();
			}
            //Esconde o loader    
            document.getElementById('soap').style.visibility = 'hidden';     
        }        
        var formData = '';
        //Exibe o loader
        document.getElementById('soap').style.visibility = 'visible';         
        document.getElementById(self.idElementDestination).style.display = 'none'; 
        objAjax.doGet(self.UrlList + formData,hldTrataRetorno);
    };
	
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////Trata resultados do Web Services////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Objetivo:Trata o resultado do Webservice
//Versão: 1.0
//Data: 27/08/2007
//Autor: luciano@vericia.com
function CResult() {
	this.Message = '';
	this.ResultIsOK = false;
	
	this.Init = function(strWsResult) {
		var self = this;
		var aResultMessage = strWsResult.split("|");
		var aResult = aResultMessage[0].split(":")
		var aMessage = aResultMessage[1].split(":");
		
		if(aResult[1] == "OK") 
			self.ResultIsOK = true;
		else
			self.ResultIsOK = false;
		this.Message = aMessage[1];		
	}	
}
