﻿var ajaxObjects = new Array();
var ajaxObjectsDelayProtect = new Array();

function trim(str) {
    return str.replace(/^\s*|\s*$/g, "");
}

var is = new function() {
    this.VER = navigator.appVersion
    this.AGENT = navigator.userAgent
    this.DOM = document.getElementById ? 1 : 0
    this.IE = (document.all && !this.DOM) ? 1 : 0;
    this.MAC = this.AGENT.indexOf("Mac") > -1
    this.NS6 = document.getElementById && !document.all ? 1 : 0
    this.NS4 = (document.layers && !this.DOM) ? 1 : 0;
    this.OPERA = this.AGENT.indexOf('Opera') > -1
    return this
}

function getElement(id) {
    if (is.DOM) return document.getElementById(id)
    else
        if (is.IE) return eval("document.all." + id)
    else
        if (is.NS) return eval("document." + id)
}

function addHomepage(id)
{
    if(document.all)
    {
        var x = document.getElementById(id);
	    x.style.behavior='url(#default#homepage)';
	    x.setHomePage("http://" + document.domain);
    } 
    else if (window.sidebar)
    {
        alert("Arrasta o link para o ícone Home Page do Firefox para fazeres desta página http://" + document.domain + " a sua homepage");
    }

}

function AddToFavorites()
{
    var title = document.title;
    var url = "http://" + document.domain;
    if (window.sidebar) // Firefox
	    window.sidebar.addPanel(title, url, '');
    else if(window.opera && window.print) // Opera
    {
	    var elem = document.createElement('a');
	    elem.setAttribute('href',url);
	    elem.setAttribute('title',title);
	    elem.setAttribute('rel','sidebar'); // required to work in opera 7+
	    elem.click();
    } 
    else if(document.all) // IE
	    window.external.AddFavorite(url, title);
}



function add_bookmark(url, imovel) {
    var browsName = navigator.appName;
    if (browsName == "Microsoft Internet Explorer") {
        window.external.AddFavorite(url, imovel);
    } else if (browsName == "Netscape") {
        alert("\nPara adicionar esta página aos seus Favoritos pressione CTRL+D");
    }
}

function toggle_visibility(id) {
	
	var e = document.getElementById(id);
	if(e.style.display == 'block')
	  e.style.display = 'none';
   else
	  e.style.display = 'block';
}

function CheckIsIE() {
    if (navigator.appName.toUpperCase() == 'MICROSOFT INTERNET EXPLORER') { return true; }
    else { return false; }
}

function email_valido(email) {
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if (reg.test(email) == false) {
        return false;
    } else {
        return true;
    }
}

function regista_newsletter() {
    var msg = "";
    if (!email_valido(document.getElementById('email2').value))
        msg += 'Campo \'E-mail\' é obrigatorio. Preencha-o correctamente.\n';

    //mostra msg de erro caso existam
    if (msg.length != 0) {
        alert("Erro(s)\n" + msg);
        return (false);
    } else {
        //senao envia o formulário
        return (true);
    }
}

function valida_form_amigo() {
    var msg = "";

    if (document.getElementById('recomenda_nome').value.length < 4)
        msg += 'Campo \'O seu Nome\' é obrigatorio. (minimo 4 caracteres.)\n';

    if (document.getElementById('recomenda_amigo_nome').value.length < 4)
        msg += 'Campo \'Nome do Amigo\' é obrigatorio. (minimo 4 caracteres.)\n';


    if (!email_valido(document.getElementById('recomenda_amigo_email').value))
        msg += 'Campo \'E-mail do Amigo\' é obrigatorio. Preencha-o correctamente.\n';

    //mostra msg de erro caso existam
    if (msg.length != 0) {
        alert("Erro(s)\n" + msg);
        return (false);
    } else {
        //senao envia o formulário
        return (true);
    }
}

