function lmapsearch(form_obj) {
        var params = [];
        params.push ("u=" + escape("http://mapes.sapo.pt"));
        params.push( "id=" + form_obj.id);
        params.push( "q=" + escape(keywords) );
        params.push( "ts=" +  s_timestamp );
        params.push( "sid=" + query_id );
        params.push( "rid=" + "0");
        params.push( "b=" + barra );
        params.push( "form_query=" + escape(form_obj.ts.value));
        new Image().src = "/clk?" + params.join("&");
}

function lsesearch(form_obj) {
    var params = [];
    params.push("u=" + escape("http://pesquisa.sapo." + form_obj.location.value +"/?q="+form_obj.q.value + "&location=" + form_obj.location.value + "&st=" + form_obj.st.value));
    params.push("q=" + escape(keywords));
    params.push("id=" + form_obj.id);
    params.push("form_query=" + form_obj.q.value);
    new Image().src = "/clk?" + params.join("&");
}

function isArray(obj) {
	return ( (obj.constructor.toString().indexOf("Array") == -1) ? false : true );
}

/* Change the display property */
function changeDisplay(o,display){
	var arr = ( o.length==1 && isArray(o[0]) )?arr = o[0]:o;
	for(var i=0; i < arr.length; i++) {
		var obj = $(arr[i]);
		if( obj!==null ){ obj.style.display=display; }
	}
}

function abrir(){
	changeDisplay( arguments , 'block' );
}

function fadeAbrir(id){
	abrir(id);
	setOpacity($(id),0);
	fadeInObj(id, null, null);
}

function abrir_inline(){
	changeDisplay( arguments , 'inline' );
}

function fechar(){
	changeDisplay( arguments , 'none' );
}

function closeDialog(o){
	o.parentNode.style.display='none';
}



/* opens the phone number from PAi */
var lastNmr;
function tlfPai( nome, tlf, paiData, fax){
	$('n_nome_empresa').update( nome );
	$('n_telefone').update( tlf );

	abrir('telefone');
	fadeInObj('telefone', null, null);
    if (lastNmr != tlf) {
        beacon(paiData, { 'linktype': (fax ? 'showfaxnumber' : 'showphonenumber') })
    }
    if (location_dns == 'pt') {
        var action = fax ? 'fax show' : 'telephone show';
        preMultiTrack(paiData, action, 'potential contact','');
    }
    lastNmr = tlf;
	return false;
}

var fade_speed      = 1;
var fade_quantidade = 10;
var timer           = new Array();


/* get opacity value */
function getOpacity(obj){
 	return parseFloat( $(obj).getStyle('opacity') )*100;
}

/* set the opacity value */
function setOpacity(obj,valor){
	return $(obj).setOpacity(valor/100);
}


/* fade out of an object */
function fadeOutObj(id, funcIni, funcFim){
	var objecto = $(id);
	window.clearTimeout(timer[id]);
	if(!objecto) { return;}
	if ( getOpacity(objecto) - fade_quantidade > 0 ){
		if( getOpacity(objecto)==100 && funcIni!=null){ funcIni(); }
		setOpacity(objecto, getOpacity(objecto) - fade_quantidade );
		timer[id] = window.setTimeout("fadeOutObj('" + id + "', " + funcIni + ", " + funcFim + ")", fade_speed);
	}
	else {
		setOpacity(objecto, 0 );
		if(funcFim!=null){ funcFim(); }
	}
}

/* fade in of an object */
function fadeInObj(id, funcIni, funcFim){
	var objecto = $(id);
	window.clearTimeout(timer[id]);
	if(!objecto){ return;}
	if ( getOpacity(objecto) + fade_quantidade < 100 ){
		if( getOpacity(objecto)==0 && funcIni!=null){ funcIni(); }
		setOpacity(objecto, getOpacity(objecto) + fade_quantidade );
		timer[id] = window.setTimeout("fadeInObj('"+id+"', "+funcIni+", "+funcFim+")", fade_speed);
	}
	else {
		setOpacity(objecto, 100 );
		if(funcFim!=null){ funcFim(); }
	}
}