function valida_form_info() {
    var msg = "";

    if (document.getElementById('info_nome').value.length < 4)
        msg += 'Campo \'O seu Nome\' é obrigatorio. (minimo 4 caracteres.)\n';

    if (document.getElementById('info_telef').value.length < 9)
        msg += 'Campo \'Nº Telefone\' é obrigatorio. (minimo 9 caracteres.)\n';

    //mostra msg de erro caso existam
    if (msg.length != 0) {
        alert("Erro(s)\n" + msg);
        return (false);
    } else {
        //senao envia o formulário
        return (true);
    }
}
// ************ ini end *****************
function activa_tab(obj) {
    try {
        if (document.getElementById) {
            if (document.getElementById('tab1').className == "on") document.getElementById('tab1').className = "off";
            if (document.getElementById('tab2').className == "on") document.getElementById('tab2').className = "off";
            if (document.getElementById('tab3').className == "on") document.getElementById('tab3').className = "off";
            if (document.getElementById('tab4').className == "on") document.getElementById('tab4').className = "off";
            if (document.getElementById('tab5').className == "on") document.getElementById('tab5').className = "off";
            if (document.getElementById('tab6').className == "on") document.getElementById('tab6').className = "off";
            document.getElementById('showtab1').className = "hide_on";
            document.getElementById('showtab2').className = "hide_on";
            document.getElementById('showtab3').className = "hide_on";
            document.getElementById('showtab4').className = "hide_on";
            document.getElementById('showtab5').className = "hide_on";
            document.getElementById('showtab6').className = "hide_on";
            document.getElementById(obj).className = "on";
            document.getElementById('show' + obj).className = "hide_off";
        }
    }
    catch (e) {
        //nada
    }
}

function activa_tab_noticias(obj) {
    try {
        if (document.getElementById) {

            document.getElementById('default_block_noticias_tab1').className = "default_block_noticias_tab";
            document.getElementById('default_block_noticias_tab2').className = "default_block_noticias_tab";

            document.getElementById('show_default_block_noticias_tab1').className = "hide_on";
            document.getElementById('show_default_block_noticias_tab2').className = "hide_on";

            document.getElementById(obj).className = "default_block_noticias_tab_sel";
            document.getElementById('show_' + obj).className = "hide_off";
        }
    }
    catch (e) {
        //nada
    }
}

function activa_tab_vinhos(obj) {
    try {
        if (document.getElementById) {

            document.getElementById('default_block_noticias_tab1').className = "default_block_vinhos_tab";
            document.getElementById('default_block_noticias_tab2').className = "default_block_vinhos_tab";

            document.getElementById('show_default_block_noticias_tab1').className = "hide_on";
            document.getElementById('show_default_block_noticias_tab2').className = "hide_on";

            document.getElementById(obj).className = "default_block_vinhos_tab_sel";
            document.getElementById('show_' + obj).className = "hide_off";
        }
    }
    catch (e) {
        //nada
    }
}
// ************ tabs end *****************


// ************ mostra_esconde end *****************
function mostra_esconde(idx) {
    var obj = document.getElementById(idx)
    //alert(obj.className);
    if (obj.className == 'hide_off') {
        obj.className = 'hide_on';
    } else {
        obj.className = 'hide_off';
    }
}

function set_style(idx, stl) {
    var obj = document.getElementById(idx)
    //alert(obj.className);
    obj.className = stl;
}

function showhide2(id) {
    obj = getElement(id);
    viz = obj.style.display;
    if (viz == 'block') {
        obj.style.display = "none";
    } else {
        obj.style.display = "block";
    }
}

function ShowHide(id, visibility) {
    obj = document.getElementsByTagName("div");
    //visibility =  obj[id].style.visibility;
    if (visibility == 'visible') {
        obj[id].style.display = 'block';
    } else {
        obj[id].style.display = 'none';
    }
}

// ************ mostra_esconde end *****************

function Imprimir() {
    var a = window.open('', '', 'scrollbars=yes,width=720,height=500');
    a.document.open("text/html");
    a.document.write('<html>\n<head>\n<link rel="stylesheet" href="/css/main.css" media="all" type="text/css" />\n<style>\n.noprint{display:none}\n<\/style>\n</head>\n<body style="background-image:none;background-color:#FFFFFF;">\n');
    a.document.write('<table align="center" width="700" border="0" cellpadding="10" cellspacing="0">\n<tr>\n<td align="left">\n<img align="absmiddle" src="/images/banner_impressao.jpg" border="0" alt="" /><br/><br/>');
    a.document.write('<tr>\n<td>\n');
    a.document.write(document.getElementById('print').innerHTML);
    a.document.write('\n<\/td>\n<\/tr>\n');
    a.document.write('<\/table>\n');
    a.document.write('<\/body>\n<\/html>');
    a.document.close();
    a.print();
}

//---------------------------------------------------------------------------------------------------------------------
//GSP Converter

function DMS_to_Degrees(d, m, s, dir) {
    var deg = parseFloat(Math.abs(d)) + parseFloat(Math.abs(m) / 60) + parseFloat(Math.abs(s) / 3600);
    if (dir == 'W' || dir == 'S') { deg = parseFloat(-1 * deg); }
    if (d == '' && m == '' && s == '') { deg = ''; }
    return comma2point(deg);
}

function Degrees_to_DMM(deg, type, spacer, minutemark) {
    if (!deg.toString().match(/[0-9]/)) { return ''; }
    if (!spacer) { spacer = ''; }
    if (!minutemark) { minutemark = ''; }
    if (type == 'lat') {
        if (parseFloat(deg) < 0) { var dir = 'S'; } else { var dir = 'N'; }
    } else {
        if (parseFloat(deg) < 0) { var dir = 'W'; } else { var dir = 'E'; }
    }
    var d = Math.floor(Math.abs(parseFloat(deg)));
    var m = 60 * (Math.abs(parseFloat(deg)) - parseFloat(d))
    m = Math.round(1000000 * m) / 1000000;
    if (type == 'lon') {
        if (d < 10) { d = '00' + d; } else if (d < 100) { d = '0' + d; }
    } else {
        if (d < 10) { d = '0' + d; }
    }
    if (parseFloat(m) == Math.floor(parseFloat(m))) { m = m + '.0'; }
    return dir + spacer + d + String.fromCharCode(176) + spacer + comma2point(m) + minutemark;
}

function Degrees_to_DMS(deg, type, spacer) {
    if (!deg.toString().match(/[0-9]/)) { return ''; }
    if (!spacer) { spacer = ''; }
    if (type == 'lat') {
        if (parseFloat(deg) < 0) { var dir = 'S'; } else { var dir = 'N'; }
    } else {
        if (parseFloat(deg) < 0) { var dir = 'W'; } else { var dir = 'E'; }
    }
    var d = Math.floor(Math.abs(parseFloat(deg)));
    var mmm = 60 * (Math.abs(parseFloat(deg)) - parseFloat(d))
    mmm = Math.round(1000000 * mmm) / 1000000;
    var m = Math.floor(parseFloat(mmm));
    var s = 60 * (parseFloat(mmm) - parseFloat(m))
    s = Math.round(1000 * s) / 1000;
    return dir + spacer + d + String.fromCharCode(176) + spacer + m + '\'' + spacer + comma2point(s) + '"';
}

function deg2rad(deg) {
    return (parseFloat(comma2point(deg)) * 3.14159265358979 / 180);
}
function rad2deg(radians) {
    return (Math.round(10000000 * parseFloat(radians) * 180 / 3.14159265358979) / 10000000);
}
function comma2point(number) {
    number = number + ''; // force number into a string context
    return (number.replace(/,/g, '.'));
}

function parseCoordinate(coordinate, type, format, spaced) {
    coordinate = coordinate.toString();
    var neg = 0; if (coordinate.match(/(^-|[WS])/i)) { neg = 1; }
    if (coordinate.match(/[EW]/i) && !type) { type = 'lon'; }
    if (coordinate.match(/[NS]/i) && !type) { type = 'lat'; }
    coordinate = coordinate.replace(/[NESW\-]/gi, ' ');
    if (!coordinate.match(/[0-9]/i)) {
        return '';
    }
    parts = coordinate.match(/([0-9\.\-]+)[^0-9\.]*([0-9\.]+)?[^0-9\.]*([0-9\.]+)?/);
    if (!parts || parts[1] == null) {
        return '';
    } else {
        n = parseFloat(parts[1]);
        if (parts[2]) { n = n + parseFloat(parts[2]) / 60; }
        if (parts[3]) { n = n + parseFloat(parts[3]) / 3600; }
        if (neg && n >= 0) { n = 0 - n; }
        if (format == 'dmm') {
            if (spaced) {
                n = Degrees_to_DMM(n, type, ' ');
            } else {
                n = Degrees_to_DMM(n, type);
            }
        } else if (format == 'dms') {
            if (spaced) {
                n = Degrees_to_DMS(n, type, ' ');
            } else {
                n = Degrees_to_DMS(n, type, '');
            }
        } else {
            n = Math.round(10000000 * n) / 10000000;
            if (n == Math.floor(n)) { n = n + '.0'; }
        }
        return comma2point(n);
    }
}