/* the Result "class", containing info about a given result */
/* to pass objects */
function Result(){
	this.resultObj = null;

	this.setResult = function( r ){
		this.resultObj = r;
	};

	this.getLink  = function(){
		return (this.resultObj.getElementsByTagName('h3')[0]).getElementsByTagName('a')[0];
	};

	this.getTitle = function(){
		return (this.getLink()).innerHTML;
	};
    this.getHostname = function() {
        return (this.getLink().toString().split('/')[2]);
    };
    this.getVid = function(){
        return (this.resultObj.getElementsByTagName('span')[0].innerHTML);
    };


}

var res = new Result();

/* function that takes care of clicks inside of a result */
function resultClick(e){

	var tgt  = Event.element(e);
    var aNode = null;;
	var posX = Event.pointerX(e);
	var posY = Event.pointerY(e);
    if (tgt.nodeName == 'A')  {
        aNode = tgt;
    } else { 
        if (tgt.parentNode.nodeName == 'A') {
            aNode = tgt.parentNode;
        }
    }
    if (aNode != null) {
        if ((aNode.href == location.toString() ) || (aNode.href == location.toString() + '#')) {
            Event.stop(e);
        }
    }
	/* Clicked result */
	var resultado = tgt;
	if ( tgt == this ){ return;}
	while ( this != resultado.parentNode ){
		resultado = resultado.parentNode;
		i++;
	}

	res.setResult(resultado);

	/* If clicked on the tools */
	if ((tgt.parentNode.parentNode.className=='tools') || (tgt.parentNode.parentNode.className == 'video')){
		var dialog = '';
		var link_to_string = (res.getHostname()).toString();
		link_to_string = link_to_string.replace(/http:\/\/(www\.)*/i, '');
		if( link_to_string.length > 50 ){
			link_to_string = link_to_string.substr(0,50) + '...';
		}

		fechar(arr_dialog);
		switch( tgt.parentNode.className ){
			/* Show preview of the website */
			case 'preview':
					dialog = 'thumb_dialog';
                    thumb=new SAPO.Widget.Thumbs({
                                'type':'thumbnail',
                                'url': tgt.parentNode.parentNode.parentNode.getElementsByTagName('A').item(0).href,
                                'size':'6',
                                'divid':dialog + '_scr'
                        });
				break;
            case 'v_video':
                    dialog = 'thumb_dialog';
                    document.getElementById('thumb_dialog_scr').innerHTML = res.getVid();
                break;
			case 'more_actions':
					dialog = 'tools';

					var strong = ($(dialog)).getElementsByTagName('strong');
					for(var i = 0; i<strong.length; i++ ){
						$( strong[i] ).update( link_to_string );
					}
					var puny_link = document.getElementById('puny_link');
					puny_link.href = 'http://puny.sapo.pt/punify?url=' + escape(res.getLink());
                    document.getElementById('l_new_w').href = res.getLink();
                    document.getElementById('l_sapolinks').href='http://links.sapo.pt/post?v=3&url='+encodeURIComponent(res.getLink())+'&title='+encodeURIComponent(res.getTitle());
				break;
			default: break;
		}
		if( dialog != '' ){
			fadeAbrir(dialog);
			($(dialog)).style.top = posY-20 + 'px';
			($(dialog)).style.left = posX+15 + 'px';

			var titulo_dialog  = ($(dialog)).getElementsByTagName('h6')[0];
			titulo_dialog.innerHTML = '<a href="' + res.getLink() + '" title="' + res.getTitle() + '">' + link_to_string + '<\/a>';
			return false;
		}
	}
	/* Click on "ver mais" from PAi || PBi */
	else if( tgt.className == 'p_mapa' ){
	}
	/* Click on "Feed rss" from Blogs || Noticias */
	else if( tgt.parentNode.className == 'rssFeed' ){
		fechar(arr_dialog);
		fadeAbrir('feed_dialog');
		($('feed_dialog')).style.top  = posY -10 + 'px';
		($('feed_dialog')).style.left = posX -10 + 'px';
        load_rss_data(res.getHostname(),res.getHostname());
		return false;
	}
	/* Everything else closes the dialogs */
	else{
         
		fechar(arr_dialog);
	}
}