// lat - Gmap Lat coordinate
// lng - Gmap Lng coordinate
// space - True/False (space between values)
function Convert_Coordinates(lat, lng, space) {
    var lat = lat;
    var lon = lng;
    var spaced = space;


    //DDD - Decimal Degrees
    //DMM - Degrees Minutes  (GPS)
    //DMS - Degrees Minutes Seconds

    var coordinates_lat_ddd;
    var coordinates_lat_dmm;
    var coordinates_lat_dms;
    var coordinates_lng_ddd;
    var coordinates_lng_dmm;
    var coordinates_lng_dms;
    var coordinates_pair_ddd;
    var coordinates_pair_dmm;
    var coordinates_pair_dms;


    coordinates_lat_ddd = parseCoordinate(lat, 'lat', 'ddd', spaced);
    coordinates_lat_dmm = parseCoordinate(lat, 'lat', 'dmm', spaced);
    coordinates_lat_dms = parseCoordinate(lat, 'lat', 'dms', spaced);

    coordinates_lon_ddd = parseCoordinate(lon, 'lon', 'ddd', spaced);
    coordinates_lon_dmm = parseCoordinate(lon, 'lon', 'dmm', spaced);
    coordinates_lon_dms = parseCoordinate(lon, 'lon', 'dms', spaced);

    coordinates_pair_ddd = coordinates_lat_ddd + ', ' + coordinates_lon_ddd;
    coordinates_pair_dmm = coordinates_lat_dmm + ', ' + coordinates_lon_dmm;
    coordinates_pair_dms = coordinates_lat_dms + ', ' + coordinates_lon_dms;

    //alert("Coordinates: DDD = "+coordinates_pair_ddd+" / DMM= "+coordinates_pair_dmm+" / DMS="+coordinates_pair_dms);
    document.write(coordinates_pair_dms);
}

//---------------------------------------------------------------------------------------------------------------------

function divide_string(param) {
    var newStr = param.substring(1, param.length - 1);
    var mytool_array = newStr.split(" ");
    Convert_Coordinates(mytool_array[0], mytool_array[1], true);
}

function change_pesq_tab(tab,tipo) {
    try{getElement("pesq_tab1").className = "pesq_tab"}catch(e) {};
    try{getElement("pesq_tab2").className = "pesq_tab"}catch(e) {};
    try{getElement("pesq_tab3").className = "pesq_tab"}catch(e) {};
    try{getElement("pesq_tab4").className = "pesq_tab"}catch(e) {};
    try{getElement("pesq_tab5").className = "pesq_tab"}catch(e) {};
    tab.className = "pesq_tab_sel";
    getElement("ctl00_input_pesquisa_topo_tipo").value = tipo;
}


function change_pesq_tab_header_tv(tipo) {
    try{getElement("pesq_tab_header_tv1").className = "pesq_tab"}catch(e) {};
    try{getElement("pesq_tab_header_tv2").className = "pesq_tab"}catch(e) {};
    try{getElement("pesq_tab_header_tv3").className = "pesq_tab"}catch(e) {};
    try{getElement("pesq_tab_header_tv4").className = "pesq_tab"}catch(e) {};
    try{getElement("pesq_tab_header_tv5").className = "pesq_tab"}catch(e) {};
    try{getElement("pesq_tab_tv1").className = "pesq_tab"}catch(e) {};
    try{getElement("pesq_tab_tv2").className = "pesq_tab"}catch(e) {};
    try{getElement("pesq_tab_tv3").className = "pesq_tab"}catch(e) {};
    try{getElement("pesq_tab_tv4").className = "pesq_tab"}catch(e) {};
    try{getElement("pesq_tab_tv5").className = "pesq_tab"}catch(e) {};
    getElement("pesq_tab_tv"+tipo).className = "pesq_tab_sel";
    getElement("pesq_tab_header_tv"+tipo).className = "pesq_tab_sel";
    getElement("ctl00_input_pesquisa_tv_topo_tipo").value = tipo;
    getElement("ctl00_input_pesquisa_tv_fundo_tipo").value = tipo;
}

//***************************************