/* opens a specific tool from the tools side bar */
function abrirFerramenta(e){
	var tgt  = Event.element(e);
	//Event.stop(e);

	var dialog = null;
    var myswitch = tgt.className;
    if (tgt.className == '') {
        myswitch = tgt.parentNode.className;
    }
	switch( myswitch ){
		case 't_email':
				dialog = 'sendmail_dialog';
				$('sendmail_link'    ).value = res.getLink();
				$('sendmail_keywords').value = keywords;
				$('sendmail_title'   ).value = res.getTitle();
			break;
		case 't_search':
				dialog = 'sitesearch_dialog';
				$('as_sitesearch'    ).value = res.getHostname();
				$('ssq'              ).value = keywords;
			break;
		case 't_pdf':
				dialog = 'pdf_dialog';
                thumb=new SAPO.Widget.Thumbs({
                                'type':'pdf',
                                'url': res.getLink().toString(),
                                'mail':true,
                                'divid':'pdf_dialog_container'
                                  });

			break;
		case 'close': break;
        case 't_new_w': 
            break;
		default:
				if( tgt.href != undefined ){
					top.location.href = tgt.href;
				}
				return false;
			break;
	}

	fechar(arr_dialog);
	if( dialog ){
		fadeAbrir(dialog);

		var link_to_string = (res.getLink()).toString();
		link_to_string = link_to_string.replace(/http:\/\/(www\.)*/i, '');
		if( link_to_string.length > 50 ){
			link_to_string = link_to_string.substr(0,50) + '...';
		}

		var titulo_dialog = ($(dialog)).getElementsByTagName('h6')[0];
		$(titulo_dialog).update( '<a href="' + res.getLink() + '" title="' + res.getTitle() + '">' + link_to_string + '<\/a>' );
		($(dialog)).style.top = this.style.top;
	}

	return false;
}



var arr_dialog = new Array('feed_dialog','thumb_dialog', 'sendmail_dialog', 'sitesearch_dialog', 'pdf_dialog', 'tools','more_services','detalhes_pai','sendVcard');

/* PAI MOSTRAR DETALHES */
function closeDetails(){
	$('fotoPai').getElementsByTagName('img')[0].src='http:\/\/sl.pt\/rp\/imgs\/2006\/img\/pai\/0.gif';
	fechar('d_logo','d_acti','d_slogan','d_paginas','paiVerPdf','paiVerMapa','paiVerFoto','paiVerInfo','mapaPai','fotoPai','infoPai','sendVcard','detalhes_pai','p_more_info','more_services');
}

function resizePaiImg(obj,sx,sy){
	if( obj.width > sx || obj.height > sy ){
		r = obj.width / obj.height;
		if( r > 1 ){
			obj.width = sx;
			obj.height = sy / r;
		}
		else{
			obj.width = sx * r;
			obj.height = sy;
		}
	}
}

function sendVcard () {
	$('vCardNumber').disabled = true;
	$(  'vCardSend').disabled	= true;
	beacon(curPaiRes, {'linktype': 'vcardsms', 'linkplace': 'resulttab.text'});

	vd = $('vCardData').innerHTML;

	var uri = '/paiRequest/vCard?to='+ $('vCardNumber').value +	buildVcard(curPaiRes);
    new Ajax.Request (uri, {
        method : 'get', 
        onSuccess : function(transport) {
            $('vCardMsg').update(transport.responseText +'<br/>');
            if (transport.responseText != 'SMS enviado.')  { 
                $('vCardNumber').disabled = false; 
                $('vCardSend').disabled = false;
                if (transport.responseText == 'Erro no envio.') {
                    preMultiTrack(curPaiRes,'sms form not send','user action','');
                } else { 
                    preMultiTrack(curPaiRes,'sms form send errors','user action','');
                }
            } else {
                preMultiTrack(curPaiRes,'sms form send','potential contact', '');
            
            } 

        }
   } );
}

function verMapa(){
	beacon(curPaiRes, {'linktype': 'detailmap', 'linkplace': 'resulttab.text'});
    preMultiTrack(curPaiRes, 'map','potential contact','');
	fechar('fotoPai','infoPai');
	abrir('p_more_info','mapaPai');
	openPaiMap();
}

function verInfo(){
	beacon(curPaiRes, {'linktype': 'detailtext', 'linkplace': 'resulttab.text'});
    preMultiTrack(curPaiRes, 'information','user action','');
	fechar('fotoPai','mapaPai');
	abrir('p_more_info','infoPai');
}

function verFoto(){
	beacon(curPaiRes, {'linktype': 'detailphoto', 'linkplace': 'resulttab.text'});
    preMultiTrack(curPaiRes, 'select photo', 'user action', curPaiRes.logo);
	if( $('fotoPai').getAttribute('foto')!='' )	{
		$('fotoPai').update( '<img src="' + $('fotoPai').getAttribute('foto') + '" alt="Fotografia" onload="resizePaiImg( this, 300, 293 )"/>' );
	}
	fechar('infoPai','mapaPai');
	abrir('p_more_info','fotoPai');
}

var paiMapObj = '';
var paiMapMarker ='';
var paiUn = '';

function resultadoPai(e,paiRes) {

    preMultiTrack(paiRes,'business name','user action','');
	var posY = Event.pointerY(e);
    var posX = Event.pointerX(e);
	/* Get the Details box */
	var objCSS      = $('detalhes_pai').style;
	objCSS.position = 'absolute';
    if ((barra == 'resumo' ) || (barra =='directorio')) {
        var w_width = document.viewport.getWidth();
        var position_paibox = $('paibox_right').offsetLeft;
        if (position_paibox == '') {
            position_paibox = w_width - 311;
        }
        var right = w_width - position_paibox;
        objCSS.right = right + 'px';
    } else {
        objCSS.left = '10px';
    }
	objCSS.top      = (posY-35) + 'px';

	/* Find the INDEX of this result */
	var paiID = 0;
	for( var paiID = 0; paiID < paiAddresses.length; paiID++ ){
		if( paiRes == paiAddresses[paiID] ){
			break;
		}
	}

	paiUn     = paiRes;
	curPaiRes = paiRes;

	beacon(curPaiRes, {'linktype': 'detail', 'linkplace': 'resulttab.text'});

	/* Set vCard */
	$('vCardNumber').disabled = false;
	$('vCardSend').disabled	  = false;
	$('vCardMsg').update();


	if ( paiRes.length != undefined ){ return false; }

	/* Solving some problems with members names coming from PAi */
	paiRes['nome']       =    !paiRes[   'nome'] ? paiRes[      'name'] : paiRes[      'nome'];
	paiRes['picture']    =    !paiRes['picture'] ? paiRes[ 'image:low'] : paiRes[   'picture'];
	paiRes['heading']    =    !paiRes['heading'] ? paiRes[  'headings'] : paiRes[   'heading'];
	paiRes['postalcode'] = !paiRes['postalcode'] ? paiRes['postalCode'] : paiRes['postalcode'];

	if(!paiRes['fullAddress']){
		paiRes['fullAddress'] = paiRes['streetAddress'] + '<br \/>' + paiRes['postalcode'];
	}

	paiRes['email'] = paiRes['email'] || paiRes['homeEmail'] || paiRes['otherEmail'] || paiRes['emailAddresses'];


	/* Close all the details */
	closeDetails();


	/* Start populating with data */
	$('d_quem').update( paiRes['nome'] );

	if( paiRes['slogan'] ){
		abrir('d_slogan');
		$('d_slogan').update( paiRes['slogan'] );
	}

	if( paiRes['logoUrl'] ){
		abrir('d_logo');
		$('d_logo').update( '<img src="' + paiRes['logoUrl'] + '" alt="Logotipo: ' + paiRes['nome'] + '" \/>' );
	}


	if( paiRes['heading']  != undefined && paiRes['heading'] != ''){
		abrir('d_acti');
		$('d_acti').update( paiRes['heading'] );
	}

	$('d_addr').update( ( ( paiRes['section'] != '' && paiRes['section'] != undefined )?'<i>'+paiRes['section']+'<\/i><br \/>':'' ) + paiRes['fullAddress'] );

	/* Append contacts */
	var contactos = '';
	if(paiRes['mainphone']){
		contactos += '<a class="p_tlf" href="#" title="Ver em tamanho grande" onclick="return tlfPai(paiAddresses[' + paiID + '].name,paiAddresses[' + paiID + '].mainphone, paiAddresses[' + paiID + ']);">' + paiRes['mainphone'] + '<\/a>';
	}
	if(paiRes['mobile']){
		contactos += '<a class="p_tlf" href="#" title="Ver em tamanho grande" onclick="return tlfPai(paiAddresses[' + paiID + '].name,paiAddresses[' + paiID + '].mobile, paiAddresses[' + paiID + ']);">'    + paiRes['mobile']    + '<\/a>';
	}
	if(paiRes['faxNumber']){
		contactos += '<a class="p_fax" href="#" title="Ver em tamanho grande" onclick="return tlfPai(paiAddresses[' + paiID + '].name,paiAddresses[' + paiID + '].faxNumber, paiAddresses[' + paiID + '], 1);">' + paiRes['faxNumber'] + '<\/a>';
	}

	if(paiRes['email']){
		var beaconCode = "preMultiTrack(curPaiRes, 'email address', 'potential contact', '"+ paiRes['email'] + "');beacon(curPaiRes, {'linktype': 'email', 'linkplace': 'resulttab.text'});";

		var strEmail = ( paiRes['email'].length > 19 ? paiRes['email'].substr(0,19) + '...' : paiRes['email'] );
		contactos += '<a onclick="'+ beaconCode +'" class="p_email" href="mailto:' + paiRes['email'] + '" title="' + paiRes['email'] + '">' + strEmail + '<\/a>';
	}

	if(paiRes['pdf']) {
		abrir('paiVerPdf');
		var beaconCode = "beacon(curPaiRes, {'linktype': 'pdfbrochure', 'linkplace': 'resulttab.text'});";
		$('paiVerPdf').update( '<a onclick="'+ beaconCode +'" class="p_pdf" href="' + paiRes['pdf'] + '">detalhes em PDF<\/a>' );
	}

	if(paiRes['website']){
		var beaconCode = "preMultiTrack(curPaiRes, 'website','potential contact','"+ paiRes['website'] + "');beacon(curPaiRes, {'linktype': 'website', 'linkplace': 'resulttab.text'});";

		var strWeb = paiRes['website'].replace(/http:\/\//i,'');
		if( strWeb.length > 19){
			strWeb = strWeb.substr(0,21) + '...';
		}
		contactos += '<a onclick="'+ beaconCode +'" class="p_www" href="' + paiRes['website'] + '" title="' + paiRes['website'] + '">' + strWeb + '<\/a>';
	}

	if (paiRes['website2']) {
		var beaconCode = "preMultiTrack(curPaiRes, 'website','potential contact','"+ paiRes['website2'] + "');beacon(curPaiRes, {'linktype': 'website2', 'linkplace': 'resulttab.text'});";
		var strWeb     = paiRes['website2'].replace(/http:\/\//i,'');

		if( strWeb.length > 19 ){
			strWeb = strWeb.substr(0,21) + '...';
		}

		contactos += '<a onclick="' +beaconCode + '" class="p_www" href="'+ paiRes['website2'] + '" title="'+ paiRes['website2'] +'">' + strWeb + '<\/a>';
	}
	$('d_cont').update( contactos );


	var paginas_p = '';
	if( paiRes['paginas_p'] ){
		$('d_paginas').update( paginas_p );
	}

	var cont=0;
	var hasMap = false;

	if( paiRes['info'] ){
        var paiinfo = paiRes['info'].join(' ');
        var cuttext = false;
        var extratext = '... <a href="http://www.pai.pt/detailssearch.ds?detailsListingId=y%3a' + paiRes['listingid'] + '">Ver mais</a>';
   
        while (paiinfo.length > 1440) {
            cuttext = true;
            paiinfo = paiinfo.substr(0,paiinfo.lastIndexOf(' '));
        }
        if (cuttext) {paiinfo +=  extratext;}
        
		$('infoPai').update(paiinfo);
		abrir('p_more_info', 'paiVerInfo', 'infoPai');
		cont++;
	}

	if( paiRes['latitude'] && paiRes['longitude'] && paiRes['latitude']!="" && paiRes['longitude']!=""){
		fechar('infoPai');
		abrir('p_more_info', 'mapaPai', 'paiVerMapa');
		cont++;
		hasMap = true;
	}

	if( (paiRes['picture']!= undefined && paiRes['picture']!='') || ( paiRes['logo']!= undefined && paiRes['logo']!= "" ) ){
		if( paiRes['logo']!= undefined && paiRes['logo']!= "" ){
			window.clearTimeout(timer['logoFade']);
			var strFade = ( paiRes['picture'] ? 'iniFoto();' : '' );
			$('fotoPai').update( '<img id="logoFade" src="' + paiRes['logo'] + '" alt="Logotipo: ' + paiRes['nome'] + '" onload="resizePaiImg( this, 300, 293 ); ' + strFade + '" style="filter: alpha(opacity:100); opacity:1;"\/>' );
			$('fotoPai').setAttribute('foto', ( paiRes['picture'] ? paiRes['picture'] : paiRes['logo'] ) );
		}
		else{
			$('fotoPai').update( '<img src="' + paiRes['picture'] + '" alt="Foto" onload="resizePaiImg( this, 300, 293 );" \/>' );
			$('fotoPai').setAttribute('foto', paiRes['picture'] );
		}
		abrir('p_more_info','paiVerFoto','fotoPai');
		fechar('infoPai','mapaPai');
		cont++;
		if( paiRes['picture'] && paiRes['logo'] ){
			cont++;
		}
		hasMap = false;
	}

	if( cont>0 ){
		abrir('mainShowBoxPai');
		if( cont==1 ){
			fechar('p_more_info');
		}
	}
	else{
		fechar('paiVerInfo','mainShowBoxPai');
	}

	if( hasMap ){
		openPaiMap();
	}
	objCSS.display = 'block';
     


	return false;
}

function openPaiMap(){ 
paiRes=paiUn;
    if (window.paimap === undefined) {
        paimap = new SAPO.Maps.Map('mapaPai');
    }
    paimap.addControl(new SAPO.Maps.Control.Navigation());
    marker = new SAPO.Maps.Marker(new OpenLayers.LonLat(paiRes['longitude'], paiRes['latitude']), {}, {markerImage: 'http://js.sapo.pt/Assets/Maps/Images/mapas_pin1.png',markerAnchor: new OpenLayers.Pixel(-16, -32),size: new OpenLayers.Size(16, 16)});
    paimap.setMapCenter(new OpenLayers.LonLat(paiRes['longitude'], paiRes['latitude']), 14);
    marker.registerEvent('click', this, function(marker) {marker.openPopup( '<strong>'+paiRes["name"] + '</strong><br> ' +  paiRes["mainphone"] + ' ')});
    paimap.addOverlay(marker);

} 

function openVcard(e){
	var posX = Event.pointerX(e);
	var posY = Event.pointerY(e);

	/* Get the Details box */
	var objCSS      = $('sendVcard').style;
	objCSS.position = 'absolute';
	objCSS.top      = (posY) + 'px';
	objCSS.left     = (posX-15) + 'px';
	abrir('sendVcard');
	$('vCardNumber').focus();
    preMultiTrack(curPaiRes, 'send phone by sms','user action','');
}

function beacon(obj, ev) {

		var rnd = Math.floor(Math.random()*100000000);
		var site_type	= barra == 'pbi' ? 'SAPO%20white' : barra == 'pai' ? 'SAPO%20yellow' : 'SAPO%20WEB%20Yellow';
		var u = 'mfinfo.site_language=pt_PT&random=' + rnd + '&mfinfo.site_type=' + site_type;

		if(!ev['linkplace']) {
				ev['linkplace'] = ((barra == 'pai') ||	(barra == 'pbi') ) ? 'result.link' : 'resulttab.text';
		}

		u += '&mfinfo.linktype='	+ ev['linktype'];
		u += '&mfinfo.linkplace=' + ev['linkplace'];

		if(barra != 'pbi'){
			u += '&mfinfo.show_listingType=business';
		}
		if(obj['mf']){
			u += obj['mf'];
		}

//		var base_url = barra == 'pbi' ? 'http://pbi.pai.pt/moniforce/tracking.html?' : 'http://www.pai.pt/moniforce/tracking.html?';
//		new Image().src = base_url + u;
		new Image().src = '/static/PAi/action?' + u;

}

function lks(a_obj, evt) {
		var params = [];
		/* Ignores Layout Anchors */
		if( (a_obj.href == document.location + "#") || (a_obj.href == document.location)  || (a_obj.href.match(/^javascript/))) { return };
		if(!a_obj.href){ return };
        

		params.push( "u="   + escape(a_obj.href) );
		params.push( "id="  + escape(a_obj.id) );
		params.push( "q="   + escape(keywords) );
		params.push( "ts="  + s_timestamp );
		params.push( "sid=" + query_id );
		params.push( "rid=" + escape( a_obj.getAttribute("accesskey") ) );
		params.push( "b="   + barra );
		params.push( "page=" + page);
		params.push( "location=" + location_dns);
		params.push( "st=" + st);

		/*
		in a prior version the if checked 'escape(a_obj.get....)' which actually impeded it
		from working properly, since the return was an object and thus the request via
		Image().src was never submitted
		*/

	//	if(( a_obj.getAttribute("accesskey") != null ) ||(true)){
           // console.log('accesskey != null');
			params.push( "rt=undefined" );

			/* Layout has 955px of width */
			var dif  = Math.round( (document.body.clientWidth - 955)/2 );
			var posX = ( dif > 0 ? -dif :0) + Event.pointerX(evt);
			params.push( "xy=" + Event.pointerX(evt) + 'x' + Event.pointerY(evt) );

			 new Image().src = "/clk?" + params.join("&"); 
		//	 var log_link = "/clk?" + params.join("&"); 
        //     console.log('log_link: ', log_link);
			/* alert( "/clk?" + params.join("&") ); */
 //   }
		
  // else{
           // console.log('accesskey = null');
	    //params.push( "rt=" + items[ escape( a_obj.getAttribute("accesskey").toString() ) ].title ) ;
//		}
		
}
function iniFoto(){
    var img_tmp = new Image();
    img_tmp.onload=function(){ timer['logoFade'] = window.setTimeout("fadeOutObj('logoFade', null, fimFoto)", 4500); }
    img_tmp.src=$('fotoPai').getAttribute('foto');
}


function fimFoto(){
    var strTimer="timer['logoFade'] = window.setTimeout(\'fadeInObj(\\\''+this.id+'\\\',null,null)\',fade_speed)";
    $('fotoPai').innerHTML='<img id="logoFade" src="' + $('fotoPai').getAttribute('foto') + '" alt="Fotografia" onload="resizePaiImg( this, 300, 293 ); ' + strTimer + '" style="filter: alpha(opacity:0); opacity:0;"/>';
}
function mytoggle(what) { var s = $(what).style; s.display = (s.display == "block"?'none':'block');}




Event.observe(window, 'load', function() {
if (document.getElementById('menu') != null) {
	    var links_topo = (document.getElementById('menu')).getElementsByTagName('a');
  	    for ( var i = 0; i < links_topo.length; i++){
		    if(links_topo[i].className!='more'){
			    links_topo[i].onclick = function(e){
				    /*
				    var ini_barra = this.href.search(/barra\=(.*)\&/i);
				    var end_barra = this.href.search(/\&location/i);
			 	    var barra     = this.href.substring(ini_barra,end_barra).replace(/=/i,'_');
				    ($('test_body')).className = barra;
				    */
				    /* OLD updateHref(obj) */
				    var q = encodeURIComponent( $('searchstr').value );
				    this.href = this.href.replace( /q=[^&]+/, 'q='+q );
				    /*return false;*/
			    }   
		    }
 	    }
    }
});

Event.observe(document, 'click', function (evt,foo) {
		var a = Event.findElement(evt, "A");

		if( typeof(query_id) == 'string' && typeof(a) != 'undefined' ){
			var tgt = Event.element(evt);
            if ((tgt.id == 'setSt') || (tgt.parentNode.parentNode.id =='setSt')){
                setST(to_st, to_st_string);
            }
			lks(a, evt);
		}
		else{
			var tgt = Event.element(evt);
			while ( tgt != document ){
                if(tgt.className) { 
			        switch( tgt.className ){
					    case 'paiDisplayTlf':
					    case 'tool_dialog':
						        return false;
						    break;
					    default:
						        tgt = tgt.parentNode;
						    break;
				    }
                    } else { tgt = tgt.parentNode; }
			}
			fechar(arr_dialog);
		}
} );

/* Delegate clicks inside of results*/

if (document.getElementById('results')) {
    Event.observe( 'results', 'click', resultClick);
}
if (document.getElementById('results_dir')) {
    Event.observe( 'results_dir', 'click', resultClick);
}
if (document.getElementById('tools')) {
    Event.observe( 'tools', 'click', abrirFerramenta);
}





function setCookie(name, value, expires, path, domain, secure) {
    var curCookie = name + "=" + escape(value) +
    ((expires) ? "; expires=" + expires : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
    document.cookie = curCookie;
}

function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else
        begin += 2;
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
        end = dc.length;
    return unescape(dc.substring(begin + prefix.length, end));
}
function setST(st,op) { 
    setCookie('st', st, 'Sun, 17-Jan-2038 19:14:07 GMT;', '/', document.domain);
    $('stInfo').innerHTML = "Prefer&ecirc;ncia guardada, a op&ccedil;&atilde;o <strong>" + op   + "</strong> ser&aacute; usada nas pr&oacute;ximas pesquisas.";
}



function buildVcard(pR) {
        return '&name='
        + SAPO.Utility.Url.base64Encode(pR['name']).replace(/=/g, '')
        + '&mainphone='
        + SAPO.Utility.Url.base64Encode(pR['mainphone']).replace(/=/g, '')
        + '&address='
        +SAPO.Utility.Url.base64Encode(pR['postalcode']).replace(/=/g, '');
}
bar_width = $('main_bar').getWidth();
bar_title_width =  $('bar_title').getWidth();
result_count_width = $('result_count').getWidth();
definition_width = $('definition').getWidth();
if (bar_width > bar_title_width + result_count_width + definition_width) {
    document.getElementById('definition').style.display = 'inline';
}
function emailFormValidation(form) {
   
    if (form.sendmail_from.value == '') {
        return false;
    } 
    if (form.sendmail_to.value == '') {
        return false;
    } 
    if(SAPO.Utility.Validator.mail(form.sendmail_email.value) == false) {
        return false;
    }

    return true;
}

function preMultiTrack(paiRes,linktype,useraction, otherinfo) {

    var mtargs =new Array();
    mtargs.push("'DCSext.show_listingId'",'paiRes.listingid');
    mtargs.push("'DCSext.show_subscriberId'",'paiRes.subscriberId');
    mtargs.push("'DCSext.show_name'",'paiRes.name');
    mtargs.push("'DCSext.show_location'",'paiRes.location');
    mtargs.push("'DCSext.show_heading'",'paiRes._heading');
    mtargs.push("'DCSext.show_postalcode'",'paiRes.postalCode');
    mtargs.push("'DCSext.show_productId'",'paiRes.productId');
    mtargs.push("'DCSext.show_itemCode'",'paiRes.itemCode');
    mtargs.push("'DCSext.show_listingType'",'paiRes.listingType');
    mtargs.push("'DCSext.useraction'",'useraction');

    var site_type="SAPO YELLOW";
    if (barra == 'pbi' ) {
        site_type="SAPO WHITE";
    }
    mtargs.push("'DCSext.site_type'",'site_type');

    linkplace = new Array();
    linkplace['pbi'] = 'sapo pbi rp';
    linkplace['pai'] = 'sapo pai rp';
    linkplace['resumo'] = 'sapo web rp';
    linkplace['directorio'] = 'sapo web rp';

    if ((linktype == 'business name' ) && ( barra != 'resumo') && ( barra != 'directorio')) {
        linktype = 'more details';
    }
    mtargs.push("'DCSext.linktype'",'linktype');

    mtargs.push("'DCSext.linkvalue'",'otherinfo');
     var te='';
     var function_call = 'dcsMultiTrack(';
     for (i=0;i<mtargs.length;i++) {
         function_call += mtargs[i] + ",";
     }
     function_call = function_call.substr(0,function_call.length-1);
     function_call += ')';
     eval(function_call);
}

var havevalues = new Array();
function check_me(input,text) {
    if (input.value == '') {
        input.style.color='#bbb'; 
        input.value = text;
        havevalues[input.id] = 0;
    } else { havevalues[input.id] = 1;}
}
function change_me(input){
    if ((havevalues[input.id] == 0 ) || (input.value == '')){
        input.style.color='#000';
        input.value = '';
    }
}
function check_pbi_form(what, where)
{
    if ((havevalues[what.id] == 0) && (what.value == 'quem')){
        what.value='';
    }
    if ((havevalues[where.id] == 0 ) && (where.value == 'onde')){
        where.value='';
    }
    return true;
}