function changeSize(obj, value) {
    try {
        elements = obj.split(",");
        for (i = 0; i < elements.length; i++)
            document.getElementById(elements[i]).style.fontSize = (parseInt(document.getElementById(elements[i]).style.fontSize) + value) + 'px';
    } catch (e) {
        alert(e.description);
    }
}

function mostrar_sn() {
    document.getElementById('social_networks').style.display = 'block';
    pos = findPos(document.getElementById("link_social_networks1"));
    pos_x = pos[0];
    document.getElementById("social_networks").style.left = pos_x - 79 + 'px';
    pos_y = pos[1];
    document.getElementById("social_networks").style.top = pos_y - 191 + 'px';
}

function mostrar_sn2(obj)
{
    document.getElementById('social_networks').style.display = 'block';
    pos = findPos(obj);
    pos_x = pos[0];
    document.getElementById('social_networks').style.left =  pos_x+'px';
    pos_y = pos[1];
    document.getElementById('social_networks').style.top = pos_y-30+'px'
}


function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
    }
    return [curleft, curtop];
}

function esconder_sn() {
    try{getElement('social_networks').style.display = 'none';}catch(err) {};
}

function mostrar_pedirinfo(obj,obj1)
{
	if(obj1=='pedir_info')
	{
	    try{esconder_pedirinfo('recomendar_imovel');}catch(err) {};
		try{esconder_pedirinfo('social_networks');}catch(err) {};
	}
	if(obj1=='recomendar_imovel')
	{
		try{esconder_pedirinfo('pedir_info');}catch(err) {};
		try{esconder_pedirinfo('social_networks');}catch(err) {};
	}
    document.getElementById(obj1).style.display = 'block';
    pos = findPos(obj);
    pos_x = pos[0]-50;
    document.getElementById(obj1).style.left =  pos_x+'px';
    pos_y = pos[1];
    pos_y = pos_y+20;
    document.getElementById(obj1).style.top = pos_y+'px';
}

function esconder_pedirinfo(obj1) {
    //getElement(obj1).style.display = 'none';
    try{parent.document.getElementById(obj1).style.display='none';}catch(err) {};
}

function mostrar_social(obj,obj1)
{
	if(obj1=='social_networks')
	{
		try{esconder_pedirinfo('pedir_info');}catch(err) {};
		try{esconder_pedirinfo('recomendar_imovel');}catch(err) {};
	}
    document.getElementById(obj1).style.display = 'block';
    pos = findPos(obj);
    pos_x = pos[0]-220;
    document.getElementById(obj1).style.left =  pos_x+'px';
    pos_y = pos[1];
    pos_y = pos_y+20;
    document.getElementById(obj1).style.top = pos_y+'px';
}

/*----------------Ajax getContent -------------------*/
function getContent(url,divobj,fnc_completo,params){
	try {
	pageTracker._trackPageview(url);
	} catch(err) {}
	var ajaxIndex = ajaxObjects.length;
	ajaxObjectsDelayProtect[url] = ajaxIndex;
	ajaxObjects[ajaxIndex] = new sack();
	ajaxObjects[ajaxIndex].requestFile = url;
	ajaxObjects[ajaxIndex].encodeURIString = false;
	ajaxObjects[ajaxIndex].onCompletion = function() {showContent(divobj,ajaxIndex,url,fnc_completo);};
	ajaxObjects[ajaxIndex].runAJAX(params);
	showWaitMessage(divobj);
} 

function showWaitMessage(divobj){
	divobj.innerHTML = '<img src="/images/ajax-loader.gif" alt="A carregar dados..." />';
}

function showContent(divobj,index,url,fnc_completo){
	if (ajaxObjectsDelayProtect[url] == index){divobj.innerHTML = ajaxObjects[index].response;	}
	if (fnc_completo)eval(fnc_completo);
}


/* So inteiros */
function intOnly(i) {
    if (i.value.length > 0) {
        i.value = i.value.replace(/[^\d]+/g, '');
    }
}

/* act combos tipologia */
function act_tipologia(tpmin, tpmax, muda) {
    if ((tpmin.selectedIndex > tpmax.selectedIndex) && (tpmax.selectedIndex != 0))
        if (muda == 1)
        tpmax.options[tpmin.selectedIndex].selected = true;
    else
        tpmin.options[tpmax.selectedIndex].selected = true;
}